Multiple Scanner Inputs (Java)

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

Multiple Scanner Inputs (Java)

You don't need multiple scanners. one is more than enough

By an input like 1 3 5 you can read that as a whole line(string)

Scanner sc = new Scanner(System.in);
String input1 = sc.nextLine();
System.out.println(input1);

or just get integer by integer

int inputA1 = sc.nextInt();
int inputA2 = sc.nextInt();
int inputA3 = sc.nextInt();
System.out.println("--------");
System.out.println(inputA1);
System.out.println(inputA2);
System.out.println(inputA3);

Reading multiple inputs from Scanner

Your solution does this allready!

If you go through the documentation of scaner you will find out that your code works with different inputs, as long they are integers separated by whitespace and/or line seperators.

But you can optimice your code, to let it look nicer:

public static void main6(String[] args) {
// Ask user input
System.out.println("Enter 6 digits: ");
// New Scanner
Scanner input = new Scanner(System.in);

// Assign 6 variables for each digit
int size=6;
int[] num=new int[size];
for (int i=0;i<size;i++) {
num[i]=input.nextInt();
}
Arrays.sort(num);
// After sorting
// Second highest number is at n-2 position

System.out.println("Second highest Number: " + num[size - 2]);
}

As an additional hint, i like to mention this code still produces lot of overhead you can avoid this by using:

public static void main7(String[] args) {
// Ask user input
System.out.println("Enter 6 digits: ");
// New Scanner
Scanner input = new Scanner(System.in);

// Assign 6 variables for each digit
int size=6;
int highest=Integer.MIN_VALUE;
int secondhighest=Integer.MIN_VALUE;
for (int i=0;i<size-1;i++) {
int value=input.nextInt();
if (value>highest) {
secondhighest=highest;
highest=value;
} else if (value>secondhighest) {
secondhighest=value;
}
}
//give out second highest
System.out.println("Second highest Number: " + secondhighest);
}

if you do not like to point on highest if there are multiple highest, you can replace the else if:

public static void main7(String[] args) {
// Ask user input
System.out.println("Enter 6 digits: ");
// New Scanner
Scanner input = new Scanner(System.in);

// Assign 6 variables for each digit
int size = 6;
int highest = Integer.MIN_VALUE;
int secondhighest = Integer.MIN_VALUE;
for (int i = 0; i < size - 1; i++) {
int value = input.nextInt();
if (value > highest) {
secondhighest = highest;
highest = value;
} else if (secondhighest==Integer.MIN_VALUE&&value!=highest) {
secondhighest=value;
}
}
// give out second highest
System.out.println("Second highest Number: " + secondhighest);
}

How to iterate multiple String input in Java using the Scanner class

First you will have to decide what is going to be considered The End Of User Input and then act upon that specific condition. In the little example below, if the User enters nothing then that will be considered the End Of User Input.

All the code numbers entered by the User are stored within a List Interface object. Rules have also been applied whereas all code numbers supplied must be numerical and eight digits in length. The String#matches() method is used for this along with a small Regular Expression (regex). Also, there can be no duplicate code numbers supplied, each code number must be unique.

When the User has finished entering the desired Code Numbers then those numbers are sorted in ascending order and displayed within the console window:

System.out.println("Enter the required code numbers (enter nothing when done): ");   
Scanner in = new Scanner(System.in);

List<String> codes = new ArrayList<>();
// Outer loop to keep asking for Code Numbers
while (true) {
boolean isValid = false; // Flag to ensure a valid entry
String codeLine = "";
// inner loop to back up valitity before storing supplied code Number.
while (!isValid) {
System.out.print("Code Line: --> ");
codeLine = in.nextLine().trim();
// Break out of this inner loop if nothing is supplied
if (codeLine.isEmpty()) { break; }
// Is the supplied number all digits and are there 8 of them?
if (!codeLine.matches("^\\d{8}$")) {
// No...
System.err.println("Invalid Code Number! Try Again...");
}
// Has the supplied number already been previously stored?
// In other words, is it unique?
else if (codes.contains(codeLine)) {
// Already got it! Not Unique!
System.err.println("Code Number: " + codeLine + " has already been supplied!");
}
// Passed validity! Set isValid to true so to exit this inner loop.
else { isValid = true; }
}
// Break out of the outer loop is nothing was supplied.
if (codeLine.isEmpty()) { break; }

// Validity has been met so Store the the supplied code number.
codes.add(codeLine);
}
in.close(); // Close the input Stream
System.out.println("Scanner closed");

