0

I have an interesting bug I need to fix. The code is very long and involved, but I'm hoping this can just be an easy question for someone with more experience without having to post it all. In the below code, it will prompt questions and answers. Once I added the double on Weight (so that I can do a calculation later that limits the weight) it started skipping the next question. it will display it, but then the next question will display on the same line and it is not possible to answer the first one. Here is the code:

System.out.print("Enter Item Name: ");
cat.setName(input.nextLine());
System.out.print("Enter Weight(lbs) - Max 25 Tons: ");
cat.setWeight(input.nextDouble());
System.out.print("Enter Value: "); //This is the line that will get skipped
cat.setValue(input.nextLine());
System.out.print("Durability (weak = 1, medium = 2, tough = 3): ");
cat.setDurability(input.nextLine());
System.out.print("Enter ID: ");
cat.setId(input.nextLine());

The output will look like this:

Enter Value: Durability (weak = 1, medium = 2, tough = 3):

Instead of:

Enter Value:
Durability (weak = 1, medium = 2, tough = 3): 

In attempting to debug, I commented out the Value, and the same exact thing will happen to the next line. This tells me it's something to do with the preceding double but I'm not sure how to address it.

Thanks in advance!

Nikolas Charalambidis
  • 29,749
  • 7
  • 67
  • 124
JenInCode
  • 250
  • 2
  • 8

2 Answers2

2

It's not a bug, it's a feature! Unlike nextLine() the nextDouble() doesn't set the position to the beginning of the next line.

Nikolas Charalambidis
  • 29,749
  • 7
  • 67
  • 124
1

I don't have computer in front of me to test this but I'm 99% sure I know what's going on:

The nextDouble presumably reads characters until it finds one that's not partof a double, then leaves the next one on the input buffer. In this case, that means there's a new line sitting on the input buffer after it completes.

Then, when you try to read a line of text, the method looks at the input buffer, sees a newline character immediately, and so returns an empty string.

Daniel McLaury
  • 2,984
  • 8
  • 28
  • That does sound like the issue! Is there any way to get it to not populate that way, or another expression I can use instead of double that will still let me do the math later? – JenInCode Apr 04 '18 at 12:42
  • I'd probably read the double as a string using `newLine` and then convert it to a double separately. – Daniel McLaury Apr 04 '18 at 12:43