Reputation: 73
I have this code:
When I launch it, I am able to get numbers i = 0 to i = 10. However I know this is not the objective of the code as the objective is to reach into the Scanner. But the scanner does not seem to work? Am I making an error importing a file or is this to do with the code? I'm noob.
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] + ".");
}
}
}
Upvotes: 2
Views: 251
Reputation: 1042
I can confirm, that your code works, as long as you change your final output:
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] + ".");
}
Upvotes: 0
Reputation: 1038
One of the first things you can do to make it easier to debug is to make the input fixed between runs. If you change Scanner scIn = new Scanner(System.in);
to this:
Scanner scIn = new Scanner(new BufferedReader(new FileReader("some-file.txt")));
Assuming that some-file.txt
is populated with the appropriate input, then you can run the program multiple times without having to manually re-enter the input. In addition, the input is fixed, so comparing the output of different runs becomes more useful.
Upvotes: 0
Reputation: 201447
Java arrays start at 0 (not 1), and you're printing the same array element twice (in your second for-loop). Finally, you could always use a debugger to help you determine where things are no longer working as you expect.
// 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] + ".");
}
You might also use formatted output (the formatter syntax) like
for (int i = 0; i <= 4; i++) {
System.out.printf("The number of %s is %s.%n", saNames[i], saNumbers[i]);
}
Upvotes: 1