2011-11-28 140 views
3

下午好標準控制檯輸入

我只想知道使用java標準控制檯輸入的最簡單方法。例如在C#中,當它來到整型或雙重輸入時,它很簡單。 在java中這樣做最簡單的方法是什麼?

double a; 
     Console.WriteLine("Please enter the value"); 

     a = double.Parse(Console.ReadLine()); 

     Console.WriteLine("thank you for entering " + a); 

親切的問候 阿里安

回答

10

直接翻譯是:

Scanner scan = new Scanner(System.in); 
System.out.println("Please enter the value"); 
double i = Double.parse(scan.nextLine()); 
System.out.println("thank you for entering " + i); 

但你也可以使用Scanner#nextDouble()

Scanner scan = new Scanner(System.in); 
System.out.println("Please enter the value"); 
double i = scan.nextDouble(); 
System.out.println("thank you for entering " + i); 
1
try { 
     InputStreamReader isr = new InputStreamReader(System.in); 
     BufferedReader br = new BufferedReader(isr); 
     String s = br.readLine(); 
     DecimalFormat df = new DecimalFormat(); 
     Number n = df.parse(s); 
    double d = n.doubleValue(); 
    } catch (IOException e) { 
     e.printStackTree(); 
    } catch (ParseException e) { 
     e.printStackTree(); 
    } 

try { 
      InputStreamReader isr = new InputStreamReader(System.in); 
      BufferedReader br = new BufferedReader(isr); 
      String s = br.readLine(); 
      double d = Double.parseDouble(s); 

     } catch (IOException e) { 
     e.printStackTree(); 
     } catch (ParseException e) { 
     e.printStackTree(); 
     } 
+0

他們說,最簡單的方法:) –

+0

也容易:) – erimerturk

1

使用java.util.Scanner - 它支持從STDIN讀取數字。

1

JDK 5.0 &上面提供了從控制檯 - Java.util.Scanner讀取輸入的功能。下面的代碼從控制檯讀取一個字符串和一個整數,並將它們存儲在變量中。

import java.util.Scanner; 
public class InputExp { 
    public static void main(String[] args) { 
     String name; 
     int age; 
     Scanner in = new Scanner(System.in);

// Reads a single line from the console 
    // and stores into name variable 
    name = in.nextLine(); 

    // Reads a integer from the console 
    // and stores into age variable 
    age=in.nextInt(); 
    in.close();    

    // Prints name and age to the console 
    System.out.println("Name :"+name); 
    System.out.println("Age :"+age); 

}}

1

試試這個

BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
     System.out.println("Please enter the value");  
     double a = in.readDouble(); 
     System.console().writer().println("thank you for entering " + a); 
+0

PS:加進口java.io. *; –