Page 1 of 1

How to get user input in Java?

PostPosted: Tue Jun 09, 2015 5:44 pm
by ghostheadx2
So, I have an assignment tomorrow. And I wanted to get ahead and try it today (I've been working ahead). Here's the assignment:

Write a program that prompts the user to enter an
integer...
If the number entered is a multiple of 5, print

HiFive

If the number is divisible by 2, print “
HiEven


Here's what I'm trying to do:

Code: Select all
class apples{
   public static void main(String args[]){
      System.out.println("Enter a number: ");
      Scanner number = new Scanner(System.in);
      if (number % 5 == 0){
         System.out.println("HiFive " + number.parseInt());
      }
      else if (number % 2 == 0){
         System.out.println("HiEven " + number.parseInt());
      }
   }
}


However, I get an error saying:

Code: Select all
classExercise.java:4: error: cannot find symbol
      Scanner number = new Scanner(System.in);
      ^
  symbol:   class Scanner
  location: class apples
classExercise.java:4: error: cannot find symbol
      Scanner number = new Scanner(System.in);
                           ^
  symbol:   class Scanner
  location: class apples
2 errors


So, I get two cannot find symbol errors. I'm getting really confused because that's exactly how I saw the Scanner define something in the tutorial. Its making me go crazy. :shock:

Re: How to get user input in Java?

PostPosted: Wed Jun 10, 2015 12:43 am
by ghost107
You forgot to import the Scanner package. Scanner is part of the Java SE library but it is not a build-in type.
Code: Select all
import java.util.Scanner;

Re: How to get user input in Java?

PostPosted: Wed Jun 10, 2015 1:50 am
by Mohanavel
Scanner number = new Scanner(System.in)


This doesn't get any input for you rather you have declared an object of scanner which can be used to get input

here is the code you want

Scanner input = new Scanner(System.in);
int number = input.nextInt();


Replace your Scanner number = new Scanner(System.in) with the above two lines and you get the output...

And dont forget to import

import java.util.*;

Re: How to get user input in Java?

PostPosted: Wed Jun 10, 2015 12:44 pm
by ghostheadx2
I did. It worked. Awesome. :)

Re: How to get user input in Java?

PostPosted: Sun Dec 13, 2015 8:08 am
by PraetG
Sure, that works. But be aware, that this produces a runtime error if you decide to enter a String. You could easily avoid that by typing something like:

Code: Select all
if(number.hasNext()){
      if(number.hasNextInt()){...}
      else
          System.out.println("Please enter an integer value");
}


And maybe put it all in a loop...