1

我想分别输入我的“盒子”类的长度、宽度和高度。现在我想把它当作一个整数流,然后将它们分别设置为盒子的每个维度。在用户按下0之前,流将被视为i / p。所以我这样写(我只是提到main方法,我单独定义了box类):

public static void main(String args[])
{

    System.out .print("Enter length, breadth and height->> (Press '0' to end the i/p)");
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    while((br.read())==0)
    {
        // What should I write here to take the input in the required manner?
    }
}

PS:我不能使用scanner,consoleDataInputStream. 所以在这里帮助我BufferedReader

4

3 回答 3

2

您不只是使用Scanner是否有特殊原因?它为您标记和解析值:

Scanner sc = new Scanner(System.in);
int width = sc.nextInt();
int height = sc.nextInt();
于 2013-11-05T16:11:12.390 回答
2

Since you indicated you absolutely must use the BufferedReader, I believe one way to do this is to use the BufferedReader#readLine() method instead. That will give you the full line as entered by the user, up to the line termination (either a '\r' or '\n' according to the documentation).

As Zong Zheng Li already said, while the Scanner class can tokenize the input line for you, since you cannot use that, you'll have to do that yourself manually.

At this moment, one way that springs to mind is to simply split on a space (\s) character. So your code might look something like this:

System.out .print("Enter length, breadth and height->> (Press '0' to end the i/p)");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String inputLine = br.readLine(); // get user input

String[] inputParts = inputLine.split("\\s+"); // split by spaces

int width = Integer.parseInt(inputParts[0]);
int height = Integer.parseInt(inputParts[1]);
int breadth = Integer.parseInt(inputParts[2]);

Note that I'm not showing any error or range checking, or input validation, as I'm just showing a general example.

I'm sure there's plenty of other ways to do this, but this is the first idea that popped in my mind. Hope it helps somewhat.

于 2013-11-05T16:22:17.263 回答
0

Maybe you can try this one.

public static void main(String args[])
{
    String input = 0;
    ArrayList<int> list = new ArrayList<int>();
    boolean exit = true;
    System.out.print("Enter length, breadth and height->> (Press '0' to end the i/p)");
    try {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       while((input = br.readLine()!=null && exit)
       { 
         StringTokenizer t = new StringTokenizer(input);
         while(t.hasMoreToken()){
             if(Integer.parseInt(t.nextToken()) != 0){
                list.add(input);
             }
             else{
                exit = false;
             }
         }

       }
       //list contains your needs. 
    } catch(Exception ex) {
       System.out.println(ex.getMessage());
    }
}
于 2013-11-05T16:21:05.030 回答