虽然我已经给出了有效的条件,但无限期循环

时间:2017-03-03 08:23:20

标签: java

我编写了一个代码,用于计算学生获得的分数百分比。即使我已经给出了有效条件,while循环也无限期地运行。例如:假设我输入的主题数= 2,而while循环不仅仅停止2个标记输入。有人可以帮忙吗。

代码:

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 个答案:

答案 0 :(得分:1)

这是因为br.read()读取char而不是int,因此ascii 2等于50 ...所以它不是无限的...只是感觉如此:)

此外,我假设您在每次输入后都按“Enter”键,因此我建议您使用readLine,尝试使用以下代码作为main:

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();
}