当我收到不需要的输入时,我再次调用该方法,但在第二次迭代时,字符串上仍然留有一个字符。为什么它不创建一个全新的字符串并替换旧的值?
所以首先我在扫描仪中输入“mmmm”,这会触发 if 语句中的条件并调用createSocial(),然后重新运行循环,然后我输入新的输入 5555。现在这是我没有得到的:当我打印出新的字符串时,它们显示为 5555,但是在循环中打印它们时留下了“m”,为什么?
public class test {
public static String createSocial() {
Scanner sc = new Scanner(System.in);
String social = sc.nextLine();
String digit = social;
System.out.println(social + " SOCIAL");
System.out.println(digit + " DIGIT");
if (social.length() != 4) {
System.out.println("You did not type 4 digits, try again");
createSocial();
}
//check non-integers
while(digit.length() > 0) {
System.out.println( digit.charAt(0) + "<---");
if(Character.isDigit( digit.charAt(0) ) == false) {
System.out.println("You did not type your last 4 digits correctly, try again");
createSocial();
}
digit = digit.substring(1);
}
return social;
}
}
这是我的输出:
enter the last 4 digits of your Social Security number
mmmm //(This is my first input for the scanner)
mmmm SOCIAL
mmmm DIGIT
m<---
You did not type your last 4 digits correctly, try again
5555 //(this is my input for the scanner the second time around)
5555 SOCIAL
5555 DIGIT
5<---
5<---
5<---
5<---
m<---
You did not type your last 4 digits correctly, try again
智慧大石
相关分类