读《程序员编程艺术》之自造Java版本-----字符串左移

在本程序中使用了最简单的按位循环转移法,虽然思想简单,但是在实现的过程中还是遇到了一些问题,经过调试最终解决。
/*
* 实现了字符串的左旋转,采用暴力法
* 在输入时,采用in.next以字符串的形式输出,后变化为char
*/
package chatacterShift;

import java.util.Scanner;

public class CharacterShift {
char l[]=new char [5];//字符串长度
int m;//旋转次数
public void GetChar() {
char ll[]=new char [5];
int mm;
String str;
Scanner in =new Scanner(System.in);
System.out.println(“请输入循环的次数”);
mm=in.nextInt();
System.out.println(“请输入要循环的字符串”);
str=in.next();
ll=str.toCharArray();
m=mm;
l=ll;
}
public void ChangeOne() {
char cache;
cache=l[l.length-1];
for (int i = l.length-1; i >0; i–) {
l[i]=l[i-1];
}
l[0]=cache;
}
public void Out() {
for (int i = 0; i < l.length; i++) {
System.out.println(l[i]);//输出字符串
}
}
public static void main(String[] args){
CharacterShift Character=new CharacterShift();
Character.GetChar();
while (Character.m>0) {
Character.ChangeOne();
Character.m–;
}
Character.Out();
}
}

实验结果如下:
请输入K的值
2
输出结果为:
20 9 15 8 2 6 10 5 7 输出结果为:
2 5

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章