Question:
[Java] Strange problems with Scanner?
Connor Lee
2013-10-10 14:52:23 UTC
I am working on an assignment for my computer science class called GroceryList. The program is supposed to ask you how many different items you want to buy, then it asks you the price and quantity of each one, adding the total at the end of each item and the end of the program. My code does this perfectly without issues, but I decided to add an extra feature that asks if you have any more items at the end, before printing the combined total. This extra feature also works as intended but there is one small issue that I can fix, but I feel that there is a better way of doing so that how I fixed it.

Here is the expected output:

Please enter how many items you have: 1
Enter the cost of item #1: 1
Enter the number of item #1: 1

total ==> $1.00

Do you have anymore items? (y/n): y
Enter the cost of item #2: 1
Enter the number of item #2: 1

total ==> $1.00

Do you have anymore items? (y/n): n

Thank you!


Your total food bill ==> $2.00

---------------------------------------------------------------------------------

Here is an example of what happens:

Please enter how many items you have: 1
Enter the cost of item #1: 1
Enter the number of item #1: 1

total ==> $1.00

Do you have anymore items? (y/n):
Do you have anymore items? (y/n): y
Enter the cost of item #2: 1
Enter the number of item #2: 1

total ==> $1.00

Do you have anymore items? (y/n):
Do you have anymore items? (y/n): n

Thank you!


Your total food bill ==> $2.00

----------------------------------------------------------------------------

Here is the GroceryListDriver class (provided by the teacher)

public class GroceryListDriver
{
public static void main( String args[] )
{
GroceryList foodForTheWeek = new GroceryList();
foodForTheWeek.shop();
System.out.print( "\n\n" );
System.out.printf("%35s $%-10.2f", "Your total food bill ==> ", foodForTheWeek.getTotal() );
}
}

---------------------------------------------------------------------------

Here is my GroceryList class

import java.util.Scanner;
public class GroceryList
{
private double totalCost;
public GroceryList()
{

}
public void shop()
{
Scanner inputScanner = new Scanner(System.in);
System.out.print("Please enter how many items you have: ");
int numItems = 0;
numItems = inputScanner.nextInt();
for(int i =0; i< numItems; i++)
{
System.out.print("Enter the cost of item #" + (i+1) + ": ");
double a = inputScanner.nextDouble();
System.out.print("Enter the number of item #" + (i+1) + ": ");
double b = inputScanner.nextInt();
System.out.print("\n" + "\t\t\t\t total ==> ");
System.out.printf("$%.2f", (a*b));
totalCost+=(a*b);
System.out.println();
if(numItems == (i+1))
{
int done = 0;
String anyMore = "duh";
do
{
//String test = inputScanner.nextLine(); <--- This line fixes the problem, but I feel like there is a more proper way to fix it.
System.out.print("\n" + "Do you have anymore items? (y/n): ");
anyMore = inputScanner.nextLine();
switch(anyMore)
{
case "y": case "Y":
numItems++;
done=1;
break;
case "n": case "N":
System.out.println("\n" + "Thank you!");
done=1;
break;
case "": //I added this to attempt to fix the problem
break; //assuming .nextLine() was returning nothing,
//but it doesn't do anything.
default:
break;
}
}while(done==0);
}
}
}
public double getTotal()
{
return totalCost;
}
}

---------------------------------------------------------------------
To me it seems like after hitting the return key to submit the last item's quantity, .nextLine() picks up the same keystroke and returns nothing. Adding the extra .nextLine() for a random variable seemed to patch that up, but I feel like there should be a better way to avoid this issue.
Four answers:
modulo_function
2013-10-10 15:33:13 UTC
I've run into this problem with the way scanner operates



nextLine() returns the entire line and removes the newsline char from the input stream

nextDouble(), nextInt(), etc removes the next token that is that data type but leaves newline chars in the stream.



You will have problems mixing these types of inputs.



The easiest way to avoid the problem is to use nextLine() to read the entire user input through the newline and parse it with

Integer.parseInt(str)

or

Double.parseDouble(str)



> Later versions of Java allow you to switch(..) on a string. But you really should do it the easier way:

char anyMore = inputScanner.nextLine().charAt(0);



and then switch on that char:

case 'Y': case 'y':



Better yet:

char anyMore = inputScanner.nextLine().toUpperCase().charAt(0);



now your case can just be the upper case:

case 'Y':



Hopefully these comments help: I don't really feel like debugging your entire code...

...
Leo D
2013-10-10 22:09:21 UTC
I had this problem when I was learning C++ as well. I don't really use input in Java. I tend to prefer command line options, but basically, Java is reading in the new-line character from "Enter the number of item #1:" as input for "Do you have anymore items? (y/n): "! (I don't know why lol. It's just what it does =Þ)



The way that you fix this, is by calling nextLine() on inputScanner before asking if the user has any more items.
?
2013-10-10 23:11:08 UTC
And simply next with out the line doesn't do it? Since youre only looking for Y or N and not Yes or No





maybe even ditching the variable all together and just use switch(inputScanner.next())

You're never using the variable again, it's not trans-versing a method....



FYI, if it was returning nothing it would have been picked up in "default"... default catches everything else. You may want to consider taking advantage of that. So if for example they say "I like cats smothered in bacon".(or type out Yes/YES etc).. it will catch it in default and ask them again "Y/N!!!!!!" or be like anything besidess y/Y n/N tells them "cant you follow directions! "and tells em to F off.





See link for a slightly modified to work on ideone code

\/ slightly modified\/
godfatherofsoul
2013-10-10 21:57:06 UTC
Is this even compiling? In Java, switch statements don't work with Strings. You have to use integers or chars (so wrap with single quotations).


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...