简体   繁体   中英

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?

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.

The read method for System.in (an InputStream ) only reads one byte of data from the input stream. 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.

The for loop loops twice, and "double prints" Keep going! and 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 . With a BufferedReader you can just call readLine() , and with a Scanner you can call nextLine() .

Also, it's unclear why you are looping from '0' to '9' with char s. It would be clearer to use an int for a and loop from 0 until 9 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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