【发布时间】:2021-11-09 00:36:08
【问题描述】:
程序概述:向用户询问短语,询问用户一个索引,其中一个打乱将旋转短语,直到索引处的字母是字符串的第一个索引 (0)。要求一个整数,直到给出一个整数。词组打乱后要求再打乱。如果是,则打乱输入的索引,如果不是,打印最终结果结束程序。
代码:
import java.util.Scanner;
public class PJ {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String phrase;
String phraseMut;
int index = 0;
System.out.println("Enter your word or phrase: ");
phrase = scan.nextLine();
phraseMut = phrase;
System.out.println();
while (true) {
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
index = scan.nextInt();
scan.nextLine();
break;
} else if (index > phraseMut.length()) {
System.out.println("Error: Index is out of bounds.");
System.out.println("Please enter an integer value.");
} else {
System.out.println("Error: Index is not Integer.");
}
}
System.out.println();
System.out.println("Rotating phrase to bring index "+index+" to the front. . .");
int count =0;
for(int i = 0; i < index; i++){
phraseMut = phraseMut.substring(1,phrase.length())+""+phraseMut.substring(0,1);
count++;
System.out.println(phraseMut);
}
}
}
问题:while 循环无限运行,但我需要它做的是检查它是否为整数,如果是,则离开循环并继续。如果它不是一个整数,则继续请求输入,直到它成为一个整数,如果整数在索引范围内,则与此相同。
【问题讨论】: