Thursday 7 April 2016

java - Scanner not detecting empty line and Counter not accurate



This should be a very basic program but I'm new to Java. I want to be able to input multiple strings into the console using Scanner to detect them. So far I've been able to get the input part right, I wanted the program to run in such a way that the results are displayed when an empty space is entered as opposed to a string. Strangely enough I've only been able to get results when i hit return twice, however, when there are more than 4 inputs hitting return once works. My counter should count the number of "Courses" entered and display them in the results but it gives inaccurate readings.




import java.util.Scanner;

public class Saturn
{

static Scanner userInput = new Scanner(System.in);

public static void main(String[] args)
{


System.out.println("For each course in your schedule, enter its building");
System.out.println("code [One code per line ending with an empty line]");

String input;
int counter = 0;

while (!(userInput.nextLine()).isEmpty())
{
input = userInput.nextLine();

counter++;
}


System.out.println("Your schedule consits of " + counter + " courses");
}
}

Answer



You're calling Scanner#nextLine twice - once in the while loop expression and again in the body of the loop. You can just assign input from the while loop expression. In addition you can use Scanner#hasNextLine to defend against NoSuchElementException occurring:




while (userInput.hasNextLine() && 
!(input = userInput.nextLine()).isEmpty()) {
System.out.println("Course accepted: " + input);
counter++;
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...