0

How to get User Input twice in Java?

I learned that, we can use Scanner method to get user input like: Scanner Input = new Scanner(System.in); But what if I need two input from user? When I try: Scanner Runs = new Scanner(System.in); Scanner Overs = new Scanner(System.in); I get an error! What can I do?

11th Oct 2020, 4:33 PM
Professor
Professor - avatar
6 Answers
+ 3
You can get multiple user inputs from the same instance of Scanner. Here is an example: Scanner input = new Scanner(System.in); int x = input.nextInt(); int y = input.nextInt(); You should use at most 1 scanner per input stream so only 1 scanner for System.in.
11th Oct 2020, 4:58 PM
Josh Greig
Josh Greig - avatar
+ 2
You cant do this here in sololearn you have only one input were you can enter text on diffrent lines.
11th Oct 2020, 5:21 PM
D_Stark
D_Stark - avatar
+ 1
Tanvir wrote, "...My question was getting two different inputs, such as Runs, Overs, Balls, Wickets. I wanted to programe a ratio-calculator. Such as Runs per over, Wicket per balls. How can I get Input twice? (I mean, I need two different inputs)" Answer: It would help to see what format of input you want to process. It sounds like this is related to cricket and I don't know even what overs and wickets are. Do you want 4 integers in and just 2 ratios as output? Input in the order of (number of runs) overs balls wickets: 10 5 20 2 Output: Runs over Overs: 2.0 Wicket per balls: 0.1 That would be because 5 / 10 = 2.0. Also 2 / 20 = 0.1. Here is an implementation of the above: Scanner input = new Scanner(System.in); int balls = input.nextInt(); int runs = input.nextInt(); int overs = input.nextInt(); int wickets = input.nextInt(); System.out.println("Runs over Overs: " + (runs * 1.0 / overs)); System.out.println("Wickets per balls: " + (wickets * 1.0 / balls));
11th Oct 2020, 6:24 PM
Josh Greig
Josh Greig - avatar
0
You only need to create one instance of scanner, You need to do the following import scanner class. //this is your object Scanner sc = new Scanner(System.in); //this is the first line of input String line1 = sc.nextLine(); //this is your second line of input String line2 = sc.nextLine(); System.out.print(line1+line2);
11th Oct 2020, 5:03 PM
D_Stark
D_Stark - avatar
0
But guys, that means I can use given the information as many time as I want. My question was not this. My question was getting two different inputs, such as Runs, Overs, Balls, Wickets. I wanted to programe a ratio-calculator. Such as Runs per over, Wicket per balls. How can I get Input twice? (I mean, I need two different inputs)
11th Oct 2020, 5:10 PM
Professor
Professor - avatar
0
Tanvir Mahfuz, can you explain in detail or share your code?
11th Oct 2020, 5:50 PM
Bhavya Ruparelia
Bhavya Ruparelia - avatar