2016-02-15 43 views
2

我正在幫助某人學習Java。我是一名高級C#開發人員。我瞭解一般的編程,但我不知道Java API。如何以初學者友好的方式從控制檯讀取int?

網絡上關於如何從控制檯讀取int的建議很複雜。它涉及BufferedReaderInputStreamReader等等。這對初學者來說是完全不可理解的。

我想爲他提供一個功能static int readIntFromConsole()這樣做。該功能的內容是什麼?

回答

2

見這個例子

import java.util.Scanner; 

public class InputTest { 

    public static void main(String[] args) { 

     //Now using the readIntFromConsole() 

     int myNumber = readIntFromConsole(); 
     System.out.println(myNumber); 
    } 

    public static int readIntFromConsole() { 
     System.out.print("Enter an integer value...."); 
     Scanner s = new Scanner(System.in); 
     int number = s.nextInt(); 
     return number; 
    } 

} 

//編輯:提供所需的方法

5

嘗試以下操作:

Scanner scanner = new Scanner(System.in); 

System.out.print("Enter some integer:\t"); 

int myIntValue = scanner.nextInt(); 

爲了通過測試應用程序的生命週期使用,你可以做到以下幾點:

public void scanInput() { 

    Scanner scanner = new Scanner(System.in); 

    while (true) { 
     System.out.print("Enter some integer:\t"); 
     int myIntValue = scanner.nextInt(); 
     System.out.print("You entered:\t" + myInteValue); 
    } 
} 
+0

它是安全的實例每次調用一個新的掃描儀?我可以告訴他使用這個:'新的掃描儀(System.in).nextInt()'。 – boot4life

+0

正確的方法是將Scanner類實例化一次,然後在應用程序的整個生命週期中使用它。看到我的答案編輯。 – aribeiro

+0

@ boot4life你不需要每次都實例化一個新的掃描器。只需獲得一個實例,並且每次都能很好地工作。 – Doc

3

你說的是從控​​制臺讀取用戶輸入?在這種情況下,您可以使用Scanner類。

Scanner stdin = new Scanner(System.in); 
int input = stdin.nextInt(); 

如果你想抓住不同的輸入,不需要初始化一個新的掃描儀。在這種情況下,您可以使用與掃描儀不同的方法,具體取決於您想要的值。

System.out.println("Enter a double: "); 
double myDouble = stdin.nextDouble(); 
System.out.println("Enter a string of characters: "); 
String myString = stdin.next(); 
System.out.println("Enter a whole line of characters: "); 
String myEntireLine = stdin.nextLine();