• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why is this code ending before printing out the sum?  RSS feed

 
Anthony Richardson
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For some reason it allows me to input both integers but it does not print out the Sum or 'Test' at the end. Please help!
 
Naziru Gelajo
Ranch Hand
Posts: 175
1
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, a couple of things please use the [code][/code] html built-in tags when posting code. They are located within the code posting interface. Also, I can attribute the reason why the code ends is due to the Scanner class and the way it handles input.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16058
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch Anthony. Being a moderator of these forums, I've added the code tags that Naziru was talking about. See how much better your code looks?

The problem with your code is that you are calling nextInt() on your Scanner objects multiple times. Each time you call that method, the Scanner is going to read a new integer.

Instead of calling the method multiple times, call it once when you want the user to enter a number, and then save the result in a variable. Then use that variable later when you want to display what the user entered.

Also, you don't need two Scanner objects A and B. You can use just one Scanner object. Finally, when you have a Scanner that reads from System.in, you should not close it (lines 15 and 16).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!