What's wrong with For Loop?

前端 未结 2 1765
失恋的感觉
失恋的感觉 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.

提交回复
热议问题