问题描述
您好,这段代码是我的代码的一部分,该代码应该检查数字字符串是否为回文。 我想从头到尾迭代我的代码,但它根本没有迭代,这是怎么回事? 我在youtube上搜索并意识到了这种情况,人们通常使用do-while循环,因此我试图按照说明进行操作,但是并没有得到我想要的内容。
do {
System.out.println("You passed Catch-Block stage!,Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
这是我的完整代码。
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
char choice;
long firstNum = 0;
firstNum = getLong(" Enter the first number: ",'-');
do {
System.out.println("You passed Catch-Block stage!,Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
public static long getLong(String prompt,char exitChar)
{
long retVal = 0;
boolean validInput = false;
String userInput = "";
Scanner kbd = new Scanner(System.in);
while (!validInput) {
System.out.println(prompt);
try
{
userInput = kbd.nextLine().trim();
if (userInput.length() > 0 && userInput.charAt(0) == exitChar)
{
System.out.println("Ending the program at the user's request");
System.exit(1);
}
retVal = Long.parseLong(userInput);
validInput = true;
}
catch (Exception ex)
{
System.out.println("That is not numeric. Try again or press " + exitChar + "to Quit");
}
}
return retVal;
}
}
解决方法
更改此:
String str = kbd.nextLine().trim();
对此
String str = kbd.next();
,
在读取choice
时,请使用nextLine()
的{{1}}界面:
next()
next()只能读取输入,直到空格为止。它无法读取由空格分隔的两个单词。同样,next()在读取输入后将光标置于同一行。因此,在下一个循环中,它将读取最后一个输入行,该行将为空字符串。