0

I just started learning java and I want to make a simple program where it requests the persons name, outputs the name then asks for the thier favorite number. It will then compare their number to the number 6 and will output something depending on if the number is larger or smaller than 6.

I am getting a "String to int convert" error in Netbeans which has to do with the scanner. Hopefully I am asking this correctly but how can I make the scanner pick-up integers? Thanks

package javaapplication2; import java.util.Scanner; import java.lang.String; public class JavaApplication2 { public static void main(String[] args) { // Creating an instance of the scanner class. // Gets name and numbers. Scanner getName = new Scanner(System.in); Scanner getNumber = new Scanner(System.in); //Holds name and number String userName; int userNumber; // Asks for the users name. // Holds name in userName. System.out.println("What is your name?"); userName = getName.nextLine(); //Reponds with the users name. System.out.println("Hello" + userName + "!"); //Asks for favorite number. // Holds number in userNumber. System.out.println("What is your favorite number?"); userNumber = getNumber.nextLine(); // Checks if users number is larger than 6. if (userNumber > 6) { // Stuff goes here. } } } 
1

2 Answers 2

6

You should use only one Scanner for one input stream:

Scanner in = new Scanner(System.in); 

And after that you should use it's methods to get integers:

String name = in.nextLine(); int number = in.nextInt(); 

To be sure, you should read the documentation for Scanner:

  1. Scanner
  2. Scanner::nextLine
  3. Scanner::nextInt
Sign up to request clarification or add additional context in comments.

2 Comments

Oh! I didnt know I could use one scanner as one input stream for all. Thanks
Need to wait 8 minutes. Thanks a lot though. I probably should read the docs. Im just reading a random Java book I have and looking at some code then changing it.
0

This might help: Javadoc page for Scanner.

3 Comments

Just pointing the documentation is OK for comments, but is not real answer.
I believe it is an answer. I checked for the answer to the OP's question on the page - having to work it out themselves given the documentation is beneficial for answering their own questions in the future. Is it a followed convention to not provide documentation in an answer, or what?
Yes, it is, you can give link to documentation in a comment, if you like (when you have enough reputation)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.