我是Java编程的初学者,我需要在程序进入for循环之前指出分数。这是一个例子:
如果我输入'4'作为输入,它将声明输入得分4次并获得平均值。
试用代码:
import java.io.*;
public class Exer2{
public static void main(String[] args)throws Exception{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String strinput;
int i;
int x;
x = Integer.parseInt(br.readLine());
System.out.print("Enter number or scores here:");
x = input.nextInt();
for (i = 0; i < x; i++){
System.out.print("Enter score here:");
if (i==0){
strinput = input.readLine();
x=Integer.parseInt(br.readLine()));
}
}
i=(a+b+c)/x;
System.out.println("The average score is " +i);
答案 0 :(得分:1)
阅读完评论后,我能够理解这个问题。
我将如何指示x作为循环的次数,我不知道该怎么开始
保存用户的输入:
System.out.print("Enter # of scores:");
x = Integer.parseInt(input.readLine());
然后在你的循环中:
int scores = 0; //This will hold the sum of the scores
for (i = 1; i <= x; i++)
{
System.out.print("Enter score " + i + ": "); //Ask for new score
scores = scores + Integer.parseInt(input.readLine()); //Add score to existing sum of previous scores
}
System.out.println("The average score is " + scores / x); // Gets the average score and prints to console
答案 1 :(得分:0)
你必须阅读你的输入,使用
x = Integer.parseInt(input.readLine());
可能在重命名变量后(x不是非常明确)