2017-09-15 133 views
0

我目前正在學習Java,有一個問題:多掃描器輸入(JAVA)

我知道,用掃描儀將讓我從控制檯接收輸入,但我如何收到一條線路多個輸入,而每行只有一個輸入?

例如:

Enter input: 1 3 5 
+2

'1 3 5'仍然是一個單一的輸入,你需要用你的邏輯處理它,例如。在空間上分裂。 – STT

+0

你不能這樣做,而是如果你堅持你應該在java中使用split()方法。 – Deee

+0

[使用Scanner類輸入]的可能重複(https://stackoverflow.com/questions/40651017/inputing-using-scanner-class) – SkrewEverything

回答

3

你不需要多臺掃描儀。一個是綽綽有餘

更受喜歡1 3 5輸入您可以讀取整個行(串)

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

或只是整數獲得整數

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

給OP想要的東西沒有任何好處。這隻會讓他(懶惰)習慣於提出一些簡單和重複的問題,這些問題可以通過Google搜索。指向一些文檔或在塊引用中發佈重要的點確實有助於他理解該主題。他要問的下一個受歡迎的問題是爲什麼在.nextInt()之後使用'.next()'來到達下一行輸入。順便說一句,這只是我的觀點,基於我的Java學習經驗。 – SkrewEverything

0

您可以使用以下功能這將返回您從掃描儀的多個輸入

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

而且你可以它本身那樣的

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

可以使用nextLine()scanner.Below的方法是示例代碼。

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

    } 
}