-1

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
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Sean
  • 2,890
  • 8
  • 36
  • 78
  • 2
    `1 3 5` is still a single input and you need to handle it with your logic, ex. splitting on spaces. – STT Sep 15 '17 at 08:29
  • you can't do that, instead if you insist you should use the split() method in java. – Deee Sep 15 '17 at 08:31
  • Possible duplicate of [Inputing using Scanner class](https://stackoverflow.com/questions/40651017/inputing-using-scanner-class) – SkrewEverything Sep 15 '17 at 08:32

3 Answers3

4

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);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • 1
    Giving just what the OP wants is not doing any good. It just makes him (lazy) used to asking some easy and repeated questions which can be googled. Pointing to some documentation or posting important points in block quotes really helps him to understand about the topic. The next popular question he is gonna ask is why `.next()` is used after `.nextInt()` to get to next line of input. BTW it's just my opinion based on my Java learning experience. – SkrewEverything Sep 15 '17 at 09:08
0

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 . .
Zain Ul Abidin
  • 2,467
  • 1
  • 17
  • 29
0

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

    }
}