我有这段代码:
当我启动它时,我能够得到数字i = 0到i = 10.但是我知道这不是代码的目标,因为目标是进入扫描仪。但扫描仪似乎不起作用?我是在导入文件时出错还是与代码有关?我是诺布。
package buggyProgram;
import java.util.Scanner;
public class BuggyProgram {
/**
* The main method of the program. This is where it all starts.
*/
public static void main(String[] args) {
String[] saNames = new String[5];
String[] saNumbers = new String[5];
Scanner scIn = new Scanner(System.in);
for (int i = 0; i <= 4; i++) {
System.out.print("Enter name: ");
saNames[i] = scIn.nextLine();
System.out.print("Enter number: ");
saNumbers[i] = scIn.nextLine();
}
System.out.println();
for (int i = 1; i < 4; i++) {
System.out.println("The number of " + saNames[i] + " is "
+ saNames[i] + ".");
}
}
}
答案 0 :(得分:1)
Java数组从0(而不是1)开始,并且您打印两次相同的数组元素(在第二个for循环中)。最后,您始终可以使用调试器来帮助您确定不再按预期工作的位置。
// for (int i = 1; i < 4; i++) {
for (int i = 0; i <= 4; i++) { // <-- to match your first loop.
System.out.println("The number of " + saNames[i] + " is "
+ saNumbers[i] + ".");
}
您也可以使用格式化输出(formatter syntax),如
for (int i = 0; i <= 4; i++) {
System.out.printf("The number of %s is %s.%n", saNames[i], saNumbers[i]);
}
答案 1 :(得分:0)
为了使调试更容易,您可以做的第一件事就是在运行之间修改输入。如果您将Scanner scIn = new Scanner(System.in);
更改为:
Scanner scIn = new Scanner(new BufferedReader(new FileReader("some-file.txt")));
假设some-file.txt
填充了适当的输入,那么您可以多次运行程序,而无需手动重新输入输入。此外,输入是固定的,因此比较不同运行的输出会变得更有用。
答案 2 :(得分:0)
我可以确认,只要您更改最终输出,您的代码就可以运行:
String[] saNames = new String[5];
String[] saNumbers = new String[5];
Scanner scIn = new Scanner(System.in);
for (int i = 0; i <= 4; i++) {
System.out.print("Enter name: ");
saNames[i] = scIn.nextLine();
System.out.print("Enter number: ");
saNumbers[i] = scIn.nextLine();
}
System.out.println();
for (int i = 1; i < 4; i++) {
System.out.println("The number of " + saNames[i] + " is "
+ saNumbers[i] + ".");
}