2 回答
TA贡献1846条经验 获得超7个赞
那是因为该sc.nextInt()方法不会读取您输入中的换行符,因此您需要调用sc.nextLine()
从文档
将此扫描器前进到当前行并返回被跳过的输入。
此方法返回当前行的其余部分,不包括末尾的任何行分隔符。位置设置为下一行的开头。
由于此方法继续搜索输入以查找行分隔符,因此如果不存在行分隔符,它可能会缓冲所有搜索要跳过的行的输入。
您的代码现在看起来像:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
sc.nextLine(); // <----- observe this
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
sc.nextLine(); // <----- observe this
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + totalmarks[i];
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++) {
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
}
TA贡献1884条经验 获得超4个赞
试试这个..你的 sc.nextLine() 在你输入整数值后读取空字符串
import java.util.Scanner;
class Student
{//start of class
public static void main(String[] args)
{//start of method main
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
String emp = sc.nextLine();
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i=0;i<n;i++)
{
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
emp = sc.nextLine();
}
int sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + totalmarks[i];//calculating total marks
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++)
{
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
}//end of method main
}//end of class
添加回答
举报