我该如何修复此代码?

时间:2016-10-27 15:33:53

标签: java

import java.util.Scanner;
import java.util.Arrays;
public class AttendanceManager {

public static void main(String args[]) 
{
    System.out.println("Enter the number of students that are to be recorded.");
    Scanner studentNum = new Scanner(System.in);
    int x = studentNum.nextInt();
    final int number[] = new int[x]; 

    for(int i=0; i<x; i++)
    {
        System.out.println("Enter 1 if the student is present and 0 if the student is not.");
        final Scanner attendance = new Scanner(System.in);
        int inp = attendance.nextInt();
        int y = inp;
        switch (inp)
        {
        case 1:
            number[y] = 1;
            y = y++;
            break;
        case 0:
            number[y] = 2;
            y = y++;
            break;
        default:
            System.out.println("Please enter 1 or 0.");
            i--; 
        }


    }
    System.out.println("Total Students: " + number.length);
    for(int k=0; k<number.length; k++)
    {
        if (number[k] == 1)
        System.out.println("Student " + (k+1) + " is " + "present.");
        else if (number[k] == 2)
        System.out.println("Student " + (k+1) + " is " + "absent.");
        else
        System.out.println("error");
    }
}

}

输出:

Enter the number of students that are to be recorded.
5
Enter 1 if the student is present and 0 if the student is not.
1
Enter 1 if the student is present and 0 if the student is not.
0
Enter 1 if the student is present and 0 if the student is not.
1
Enter 1 if the student is present and 0 if the student is not.
1
Enter 1 if the student is present and 0 if the student is not.
0
Total Students: 5
Student 1 is absent.
Student 2 is present.
error
error
error

为什么最后3个没有被分配到1或0?

2 个答案:

答案 0 :(得分:1)

您正在使用WRONG数组索引:

    int inp = attendance.nextInt();
    int y = inp;
    switch (inp)
    {
    case 1:
        number[y] = 1;
        y = y++;

y是用户输入的值,例如10,然后将其用作number数组索引。但由于用户只输入10,因此您从不设置数组索引234等。 ..所以你试图输出从未定义的数组条目。

应该是

  number[i] = 1;
         ^--

答案 1 :(得分:0)

您正在介绍另一个没有用的计数器y,只需保留i一个。

作为y的可能值,其中0或1,数组的其他索引都不会正确填充。

使用您当前的代码更糟糕的是:

如果提供0,则索引0将始终包含1(否则为0)

如果提供1,则索引1将始终包含2(否则为0)

其他索引永远不会填充,并且始终包含0。

for(int i=0; i<x; i++)
    {
        System.out.println("Enter 1 if the student is present and 0 if the student is not.");
        final Scanner attendance = new Scanner(System.in);
        int inp = attendance.nextInt();
        //int y = inp;
        switch (inp)
        {
        case 1:
            number[i] = 1;
            break;
        case 0:
            number[i] = 2;
            break;
        default:
            System.out.println("Please enter 1 or 0.");
            i--; 
        }


    }