【问题标题】:java bufferedreader read line after another line, not under itjava bufferedreader逐行读取,不在其下
【发布时间】:2015-01-17 11:57:48
【问题描述】:

当我使用缓冲阅读器时,它会跳过一行然后读取用户输入的输入。有没有办法让它从诸如 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!"

变量名称是荷兰语,但无论如何它们与我的问题并不真正相关。

【问题讨论】:

  • 它在我的系统(Windows 7,JDK 1.8.0 25)上按你想要的方式工作
  • 如果您可以发布您使用的确切代码,我们会更有帮助。
  • @isuru-buddhika 已编辑

标签: java console line bufferedreader


【解决方案1】:

我编写了一个简单的程序,只需将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);
    }   
}

【讨论】:

  • 请记住:输入 int 以外的任何内容都会给您一个例外。
猜你喜欢
  • 2015-05-14
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
  • 1970-01-01
  • 1970-01-01
  • 2015-10-06
相关资源
最近更新 更多