简单的Java程序if / else

时间:2018-09-16 15:57:12

标签: java

我对编程很陌生,并且已经通过租用玩具车制作了一个程序。只有一个问题,如果我输入11和16,程序运行正常。但是如果我输入2和4(例如)。 System.out.println("Total time " + (end - beginning));

之后,该程序将不会显示任何内容

从0到7和从17到24的价格点是1 $。 从7到17是2美元。

请帮助!最有可能的是,我搞砸了这种表示法。请显示如何正确编写代码。预先谢谢你!

PS。我只能在“从这里完成”后面的信息中进行修改。而且我不能使用数组,循环等。只能使用基本的东西(如果/ else,<=,!=,int,double,boolean等)

import java.util.Scanner;

public class Car {

  public static void main(String[] args) {
    Scanner clavier = new Scanner(System.in);
    System.out.print("Give an Int as a starting hour : ");
    int beginning = clavier.nextInt();
    System.out.print("Give an Int as an ending time : ");
    int end = clavier.nextInt();

    /*******************************************
     * Complete from here.
     *******************************************/

    int tarif1 = 0;
    int tarif2 = 0;
    int tarif3 = 0;
    int total = tarif1 + tarif3 + (tarif2 * 2); 
    if (((beginning < 0) || (beginning >= 24)) || ((end <= 0) || (end > 24))) {                       
    System.out.println("Time must be within 0 and 24 !");
    } else {
        if ((beginning - end) <= 0) {
    System.out.println("Not enough time !");
    } else {
        if ( beginning > end) {
    System.out.println("Error, beginning > end");
        } else {
            if (beginning > 0) {
                System.out.println("Total time " + (end - beginning));
                if (beginning < 7) {
                    tarif1 = (7 - beginning);                   
                } else {
                    tarif1 = 0; {
                if ((24 - end) <= 7) {
                    tarif3 = (end - 17);
                } else {
                    tarif3 = 0; {
                }
                tarif2 = ((end - beginning) - tarif1 - tarif3);
                System.out.println((tarif1 + tarif3) + " hours in 1 dollar tariff");
                System.out.println(tarif2 + " hours in 2 dollar tariff");
                total = tarif1 + tarif3 + (tarif2 * 2);


    System.out.print("Amount to pay is : " + total);
    System.out.println(" dollar(s).");
            }






    /*******************************************
     * No modifications after this line.
     *******************************************/

    clavier.close();
   }

    }
    }
   }
 }
}

1 个答案:

答案 0 :(得分:0)

在这段代码中

if (beginning < 7) {
    tarif1 = (7 - beginning);                   
} else {

其他部分的右括号用println覆盖所有代码,因此不打印。该程序根本无法实现。您应该尽早将右括号括起来。我不知道您的确切意图,但是请尝试以下操作:

if (beginning < 7) {
    tarif1 = (7 - beginning);                   
} else {
    tarif1 = 0; 
}
if ((24 - end) <= 7) {
    tarif3 = (end - 17);
} else {
    tarif3 = 0; 
}

然后您应该在代码下方删除多余的花括号。

考虑使用 else if 结构并使用适当的缩进,因为这将使您的代码更具可读性,并且将来不易出错。