2016-10-27 3 views
-4
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에 할당되지 않습니다? 잘못된 배열 인덱스를 사용

+0

'y = y ++'는 완전히 중복됩니다. 'y ++'는'y = y + 1'과 같습니다. –

+0

'y = y ++'는'y '를 증가시키지 않습니다. – khelwood

+1

어쨌든'y'의 수정은 무의미합니다. 모든 반복에서'in'을'y'에 할당합니다. 반드시 ** i' **를 대신 배열 인덱스로 사용하고 싶습니다. – Holger

답변

1

는 :

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

y 값은 사용자 입력은, 예를 들어 1 또는 0을 입력하고 number 배열 색인으로 사용합니다. 하지만 사용자가 1 또는 0 만 입력 했으므로 NEVER 배열 인덱스 2, 3, 4 등을 설정 했으므로 정의되지 않은 배열 항목을 출력하려고합니다.

number[i] = 1; 
     ^-- 
0

당신은 아무 소용이없는 다른 카운터 y을 소개하고, 그냥 혼자 i 하나를 유지해야한다.

y의 가능한 값은 0 또는 1이며, 배열의 다른 인덱스는 올바르게 채워지지 않습니다.

현재 코드에 더 나쁜 : 0 1 (그렇지 않으면 0) 제공 한 경우 1이 항상 2가 포함됩니다 (그렇지 않으면 0)

색인을 제공 한 경우 0은 항상 1이 포함됩니다

지수

다른 색인은 절대 채워지지 않으며 항상 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--; 
     } 


    } 
관련 문제