简体   繁体   中英

Multiple Scanner Inputs (Java)

I am currently learning Java and had a question:

I know that using Scanner will allow me to receive input from the console, but how do I receive multiple inputs on one line, rather than just one input per line?

For example:

Enter input: 1 3 5

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);

You can use below function that will return you multiple inputs from scanner

public List<String> getInputs(String inputseparator)
{
   System.out.println("You Message here");
   Scanner sc = new Scanner(System.in);
   String line = sc.nextLine();
   return line.split(inputseparator);
}

and you can use it like that

List<String> inputs = getInputs(" ");
//iterate inputs and do what you want to . .

You can use nextLine() method of scanner.Below is sample code.

import java.util.Scanner;

public class Test {
    public static void main(String args[])
 {

        Scanner s = new Scanner(System.in);
        //sample input: 123 apple 314 orange
        System.out.println("Enter multiple inputs on one line");

        String st = s.nextLine();
        s = new Scanner(st).useDelimiter("\\s");
        //once the input is read from console in one line, you have to manually separate it using scanner methods.
        System.out.println(s.nextInt());
        System.out.println(s.next());
        System.out.println(s.nextInt());
        System.out.println(s.next());
        s.close();

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM