Java:If语句

Java:If语句,java,Java,我试图为if(student==1,2,3)添加另一个错误 如果他们输入的积分量为0,则显示无效的输入消息 我做错了什么有什么帮助吗 import javax.swing.*; import java.text.*; public class TuitionCost { public static void main(String[] args) { int costHours; int student; String input; double a;

我试图为
if(student==1,2,3)
添加另一个错误
如果他们输入的积分量为0,则显示无效的输入消息

我做错了什么有什么帮助吗

import javax.swing.*;
import java.text.*;

public class TuitionCost {

  public static void main(String[] args) {
    int costHours;
    int student;
    String input;
    double a;
    double b;
    double c;
    DecimalFormat dollar = new DecimalFormat("#,##0.00");

    JOptionPane.showMessageDialog(null, "OCC Tuition Cost Calculation Program", "Tuition Costs at OCC", JOptionPane.INFORMATION_MESSAGE);
    input = JOptionPane.showInputDialog(null, "Are you a:\n1 - College District Residents\n2 - Non-Residents of College District\n3 - Out-of-State and International Students\n\nPlease enter 1, 2 or 3:", "Input", JOptionPane.QUESTION_MESSAGE);
    student = Integer.parseInt(input);

    if (student == 1) {
      input = JOptionPane.showInputDialog(null, "How many credit hours are you taking?", JOptionPane.QUESTION_MESSAGE);
      costHours = Integer.parseInt(input);
      a = costHours * 76.40;
      JOptionPane.showMessageDialog(null, dollar.format(costHours) + " hours at $76.40 per hour yields a tuition of $" + dollar.format(a));
      System.exit(0);
    }

    if (student == 2) {
      input = JOptionPane.showInputDialog(null, "How many credit hours are you taking?", JOptionPane.QUESTION_MESSAGE);
      costHours = Integer.parseInt(input);
      b = costHours * 139.10;
      JOptionPane.showMessageDialog(null, dollar.format(costHours) + " hours at $139.10 per hour yields a tuition of $" + dollar.format(b));
      System.exit(0);
    }

    if (student == 3) {
      input = JOptionPane.showInputDialog(null, "How many credit hours are you taking?", JOptionPane.QUESTION_MESSAGE);
      costHours = Integer.parseInt(input);
      c = costHours * 195.15;
      JOptionPane.showMessageDialog(null, dollar.format(costHours) + " hours at $195.15 per hour yields a tuition of $" + dollar.format(c));
      System.exit(0);
    } else {
      JOptionPane.showMessageDialog(null, "You must enter a 1, 2, or 3.\nPlease Run the program again.", "Invalid Input", JOptionPane.ERROR_MESSAGE);
    }
    System.exit(0);
  }
}
你错过了所有“如果”之间的“其他”。所以你得到了这个流程:

if (1) { ... }
and if (2) { ... }
and if (3) { ... } else { ... }

到处都需要“或”逻辑。

这是因为else将捕获不同于1、2或3的值:

else               
     JOptionPane.showMessageDialog(null, "You must enter a 1, 2, or 3.\nPlease Run the program again.", "Invalid Input", JOptionPane.ERROR_MESSAGE);
     System.exit(0);
您需要添加一个条件来检查0:

if (student == 0){}
如果语法为:

if(student==0){
}else if(student==1){
}else if(student==2){
}else if(student==0){
}else{
//anything else
}

这是编写if-else-if-else语句的正确方法。你错过了“其他”


如果有一组可能的值,最好使用
开关

switch (student) {
    case 0:
        //do stuff
        break;
    case 1:
        //do stuff
        break;
    ...
    default:
        //it's analog of else
        //do stuff
        break;
}

我建议此代码遵循干燥原则。将费率声明为一个
double[]
(),然后使用数组获取每个特定类型学生的值。每个学生的代码非常相似,一个简单的数组将允许主逻辑只写一次

double[] rates = {76.40,139.10,195.15};
student = Integer.parseInt(input);

if(student > 0 && student < 4){
    input = JOptionPane.showInputDialog(null, "How many credit hours are you taking?", JOptionPane.QUESTION_MESSAGE);
    costHours = Integer.parseInt(input);
    if(costHours != 0){
        a = costHours * rates[student];
        JOptionPane.showMessageDialog(null, dollar.format(costHours) + " hours at $" + rates[student] + " per hour yields a tuition of $" + dollar.format(a));
    }else{
        JOptionPane.showMessageDialog(null, "Credit hours cannot be zero.", "Invalid Input", JOptionPane.ERROR_MESSAGE);
    }
    System.exit(0);
}else{
    JOptionPane.showMessageDialog(null, "You must enter a 1, 2, or 3.\nPlease Run the program again.", "Invalid Input", JOptionPane.ERROR_MESSAGE);
}
double[]rates={76.40139.10195.15};
student=Integer.parseInt(输入);
如果(学生>0&&学生<4){
input=JOptionPane.showInputDialog(null,“你修了多少学分?”,JOptionPane.QUESTION\u消息);
costHours=Integer.parseInt(输入);
如果(成本小时数!=0){
a=成本时数*费率[学生];
JOptionPane.showMessageDialog(null,美元格式(costHours)+“每小时$”+费率[学生]+”的小时数产生美元+美元格式(a))的学费;
}否则{
JOptionPane.showMessageDialog(null,“学分不能为零”,“输入无效”,JOptionPane.ERROR_消息);
}
系统出口(0);
}否则{
JOptionPane.showMessageDialog(null,“必须输入1、2或3。\n请再次运行程序。”,“输入无效”,JOptionPane.ERROR\u消息);
}

您可能希望简化处理并将代码分解为多种方法。考虑以下组织:

  • 将取决于学生住所的每小时成本放入一个数组中
  • 创建一个显示消息的方法
  • 创建一个询问问题的方法,获取int响应,并检查响应是否介于min和max之间
  • 然后,您可以将代码调整为更简单一点——例如

    package com.snippet;
    
    import java.text.DecimalFormat;
    import javax.swing.JOptionPane;
    
    public class TuitionCostNew {
    private static TuitionCostNew me;
    
    /** cost per hour for:
     *  college district resident, 
     *  in-state but not college district, 
     *  out of state (including international)
     * 
     */
    private static double[] hourCost = { 76.40, 139.10, 195.15 };
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        me = new TuitionCostNew();
        me.start(hourCost);
    }
    
    /**
     * @param hourCost
     */
    private void start(double[] hourCost) {
        int studentType;
        int creditHours;
        double tuitionCost;
        DecimalFormat dollar = new DecimalFormat("#,##0.00");
    
        showInformationMessage("OCC Tuition Cost Calculation Program","Tuition Costs at OCC");
    
        studentType = inputIntegerDialog(
                "Are you a:\n1 - College District Residents\n2 - Non-Residents of College District\n3 - Out-of-State and International Students\n\nPlease enter 1, 2 or 3:",
                1, 3);
    
        creditHours = inputIntegerDialog("How many credit hours are you taking?", 1, 25);
        tuitionCost = hourCost[studentType-1] * creditHours;
        showMessage(dollar.format(creditHours) + " hours at "
                + hourCost[studentType-1] + " per hour yields a tuition of $"
                + dollar.format(tuitionCost));
    }
    
    /** Show user an informational message pane, including a title for the pane and a message.
     * @param title
     * @param message
     */
    private void showInformationMessage(String title, String message) {
        // TODO Auto-generated method stub
        JOptionPane.showMessageDialog(null, title, message,
                JOptionPane.INFORMATION_MESSAGE);
    }
    
    /** Shoe user a simple message
     * @param message
     */
    private void showMessage(String message) {
        JOptionPane.showMessageDialog(null, message);
    }
    
    /** Ask the user to enter an integer value using the message, where the value must be between min and max
     * @param message
     * @param min
     * @param max
     * @return
     */
    private int inputIntegerDialog(String message, int min, int max) {
        String input;
        int value = -1;
        boolean validAnswer = false;
    
        while (!validAnswer) {
            input = JOptionPane.showInputDialog(null, message, "Input",
                    JOptionPane.QUESTION_MESSAGE);
            value = Integer.parseInt(input);
            validAnswer = value >= min && value <= max;
            if (!validAnswer) {
                String errMessage = "Invalid entry. Enter number between "
                        + min + " and " + max + ". Try again.";
                showMessage(errMessage);
            }
        }
        return value;
    }
    
    package.com.snippet;
    导入java.text.DecimalFormat;
    导入javax.swing.JOptionPane;
    公共课学费{
    私人静态学费;
    /**以下各项的每小时成本:
    *大学区居民,
    *在州立大学而不是大学区,
    *州外(包括国际)
    * 
    */
    私人静态双[]小时成本={76.40、139.10、195.15};
    /**
    *@param args
    */
    公共静态void main(字符串[]args){
    //TODO自动生成的方法存根
    me=新学费成本新();
    me.启动(小时成本);
    }
    /**
    *@param hourCost
    */
    专用作废开始(双[]小时成本){
    int学生型;
    整数小时;
    双学费;
    DecimalFormat dollar=新的DecimalFormat(“0.00”);
    showInformationMessage(“OCC学费成本计算计划”、“OCC学费成本”);
    studentType=InputItemDialog(
    “您是:\n1-大学区居民\n2-大学区非居民\n3-州外和国际学生\n\n请输入1、2或3:”,
    1, 3);
    creditHours=inputIntegerDialog(“你修了多少学分?”,1,25);
    学费成本=小时成本[学生类型-1]*学分时数;
    showMessage(美元格式(creditHours)+“小时数”
    +hourCost[studentType-1]+“每小时产生的学费为美元”
    +美元格式(学费);
    }
    /**向用户显示信息性消息窗格,包括窗格标题和消息。
    *@param title
    *@param消息
    */
    私有void showInformationMessage(字符串标题、字符串消息){
    //TODO自动生成的方法存根
    JOptionPane.showMessageDialog(空、标题、消息、,
    JOptionPane.INFORMATION(信息和消息);
    }
    /**一个简单的消息
    *@param消息
    */
    私有void showMessage(字符串消息){
    showMessageDialog(空,消息);
    }
    /**要求用户使用消息输入一个整数值,其中该值必须介于最小值和最大值之间
    *@param消息
    *@param-min
    *@param max
    *@返回
    */
    私有int-inputIntegerDialog(字符串消息,int-min,int-max){
    字符串输入;
    int值=-1;
    布尔值validAnswer=false;
    而(!validAnswer){
    input=JOptionPane.showInputDialog(空,消息“input”,
    JOptionPane.QUESTION_消息);
    value=Integer.parseInt(输入);
    
    validAnswer=value>=min&&value
    if(student==0){}
    如何。else
    是最后一个
    if
    的一部分。请修复代码格式和缩进。尝试使用else-if。你可能还需要else子句的括号。你真的想识别所有student“类型”使用的模式吗并且只做一次练习。不要把它全部输入多次(我的键盘不会拼写,所以我可以在相同内容的第二或第三个副本上创建错误)。再次。识别学生“类型”之间的差异,在这种情况下,只有小时成本是不同的。所以最佳做法是创建一个小时成本数组,并确定该数组中的索引…然后您只需将其余语句编写一次。您希望简化并避免所有这些if/else构造。查看问题,您将看到student类型仅适用于trols hourly credit cost,它必须是1、2或3。因此:使用一个数组,将student作为索引;使用一个输入法,您可以为其指定一个最小值和最大值以检查错误。这样,您就可以将输入法重新用于其他项目(例如,0到25之间的学分数)如果你可以用另一种方法来减少问题,那么不要使用复数。此外,在请求有效输入时考虑循环,而不是中止并让用户从头开始。
    package com.snippet;
    
    import java.text.DecimalFormat;
    import javax.swing.JOptionPane;
    
    public class TuitionCostNew {
    private static TuitionCostNew me;
    
    /** cost per hour for:
     *  college district resident, 
     *  in-state but not college district, 
     *  out of state (including international)
     * 
     */
    private static double[] hourCost = { 76.40, 139.10, 195.15 };
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        me = new TuitionCostNew();
        me.start(hourCost);
    }
    
    /**
     * @param hourCost
     */
    private void start(double[] hourCost) {
        int studentType;
        int creditHours;
        double tuitionCost;
        DecimalFormat dollar = new DecimalFormat("#,##0.00");
    
        showInformationMessage("OCC Tuition Cost Calculation Program","Tuition Costs at OCC");
    
        studentType = inputIntegerDialog(
                "Are you a:\n1 - College District Residents\n2 - Non-Residents of College District\n3 - Out-of-State and International Students\n\nPlease enter 1, 2 or 3:",
                1, 3);
    
        creditHours = inputIntegerDialog("How many credit hours are you taking?", 1, 25);
        tuitionCost = hourCost[studentType-1] * creditHours;
        showMessage(dollar.format(creditHours) + " hours at "
                + hourCost[studentType-1] + " per hour yields a tuition of $"
                + dollar.format(tuitionCost));
    }
    
    /** Show user an informational message pane, including a title for the pane and a message.
     * @param title
     * @param message
     */
    private void showInformationMessage(String title, String message) {
        // TODO Auto-generated method stub
        JOptionPane.showMessageDialog(null, title, message,
                JOptionPane.INFORMATION_MESSAGE);
    }
    
    /** Shoe user a simple message
     * @param message
     */
    private void showMessage(String message) {
        JOptionPane.showMessageDialog(null, message);
    }
    
    /** Ask the user to enter an integer value using the message, where the value must be between min and max
     * @param message
     * @param min
     * @param max
     * @return
     */
    private int inputIntegerDialog(String message, int min, int max) {
        String input;
        int value = -1;
        boolean validAnswer = false;
    
        while (!validAnswer) {
            input = JOptionPane.showInputDialog(null, message, "Input",
                    JOptionPane.QUESTION_MESSAGE);
            value = Integer.parseInt(input);
            validAnswer = value >= min && value <= max;
            if (!validAnswer) {
                String errMessage = "Invalid entry. Enter number between "
                        + min + " and " + max + ". Try again.";
                showMessage(errMessage);
            }
        }
        return value;
    }