What's wrong with For Loop?

前端 未结 2 1763
失恋的感觉
失恋的感觉 2021-01-28 01:24
package mygradeloops;

import java.io.IOException;

public class MyGradeLoops {

    public static void main(String[] args) throws IOException {
        char x = \'A\';
         


        
相关标签:
2条回答
  • 2021-01-28 01:42

    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.

    0 讨论(0)
  • 2021-01-28 01:58

    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 chars. It would be clearer to use an int for a and loop from 0 until 9.

    0 讨论(0)
提交回复
热议问题