簡體   English   中英

Java基本輸入和輸出

[英]Basic input and output in Java

我使用的是NetBeans IDE 7.4,對Java還是很陌生,我試圖讓用戶輸入兩個數字(兩個都是雙精度數字),然后將它們存儲在另一個變量中。 我去過DOZENS的教學網站,但效果不好。 如何獲得基本的輸入和輸出?

原始示例:

import java.util.Scanner;

public class TestIO {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Print something:");    // printing output
        String text = scanner.nextLine();          // taking input

        System.out.println("You have printed the following text: " + text);
    }

}


更新
抱歉,您想參加雙打比賽,這很對。 干得好:

import java.util.Scanner;
import java.util.InputMismatchException;

public class TestIO {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double firstDouble = 0L;
        double secondDouble = 0L;
        while (true) {  // take input (two doubles) until successful
            System.out.println("Print two doubles (press enter after each input):");
            try {
                firstDouble = scanner.nextDouble();
                secondDouble = scanner.nextDouble();
            } catch (InputMismatchException e) {
                System.out.println("Wrong input. You must print doubles.\n" +
                                   "Depending on your locale, as a decimal separator " +
                                   "use either a comma or a dot.\n");
                scanner.nextLine(); // clearing the buffer with the wrong input
                                    // to avoid infinite loop
                continue;
            }
            break; 
        }
        // Printing the user input (limiting doubles to 3 decimal places)
        System.out.format("You have printed %.3f and %.3f %n", 
                          firstDouble, secondDouble);
    }
}

推薦閱讀:

import java.util.*;

public class Test
{
static Scanner console = new Scanner (System.in)
public static void main (String[] args)
{
double input1, input2; // Declares the double value of input1 and input2
input1 = console.nextDouble(); // User inputs value into input1
input2 = console.nextDouble();

String value1 = "" + input1; // Storing value into a String
String value2 = "" + input2;
// If you want to store it in let's say string.
// Or else i think / int value1 = Integer.parseInt(input1);
// This changes the double value into an Int value
// Something like that.
}
}

不太確定這是否是您的問題,因為輸出值也可以

System.out.println(input1); // This outputs the value of input1 on the screen.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM