讀《程序員編程藝術》之自造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

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