出现的错误:
import java.util.Scanner;
public class tickets {
public static void main(String[] args) {
Scanner stdin=new Scanner(System.in);
System.out.println("Please enter the for family or not ( Y or N ): ");
String family=stdin.nextLine();
String readEnter=stdin.nextLine();
System.out.println("Please enter the number of persons:");
double number=stdin.nextDouble();
stdin.close();
String Y="Y",N="N";
double price,totalprice;
if (family.equals(Y)){
if (number>=1 && number<=2){
price=6.50;
}
if (number>2 && number<7 ){
price=5.50;
}
if (number>6 && number<10){
price=4.5;
}
if (number>=10){
price=4.00;
}
totalprice=price*number;
System.out.println("Tickets for "+number+" family cost "+totalprice+" euros.");
}
if (family.equals(N)){
if (number>=1 && number<=2){
price=6.50;
}
if (number>2 && number<10 ){
price=6.00;
}
if (number>=10){
price=4.0;
}
totalprice=price*number;
System.out.println("Tickets for "+number+" family cost "+totalprice+" euros.");
}
}
}
解决方案:
表面上我的price 和 totalprice 都可以取得到值,但是,如果前面的几条if判断语句均为成功的话,说明price还是没有赋值的!这样就导致错误!!
理由相当于:
int price;
int totalprice=price*10;
而此时price并没有原始初值!所以出错!
判断时,最好使用if else ,这样能保证到price能取到初值!