简体   繁体   English

For Loop有什么问题?

[英]What's wrong with For Loop?

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? 我做错了“ For Loop”吗?

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). 这是“两次打印”,因为当您按回车键输入一个字符时,实际上是在写两个字符:您键入的字符和\\n (换行符)。

Add a second System.in.read(); 添加第二个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; 同样,不需要将x初始化为'A'char x; is fine. 很好 In fact, it doesn't make sense to use a char in this loop, using an int would be preferred. 实际上,在此循环中使用char没有任何意义,首选使用int

The read method for System.in (an InputStream ) only reads one byte of data from the input stream. System.inInputStream )的read方法仅从输入流读取一个字节的数据。 Because you must hit "Enter" to send your input to the stream, you have two characters on the stream - the character you typed plus a newline. 因为必须按“ Enter”键才能将输入发送到流,所以流上有两个字符-键入的字符和换行符。

The for loop loops twice, and "double prints" Keep going! for循环循环两次,然后“两次打印” Keep going! and Please enter in one of your grades. 并且Please enter in one of your grades. because each iteration reads one of the two characters on the stream. 因为每次迭代都会读取流中两个字符之一。

It would be easier to wrap System.in in a InputStreamReader then a BufferedReader or just initialize a Scanner with System.in . System.in包装在InputStreamReader然后再包装BufferedReader或者仅使用System.in初始化Scanner会更容易。 With a BufferedReader you can just call readLine() , and with a Scanner you can call nextLine() . 使用BufferedReader您可以仅调用readLine() ,而使用Scanner您可以调用nextLine()

Also, it's unclear why you are looping from '0' to '9' with char s. 同样,还不清楚为什么要使用char s从'0'循环到'9' It would be clearer to use an int for a and loop from 0 until 9 . int用作从09 a and循环会更清楚。

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

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