无限期虽然循环eventhough我已经给出了有效的条件
问题描述:
我已经写了一个代码,计算学生获得的分数的百分比。 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();
}
}
答
这是因为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();
}
不确定?这意味着它仍然有希望结束 - 只要在那里坚持! – gpasch
我明白了。你很聪明。但如果能帮上忙,那会更好:) – Nan