What's wrong with For Loop?

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

提交回复
热议问题