简体   繁体   English

如何通过BufferedReader加载String?

[英]How to load String by BufferedReader?

I need to load in a given String which will be type in as an input String: 我需要加载给定的String,将其作为输入String输入:

             20 6
             ....................
             ..XXXXX..XXX.XXX..X.
             ..X.X.X..X.XXX.X..X.
             ..XXXXX..XX.X..X....
             ..XX......XXXXXX..X.
             ....................

something like that. 这样的事情。 It contains 2 integers and a String with "." 它包含2个整数和一个带“。”的字符串。 and "X" Now I just want to ask 2 questions: 1)I need to load the 2 integers first,but how can get the first two integers by BufferedReader?(the 2 int is divide by space between each other and the rest) 和“ X”现在我只想问两个问题:1)我需要先加载2个整数,但是如何通过BufferedReader获得前两个整数?(2个int被彼此之间的空间除以其余的)

2)Then after loading the two integers,how can I load the following rest string char by char?(Like everytime I need to just load one char,then I go to some function,then come back and load the next char;and between there is no blank space) 2)然后加载两个整数后,如何按char加载下面的其余字符串char?(就像每次我只需要加载一个char一样,然后转到某个函数,然后返回并加载下一个char;没有空格)

Here is part of my code: 这是我的代码的一部分:

       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       String str=br.readLine();
       number1 = Integer.parseInt();
       number2 = Integer.parseInt();

And now I don't know how to continue...Anyone can help me to load it? 现在我不知道如何继续...任何人都可以帮助我加载它?

For 1) you just need to do a split 对于1),您只需要进行split

 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   String str=br.readLine();
   String ints[] = str.split(" ");
   number1 = Integer.parseInt( ints[0] );
   number2 = Integer.parseInt( ints[1] );

Then for 2) once you have a String you can have it length and so get them char by char ;) 然后对于2)一旦有了字符串,就可以将其长度设置为char,然后按char进行获取;)

String lol = "......XXX..XX...";
for( int i = 0; i < lol.length(); i++ )
    System.out.println(lol.charAt(i));

With this you will get all your string char by char 有了这个,您将按字符获取所有字符串char

It is much better if you use Scanner then you can read int and the String easier. 如果使用Scanner会更好,那么您可以更轻松地读取int和String。 I suppose you input two integers as col and row. 我想您输入两个整数作为col和row。 Example like this: 像这样的例子:

Scanner scan = new Scanner(System.in);
int col = scan.nextInt();
int row = scan.nextInt(); //input two int first
scan.nextLine();
for(int i = 0; i < row; i++) { 
    String s = scan.nextLine();
    for(int j = 0; j < col; j++) {
        char c = s.charAt(j);
        //your code here
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM