我正在尝试计算学生成绩的平均值:
import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
int mark;
int countTotal = 0; // to count the number of entered marks
int avg = 0; // to calculate the total average
Scanner Scan = new Scanner(System.in);
System.out.print("Enter your marks: ");
String Name = Scan.next();
while (Scan.hasNextInt())
{
mark = Scan.nextInt();
countTotal++;
avg = avg + ((mark - avg) / countTotal);
}
System.out.print( Name + " " + avg );
}
}
答案 0 :(得分:5)
这是一个使用两个Scanner
的解决方案(如previous answer中所述)。
Scanner stdin = new Scanner(System.in);
扫描用户的输入Scanner scores = new Scanner(stdin.nextLine());
会扫描包含得分的行另请注意,它使用更简单,更易读的公式来计算平均值。
Scanner stdin = new Scanner(System.in);
System.out.print("Enter your average: ");
String name = stdin.next();
int count = 0;
int sum = 0;
Scanner scores = new Scanner(stdin.nextLine());
while (scores.hasNextInt()) {
sum += scores.nextInt();
count++;
}
double avg = 1D * sum / count;
System.out.print(name + " " + avg);
示例输出:
Enter your average: Joe 1 2 3
Joe 2.0
答案 1 :(得分:4)
因为它仍然位于while
循环中,等待指令突破循环。
这是一个Sun tutorial on the subject。您获得的课程材料也应该包含此信息。
答案 2 :(得分:1)
在我之前的帖子(previous answer)中,我表示您需要在输入数字后按Ctrl + D. Ctrl + D向您的程序发出信号,表示没有更多输入。
尝试输入:
WM 1 2 3 6
然后按Ctrl + D
答案 3 :(得分:0)
您应该使用getline并接受“退出”字符串。 String.split和一些Integer.valueOf的东西使用Java编写的字符串文字解析数字很容易。
答案 4 :(得分:0)
这个怎么样?
import java.util.Scanner;
public class Average{
public static void main(String[] args)
{
int mark = 0;
int countTotal = 0; // to count the number of entered marks
int avg = 0; // to calculate the total average
Scanner scan = new Scanner(System.in);
System.out.println("Enter student name: ");
String name = scan.next();
System.out.println("Please enter marks one by one?");
while(scan.hasNextInt()){
int tempMark = scan.nextInt();
mark += tempMark;
countTotal+=1;
System.out.println("If you are done with mark, type \"Done!\"");
}
avg = mark/countTotal;
System.out.print( name + " " + avg );
}
}