+ 2

Getting user input on if else statements

hi there, i've been learning Java for about 3 days, with no experience, so apologies for silly questions. I have been trying to practice the data input and the conditional statements... what am I doing wrong? import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner myVar = new Scanner(System.in); System.out.println(myVar.nextInt()); int age = myVar; if (age < 16) { System.out.println("Too Young"); } else {

19th Mar 2018, 7:47 AM
Chris Stott
Chris Stott - avatar
6 Answers
+ 13
Let we see your code : import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner myVar = new Scanner(System.in); System.out.println(myVar.nextInt()); int age = myVar; if (age < 16) { System.out.println("Too Young"); } else { ****************************** What do this part: 👉System.out.println(myVar.nextInt()); Displays the number you entered. (Note : The number you entered can no longer be used because it is not memorized! ) 👉Let we see next line: int age = myVar; You declared variable "age" as int type of variable. And you're trying to assign it value "myVar". But this is impossible because "myVar" is object of class Scanner (is not number) 👉What you need to do? đŸ”čDeclare and initialize variable "age" before line : System.out.println(myVar.nextInt()); as: int age =myVar.nextInt(); đŸ”čThen line: System.out.println(myVar.nextInt()); replace with: System.out.println(age); Here the code displays your input, but after the input is memorized as the value of variable "age". That is the reason why this line goes after : int age=myVar.nextInt() ; đŸ”čSo, your code will looks like: import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner myVar = new Scanner(System.in); int age = myVar.nextInt(); System.out.println(age); if (age < 16) { System.out.println("Too Young"); } else {
19th Mar 2018, 11:22 AM
LukArToDo
LukArToDo - avatar
+ 3
Int age has to be int age = myVar.nextInt();
19th Mar 2018, 8:24 AM
Sad
Sad - avatar
+ 3
Share your code on code playground for more help. I will see your code in code playground and help you fix code easier.
19th Mar 2018, 8:26 AM
Sad
Sad - avatar
+ 2
import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner myVar = new Scanner(System.in); System.out.printLn("enter your age"); int age = myVar.nextInt(); if (age < 16) { System.out.println("Too Young"); } else { }
19th Mar 2018, 9:56 AM
Farshaad Heydari
Farshaad Heydari - avatar
+ 1
it says it can't use myVar as an integer, so how do I output it as such?
19th Mar 2018, 7:49 AM
Chris Stott
Chris Stott - avatar
+ 1
You are assigning a Scanner to the variable of int type
19th Mar 2018, 12:09 PM
Harsh Raj
Harsh Raj - avatar