简体   繁体   中英

For loop that takes user input 5 times

I was to make a for loop that repeats 5 times. Each time it asks you to enter a grade, takes your input using System.in.read();, then says what you entered. For some reason the output looks strange and it isn't working right. The output looks like this:

  • Enter a letter grade for your class
  • (the letter you enter ex. a)
  • Grade entered = a
  • Enter a letter grade for your class
  • Grade entered =

the above repeats 3 times then ends with the "thanks, keep up the good work!" line ^

The output should look like

  • Enter a letter grade for your class
  • (entered letter ex. b)
  • Grade entered = b

And it does this 5 times ^

Sorry if it isn't indented properly or the solution is obvious, new to programming.

   char g; 
        {                           
        for (int x = 0; x < 5; x++) {
        System.out.println("Enter a letter grade for your class"); 
        g = (char) System.in.read();
        System.out.println("Grade entered = " + g); }
    System.out.println("Thanks, keep up the good work!");   }

Some points regarding your code. Firstly, format it correctly. Your problem currently is that your for-loop is only running for the System.out.println statement, and the rest is ignored. Don't omit brackets when you write for-loops, its not a very good habit. Since this is homework, I will not give you the code, but I will give you the code structure:

public class Main {
    public static void main(String[] args) {
        for (int x = 0; x < 5; x++) { //looping 5 times
            System.out.println("Enter a letter grade for your class"); //print statement
            //code here to get character
            System.out.println("Grade entered = " + g);
        }
        //print final statement outside the for-loop.
        System.out.println("Thanks, keep up the good work!"); 
    }
}

Next point: I would not recommend using System.in.read() for reading the input from the console. Reason for this, is because it will include the carriage return when you press 'Enter' - you would need to specifically look out for that in your code. In order to avoid this, use a Scanner , and get the first character of the returned Scanner string using charAt(0) .

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