java bufferedreader读取另一行之后的行,而不是它下面的行

时间:2015-01-17 11:57:49

标签: java console line bufferedreader

当我使用缓冲重新读取器时,它将跳过一行,然后读取用户输入的输入。有没有办法让它读取控制台中一行之后的内容,例如System.out.print();?

示例:"在此输入您的年龄:" (请在此处阅读)

代替:"在此输入您的年龄:"

(在此处阅读)

我不一定需要使用缓冲读取器来处理所有重要事项,我只是希望它能够在行之后阅读,而不是在它之下。

编辑:来自我所处的程序的代码,这是一个很好的例子。

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) {
        int y;
        int z;
        int x = 0;
        String line2 = "empty";
        String line = "empty";

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    BufferedReader br2 = new BufferedReader(
            new InputStreamReader(System.in));
    System.out.println("enter 2 numbers of which the first is larger than the second");
    try {
        line = br.readLine();
    }

    catch (Exception e) {
        e.printStackTrace();

    }
    try {
        line2 = br2.readLine();
    }

    catch (Exception e) {
        e.printStackTrace();

    }

    y = Integer.parseInt(line);
    z = Integer.parseInt(line2);

    if (y < 9 && y > 5 && z > 5 && z < 9) {
        if (y > z) {
            x = (int) ((Math.random() * (y - z)) + z);
        }
        if (z > y) {
            x = (int) ((Math.random() * (z - y)) + y);
        }
    }else System.out.println("only numbers between 5 and 9!");
    int[] getallen = new int[x];
    for (int i = 0; i < x; i++) {
        getallen[i] = (int) ((Math.random() * (y - z)) + z);
        System.out.println(getallen[i]);
    }

}

}

输出:

"enter 2 numbers of which the first is larger than the second
2
5
only numbers between 5 and 9!"

我想要的是什么:

"enter 2 numbers of which the first is larger than the second 2 5
 only numbers between 5 and 9!"

变量名是荷兰语,但它们与我的问题无关。

1 个答案:

答案 0 :(得分:0)

我制作了一个简单的程序,只需将System.out.println(...)更改为System.out.print(...),就可以使用Eclipse。但你有问题要分开数字,例如Enter number(s): 1 2 3会将1 2 3作为一个字符串返回。

因此我建议您使用Scanner来阅读输入,因为它有一个nextInt()方法,您可以不断提取数字(例如Enter number(s): 1 2 3会在一开始就给您致电1,第二次致电2,第三次致电3

示例:

 public static void main(String[] args) {

    int number = 0;
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter number(s): ");
    while(scanner.hasNextInt()) {
        number = scanner.nextInt();
        System.out.println("Number was " + number);
    }   
}