[英]Printing character in java
I'm trying print a given String char by char: 我正在尝试通过char打印给定的String char:
public static void main(String[] args) {
char c;
Scanner scaner = new Scanner(System.in);
int length = scaner.next().length();
System.out.println(length);
int i = 0;
while (i < length) {
c = scaner.next().charAt(i);
System.out.println(c);
i++;
}
}
Once this code has reached int length = scaner.next().length();
一旦此代码达到
int length = scaner.next().length();
it doesn't continue. 它不会继续。 What's causing this?
是什么原因造成的?
You should store the scanned value in the temporary variable. 您应该将扫描的值存储在临时变量中。
char c;
Scanner scaner = new Scanner(System.in);
// Storing scanned value
String nextStr = scaner.next();
int length = nextStr.length();
System.out.println(length);
int i = 0;
while(i < length){
c = nextStr.charAt(i);
System.out.println(c);
i++;
}
In your original code you call next
repeatedly in a loop, but this does not return the original scanned value, but the next line of input. 在原始代码中,您将在循环中重复调用
next
,但这不会返回原始扫描值,而是返回下一行输入。
You need to enter something after calling next(). 您需要在调用next()之后输入一些内容。
As addition too Alexander's answer. 亚历山大的答案也是如此。
The line: int length = scaner.next().length();
这行代码:
int length = scaner.next().length();
gets the next line and then checks the length. 获取下一行,然后检查长度。 So you already got the next line and calling next() again asks for different input.
因此,您已经获得了下一行,并再次调用next()要求输入不同的内容。
That's the reason why you should always store the return value of next() in a variable! 这就是为什么您应该始终将next()的返回值存储在变量中的原因!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.