Java嵌套if语句

时间:2016-03-19 16:46:48

标签: java nested-if

我正在使用可实例化的类并在Java中嵌套if语句。当我运行它时,即使输入超过5,它也总是输出500.

夏季: 不到5人是500, 超过5人是400

秋季: 少于5是700, 超过5是600

冬天:不到5个人就是400, 超过5人是300

弹簧: 少于5是200, 超过5是100

public class Seasons{

//data members
private String season;
private int people;
private int cost;

//constructor
public Seasons(){
season="";
people=0;

}

    //set methods
    public void setSeason(String season){
        this.season=season;
    }

    public void setPeople(int people){
        this.people=people;
    }

    //compute method
    public void compute(){
        if(season.equals ("summer")){
            if(people<=5){
                cost=500;
            }
            else{
                cost=400;
            }
        }


        else if(season.equalsIgnoreCase("autumn")){
            if(people<=5){
                cost=700;
            }
            else{
                cost=600;
            }
        }

        else if(season.equalsIgnoreCase("winter")){
            if(people<=5){
                cost=400;
            }
            else{
                cost=300;
            }
        }
        else if(season.equalsIgnoreCase("spring")){
            if(people<=5){
                cost=200;
            }
            else{
                cost=100;
            }


        }
}




    //get method
    public int getCost(){
        return cost;
    }
}

App类:

import javax.swing.JOptionPane;
public class SeasonsApp{
    public static void main(String args[]){

        //declare variables
         String season;
         int people;
         int cost;

         //declare objects
         Seasons mySeasons;

         //create objects
         mySeasons=new Seasons();

         //input
         season=JOptionPane.showInputDialog(null,"what season is it");
         people=Integer.parseInt(JOptionPane.showInputDialog(null,"How many people are going?"));

         //set
         mySeasons.setSeason(season);

         //compute
         mySeasons.compute();

         //get
         cost=mySeasons.getCost();

         //output
         JOptionPane.showMessageDialog(null,"your cost is " + cost + " euro");


    }
}

1 个答案:

答案 0 :(得分:0)

您没有设定人数 添加行

mySeasons.setPeople(people); 

之前

mySeasons.compute();