+ 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 {
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 {
+ 3
Int age has to be
int age = myVar.nextInt();
+ 3
Share your code on code playground for more help. I will see your code in code playground and help you fix code easier.
+ 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 {
}
+ 1
it says it can't use myVar as an integer, so how do I output it as such?
+ 1
You are assigning a Scanner to the variable of int type