我没有编程很长时间,这是我第一次在程序中声明一个方法并在程序中使用这个方法.简单来说,程序让用户输入一个5位数的邮政编码,我创建的方法检查邮政编码只有5个字符,都是数字.当我在程序中使用该方法时,无论我为zipcode输入什么,while语句都会运行,要求我再次输入我的邮政编码.只有在输入不是五个字符的字符串或不包含数字的字符串时才会发生这种情况.但是,现在即使输入了一个实际的邮政编码也会发生这种情况,让我假设这个方法有问题.我试图在问题中尽可能清楚,但如果需要进一步澄清我可以尝试清理,你可以给予的任何信息将不胜感激.这是我的代码:
import java.util.Scanner;
public class BarCode {
public static void main(String[] args) {
String zipcode;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a 5 digit zipcode: ");
zipcode = in.nextLine();
while (checkInput(zipcode) == false) {
System.out.println("You did not enter a 5 digit zipcode: ");
zipcode = in.nextLine();
} // end while
} // ends main
public static boolean checkInput(String zipcode) {
boolean zipcodeLength = true;
boolean zipcodeDigits = true;
if (zipcode.length() != 5) {
zipcodeLength = false;
} // end if statement
for (int i = 0; i <= zipcode.length(); i++) {
if (!Character.isDigit(i)) {
zipcodeDigits = false;
} // end if statement
} // end for statement
if (zipcodeLength == false || zipcodeDigits == false) {
return false;
} // end if statement
else {
return true;
} // end else statement
} // end checkInput
}
Run Code Online (Sandbox Code Playgroud)
这是你的问题 :
if(!Character.isDigit(i))
Run Code Online (Sandbox Code Playgroud)
应该
if(!Character.isDigit(zipcode.charAt(i)))
Run Code Online (Sandbox Code Playgroud)