讓我得到的錯誤是0Accesssing櫃檯外,同時循環的Java
I'ts師由於totDrivers
值。我不確定是否因爲計數器沒有更新,因爲while
循環循環。或者,如果這是因爲totDrivers
我不正確地從循環外部訪問變量。
我讀過的其他帖子說,要訪問一個循環外的變量,你需要在循環之外初始化它。但它沒有說明如果通過這樣做,計數器更新值將出來。
[Exception in thread "main" java.lang.ArithmeticException:/by zero
at Statistics.main(Statistics.java:84)]
import java.util.Scanner;
public class Statistics
{
public static void main (String [] args)
{
Scanner in=new Scanner(System.in);
//counters initilization
int f=0; //female
int m=0;//male
int u=0;//unspecified
int u25=0;//less than 25 in age
int mu=0;//male and under 25
int bt=0;//between 25 and 75
int ab=0;//above 75
int y=0;//res
int n=0;//non res
int age=0;
String gender="U";
String nlRes="Y";
int totDrivers=0;
while (age !=0)
{
totDrivers++;
System.out.print("Please enter age\\(Enter 0 if theres no more input\\): ");
age= in.nextInt();
System.out.print("Please enter gender(M,F,or U): ");
gender= in.next();
System.out.print("Please enter gender: ");
nlRes= in.next();
if (age<25)
{
u25++;
}
if(gender.equals("M"))
{
mu++;
}
else if(age>=25&&age<=75)
{
bt++;
}
else if(age>75)
{
ab++;
}
if(gender.equals("M"))
{
m++;
}
else if(gender.equals("F"))
{
f++;
}
else if(gender.equals("U"))
{
u++;
}
if(nlRes.equals("Y"))
{
y++;
}
else if(nlRes.equals("N"))
{
n++;
}
System.out.println("totd"+totDrivers);
}
//output
double perU25=(u25/totDrivers)*100;
double perMU25=(mu/m)*100;
double perF=(f/totDrivers)*100;
double perNonNL=(n/totDrivers)*100;
double perAbove=(ab/totDrivers)*100;
System.out.println("The % of drivers under 25 is : %"+perU25);
System.out.println("The % of male drivers under 25 is : %"+perMU25);
System.out.println("The % of female drives is : %"+perF);
System.out.println("The % of out of province drivers is : %"+perNonNL);
System.out.println("The % of drivers over the age of 75 is : %"+perAbove);
}
}
哪條線失敗的原因?我不認爲第84行是由'totDrivers'劃分的。 –
一個簡單的'if(totDrivers> 0 && m> 0){//在這裏做數學運算}'將解決你的問題。你有沒有想過,也許代碼永遠不會進入你的循環? – bated