0

I'm trying to read input in my code but for some reason I can't submit values.

If the input is int, when I enter an integer, nothing happens. I just keep pressing enter. I need mention that I use Intellij Community Edition 2017.1 EAP.

Here is the code:

import java.util.Scanner;

/**
 * Created by David on 21/01/2017.
 */
public class Main {

    public static void main(String[] args) {
        int num;

        Scanner in = new Scanner(System.in);
        System.out.println("Enter a num: ");

        num = in.nextInt();

        System.out.print(num);
    }
}

Output:

Enter a num: 
5
6
3
aasd
1335

What's the problem here?

David Lasry
  • 622
  • 1
  • 11
  • 26
  • Possible duplicate of [How can I read input from the console using the Scanner class in Java?](http://stackoverflow.com/questions/11871520/how-can-i-read-input-from-the-console-using-the-scanner-class-in-java) – David Rawson Jan 21 '17 at 00:40

1 Answers1

0

Currently you are only expecting Integers from the user by using in.nextInt(). What you should do is use in.nextLine() then parse the input based on what it is instead of assuming it to be an Integer.

public static void main(String[] args) {
    String input = "nothing...";

    Scanner in = new Scanner(System.in);
    //take in input until you type "exit"
    while(!input.equals("exit"))
    {
        System.out.println("Enter a num: ");
        input = in.nextLine();
        System.out.println(input); //use println() not print
    }
}
RAZ_Muh_Taz
  • 3,964
  • 1
  • 10
  • 22
  • this works, what exactly do you want it to do when you enter something other than an Integer?? – RAZ_Muh_Taz Jan 21 '17 at 00:10
  • I know it works, but when I enter an integer, nothing happens. It should print the integer in a new line. – David Lasry Jan 21 '17 at 00:21
  • the above code will print whatever was entered by the user regardless of what it is. Why do you need to use nextInt() if all you are doing is printing it back out to console? @DavidLasry – RAZ_Muh_Taz Jan 21 '17 at 00:33
  • you are using print and not println() when you output the input @DavidLasry – RAZ_Muh_Taz Jan 21 '17 at 00:40
  • This code doesn't have a purpose. I simply wrote it because I wanted to play a little bit with the Scanner package. I run the code and then I enter a number and I press Enter. When I press Enter, nothing happens. The code is still running and my input is not received. – David Lasry Jan 21 '17 at 00:44