2 回答

TA貢獻1846條經(jīng)驗 獲得超7個贊
那是因為該sc.nextInt()方法不會讀取您輸入中的換行符,因此您需要調(diào)用sc.nextLine()
從文檔
將此掃描器前進到當前行并返回被跳過的輸入。
此方法返回當前行的其余部分,不包括末尾的任何行分隔符。位置設(shè)置為下一行的開頭。
由于此方法繼續(xù)搜索輸入以查找行分隔符,因此如果不存在行分隔符,它可能會緩沖所有搜索要跳過的行的輸入。
您的代碼現(xiàn)在看起來像:
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條經(jīng)驗 獲得超4個贊
試試這個..你的 sc.nextLine() 在你輸入整數(shù)值后讀取空字符串
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
添加回答
舉報