2017-03-03 18 views
-2

我已經寫了一個代碼,計算學生獲得的分數的百分比。 while循環無限期運行,即使我已經給出了有效的條件。例如:假設我輸入的科目數= 2,while循環不僅僅停留在2個標記輸入。有人可以請幫忙。無限期雖然循環eventhough我已經給出了有效的條件

代碼:

import java.io.*; 

class student{ 
    int n; 
    int m[]; 
    float percentage; 

    public void calculate(){ 
     int total=m[0]+m[1]; 

     for(int j=2;j<n;j++) 
     { 
      total= total+m[j]; 
     } 
     percentage = total/n;   
     System.out.println("Your percentage equals = "+percentage); 
    }  
} 

public class PercentageCalc{  
    public static void main(String args[]) throws IOException{   
     student s1=new student(); 
     BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); 
     System.out.println("enter the total number of subjects "); 
     s1.n=br.read(); 
     int a=s1.n-1; 
     s1.m=new int[a]; 
     int i=0; 
     System.out.println("Please enter your marks one after another "); 
     while(i<=a) 
     {  
      s1.m[i]=br.read(); 
      i++;     
     }   
     s1.calculate(); 
    }  
} 
+1

不確定?這意味着它仍然有希望結束 - 只要在那裏堅持! – gpasch

+0

我明白了。你很聰明。但如果能幫上忙,那會更好:) – Nan

回答

1

這是因爲br.read()讀取char而不是int,所以ASCII 2等於50 ...所以它不是無限的...只是覺得這樣:)

此外,我認爲你打的每個輸入後「回車」,所以我建議你使用的readLine相反,嘗試下面的代碼主:

public static void main(String args[]) throws IOException{ 

student s1=new student(); 
BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); 
System.out.println("enter the total number of subjects "); 
try{ 
s1.n=Integer.parseInt(br.readLine()); 
}catch(NumberFormatException e) 
{} 
//int a=s1.n-1; // By doing this, you make the array one shorter than you seem to need, so you will not be able to enter the data for the last subject. 
int a=s1.n; //this should have enough space to store marks for all subjects. 
s1.m=new int[a]; 
int i=0; 
System.out.println("Please enter your marks one after another "); 
while(i<a) 
{ 
    try{ 
    s1.m[i]=Integer.parseInt(br.readLine()); 
    }catch(NumberFormatException e) 
    { System.out.println("Bad value entered, please enter again "); // additional check for invalid numbers, just in case ;) 
    continue;} 
    i++; 
} 
s1.calculate(); 
}