简体   繁体   English

像C ++一样读取Java中的字符?

[英]read characters in java like c++?

I have an input like 我有一个输入像

...
...
..# 

if read in c++ it would be like: 如果用c ++读取,它将像:

int main() {
    char c;

    int n = 9;

    while(n--) {
       cin >> c;
    }
  return 0;
}

but in java I have tried doing: 但在Java中,我尝试这样做:

public static void main(String args[]) {

    Scanner s =  new Scanner(System.in);
    int n = 9;
    char c;
    while(n--) {

        c = s.next().chartAt(0);

    }

}

it skips dots, I mean it only reads the first dot of each line. 它跳过点,我的意思是只读取每行的第一个点。

There is not space between each dot. 每个点之间没有空格。

When I was learning Java a long time ago, I always used this method to read a single character: 很久以前,当我学习Java时,我总是使用此方法读取单个字符:

char c = s.findWithinHorizon(".", 0).charAt(0);

where s is the scanner. s是扫描仪。

After some testing, I found that this doesn't read new line characters! 经过一些测试,我发现它不会读取换行符! So this code works! 因此,此代码有效!

String input = "...\n...\n..#";
Scanner s = new Scanner(input);
for (int i = 0 ; i < 9 ; i++) {
    char c = s.findWithinHorizon(".", 0).charAt(0);
    // do whatever you want with c here
}

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

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