[英]For loop that takes user input 5 times
I was to make a for loop that repeats 5 times.我要制作一个重复 5 次的 for 循环。 Each time it asks you to enter a grade, takes your input using System.in.read();, then says what you entered.
每次它要求您输入成绩时,使用 System.in.read(); 获取您的输入,然后说出您输入的内容。 For some reason the output looks strange and it isn't working right.
出于某种原因,输出看起来很奇怪,而且工作不正常。 The output looks like this:
输出如下所示:
the above repeats 3 times then ends with the "thanks, keep up the good work!"以上重复 3 次,然后以“谢谢,继续努力!”结束。 line ^
行^
The output should look like输出应该看起来像
And it does this 5 times ^它这样做了 5 次 ^
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.
您目前的问题是您的 for 循环仅针对 System.out.println 语句运行,其余部分被忽略。 Don't omit brackets when you write for-loops, its not a very good habit.
写for循环时不要省略括号,这不是一个很好的习惯。 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.下一点:我不建议使用
System.in.read()
从控制台读取输入。 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.这样做的原因是因为当您按“Enter”时它会包含回车符 - 您需要在代码中特别注意这一点。 In order to avoid this, use a Scanner , and get the first character of the returned Scanner string using
charAt(0)
.为了避免这种情况,请使用Scanner ,并使用
charAt(0)
获取返回的 Scanner 字符串的第一个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.