For Loop有什么问题? [英] What's wrong with For Loop?
本文介绍了For Loop有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
package mygradeloops;
import java.io.IOException;
public class MyGradeLoops {
public static void main(String [] args)throws IOException {
char x ='A'; (x ='0'; x <'9'; x ++){
System.out.println(请输入您的一个成绩)。
;
System.in.read();
System.out.println(Keep going!);
$ b code
<这个代码在第一个等级之后保持双重打印。有谁知道它为什么双打印?我已经做了For循环错误?解决方案这是双重打印,因为当你通过按回车键入一个字符,你实际上写了两个字符:你输入的字符,和 \\\
(换行符)。
添加第二个 System.in.read();
调用以读取换行符:
for(x ='0'; x <'9'; x ++){
System.out.println(请输入您的一个成绩。
System.in.read(); //你的字符
System.in.read(); // newline
System.out.println(Keep going!);
$ / code>
另外,初始化 x
到'A'
不需要, char x;
很好。事实上,在这个循环中使用 char
是没有意义的,使用 int
将是首选。
package mygradeloops;
import java.io.IOException;
public class MyGradeLoops {
public static void main(String[] args) throws IOException {
char x = 'A';
for (x='0';x<'9';x++){
System.out.println("Please enter in one of your grades.");
System.in.read();
System.out.println("Keep going!");
}
}
}
This code keeps double printing after the first "grade". Does anyone know why it double prints? Have I done the "For Loop" wrong?
解决方案 It's "double printing" because when you enter a character by pressing return, you're actually writing two characters: the character you typed, and \n
(newline character).
Add a second System.in.read();
call to read the newline character:
for (x='0';x<'9';x++){
System.out.println("Please enter in one of your grades.");
System.in.read(); // your character
System.in.read(); // newline
System.out.println("Keep going!");
}
Also, initializing x
to 'A'
in not needed, char x;
is fine. In fact, it doesn't make sense to use a char
in this loop, using an int
would be preferred.
这篇关于For Loop有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文