0
getting user inputs
hi I just started learning java and I am trying to get 2 inputs from user and checking which one is greater . But its throwing me exceptional error. Can someone help? import java.util.Scanner; class myclass{ public static void main(String[] args){ Scanner a=new Scanner(System.in); int var1=a.nextInt(); Scanner b=new Scanner(System.in); int var2=b.nextInt(); if(var1>var2){ System.out.println(var1); } } }
3 Réponses
0
Fixed:
import java.util.Scanner;
public class Main{
private static Scanner sc;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int var1;
int var2;
System.out.println("Enter your first number");
var1 = sc.nextInt();
System.out.println("Enter your second number");
var2 = sc.nextInt();
if(var1>var2){
System.out.println("this number is bigger"+ var1);
}
else{
System.out.println("this number is bigger "+var2);
}
}
}
0
When getting user input you need to initialized the Scanner first:
Scanner sc = new Scanner(System.in);
Then when trying to get user input and placing it into a specialised variable you need to say:
int x;
String y;
String str = "abcdefghijklmnopqrstuvwxyz";
System.out.println("Enter a number");
x = sc.nextInt();
/* this code is telling the compiler to put the imputed integer into this integer variable */
System.out.println("Enter you name: );
y = sc.next();
/* this code is telling the compiler to put the imputed string into this specified string variable */
Scanner SCC = new Scanner(str);
/* this code tells the compiler that the Scanner get the string information from the specified String variable */
0
Hi Amitha,
This is the best and easiest way to do that.
import java.util.Scanner;
class GetInputFromUser {
public static void main(String args[]){
int num1;
int num2;
Scanner in = new Scanner(System.in);
//get input num for first number
System.out.println("Enter first number of choice.");
num1 = in.nextInt();
System.out.println("num 1 is: " +num1);
//getting input num for second num
System.out.println("Enter Second number of choice");
num2 = in.nextInt();
System.out.println("num 2 is: " +num2);
if (num1 > num2) {
System.out.print(num1 + " is greater");
}else{
System.out.print(num2 + " is greater");// this outputs whether the first number is greater or the the second number
}
}
}