// Sort the Stored Code Numbers in ascending order.
Collections.sort(codes);

// Display the Stored Code Numbers...
System.out.println("Code Numbers Entered:");
System.out.println(codes);

How to read multiple inputs on same line in Java?

You can do it as follows:

import java.util.Scanner;

public class SecondLargest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter 10 integers separated by single spaces: ");
String str = sc.nextLine();
int last = str.lastIndexOf(" ");
int num = Integer.parseInt(str.substring(0, str.indexOf(" ")));
int largest = num;
int secondLargest = num;
int index = str.indexOf(" ");
for (int i = 1; i < 10; i++) {
str = str.substring(index + 1);
index = str.indexOf(" ");
if (index != -1) {
num = Integer.parseInt(str.substring(0, index));
if (num > largest) {
secondLargest = largest;
largest = num;
}
}
}
System.out.println("The second largest number is: " + secondLargest);
}
}

A sample run:

Enter 10 integers separated by single spaces: 10 23 4 12 80 45 78 90 105 7
The second largest number is: 90

Note: This is just a sample program assuming that the input is in a correct format. I leave it to you to work on how to deal with wrong input. It will be a good exercise for you. Feel free to comment if you need any further help. Best of luck!

Multiple inputs from user using Scanner and arrays

You can have another array for marks and store the marks in the other array. Following code may help.

Scanner sc = new Scanner(System.in);
System.out.print("How many students are there? ");
int n = sc.nextInt();
String [] student = new String[n];
String [] marks =new String[n]; // use another array to store marks

for(int i = 0; i <student.length; i++){
int nextI = i + 1;
System.out.print("Enter name of student " + nextI + ": ");
student[i] = sc.next();
System.out.print("Enter Marks for " + student[i] + ": ");
marks[i]= sc.next(); // store marks for the student
}
System.out.println("StudentName Marks");
for(int i=0;i<student.length;i++) {
System.out.println(student[i]+" "+marks[i]);
}

OUTPUT:

How many students are there? 2
Enter name of student 1: back
Enter Marks for back: 20
Enter name of student 2: door
Enter Marks for door: 30
StudentName Marks
back 20
door 30

This can more effectively be done by Map. Explore yourself to learn more about Map try to implement the above code using Map

How to get multiple inputs using scanner in Java?

Scanner scan = new Scanner("3\n" +
"\n" +
"1 45 5 3 5 Fizz Buzz FizzBuzz Nil\n" +
"\n" +
"4 13 10 2 7 Ba Bi Be Bu\n" +
"\n" +
"49 23 5 5 10 Oong Greeng Kattu Eswah");

ArrayList<String> strings = new ArrayList<>();
ArrayList<Integer> ints = new ArrayList<>();
while(scan.hasNext()){
String word=scan.next();
try {
ints.add(Integer.parseInt(word));
} catch(NumberFormatException e){
strings.add(word);
}
}

scan.close();

System.out.println(ints);
System.out.println(strings);

If you want Scanner scan input from console with System.in then you need some trigger word which will end loop, for example if("exit".equals(word)) break;.

facing issue in java with scanner class while taking multiple input

After you call obj.nextInt(), you still have the EOL from the Return that the user pressed after entering the number sitting in the input buffer, because nextInt() only read the numeric characters. You have to skip those characters by calling obj.nextLine() and just ignoring the result. Then you can go on and ask for additional input from the user.

This gives you what you expected:

Scanner obj = new Scanner(System.in);
String a,b,c;
int x,y,z;
System.out.print("Enter any string: ");
a = obj.nextLine();
System.out.print("enter any int: ");
x = obj.nextInt();
obj.nextLine();
System.out.print("Enter any thing: "); //after getting input for int it ignore next string
b = obj.nextLine();
System.out.print("Enter any thing: ");
c = obj.nextLine();

System.out.println("1: " + b);
System.out.println("2: " + c);

Sample run:

Enter any string: anystring
enter any int: 12345
Enter any thing: anything
Enter any thing: more anything
1: anything
2: more anything


Related Topics



Leave a reply



Submit