尝试将if语句值添加到Java中的总答案中

时间:2013-10-27 00:41:55

标签: java if-statement

对Java来说很新,所以试图理解它可能很困难。

无论如何这个问题,作为一项任务的一部分,我必须编写剧院门票控制台应用程序。我差不多完成了我只想添加最后一部分

作为任务的一部分,我们必须询问用户他们是否希望张贴门票,如果是,则会产生一笔费用,该费用将应用于总费用。目前我不确定如何做到这一点。目前我正在使用If和else语句和..你会在下面看到。

   System.out.println ("Do you require the tickets to be posted?\n(£2.34 for post and packing for the entire order)\n(please enter 'Yes' on the next line if you require postage)");
   String postinp = scanner.next();

           if ("Yes".equals(postinp)){
            System.out.println("Postage will be added to your cost" );
           }
            else
            System.out.println("Postage will not be added to your cost");

我正在尝试编码,如果用户输入“是”,那么它会将邮资费用添加到总数中,但在此部分代码中我不确定如何执行此操作。

任何帮助将不胜感激。谢谢!

5 个答案:

答案 0 :(得分:2)

if-statement内,我们需要做的就是将2.34英镑加到程序计算的总金额上。

    public static void main(String args[]) {
       Scanner input = new Scanner(System.in);
       double total = 10.00;
       System.out.println("Do you require the tickets to be posted?\n(£2.34 for post and packing for the entire order)\n(please enter 'Yes' on the next line if you require postage)");

       if ("Yes".equalsIgnoreCase(input.next())) {
          System.out.println("Postage will be added to your cost");
          total = total + 2.34;
       } else
          System.out.println("Postage will not be added to your cost");
   }

答案 1 :(得分:0)

使用scanner.nextLine()而不是scanner.next();

并使用“是”而不是“Ye”

答案 2 :(得分:0)

我要做的是改变

if ("Ye".equals(postinp)) {

if ("yes".equals(postinp.toLowerCase())) {

这样,它对用户输入的内容不敏感,因为否则他们必须完全输入Yes

答案 3 :(得分:0)

您可以在then-else声明

if块中添加更多代码
if ( "Yes".equals(postinp) ) 
{
    this.cost += 2.34 ; // or whatever it is you need to do

    System.out.println("Postage will be added to your cost" );
}
else 
{
    System.out.println("Postage will not be added to your cost");
}

答案 4 :(得分:0)

您似乎需要解决两件事 - 评估答案然后采取相应行动。

试试这个:

String postinp = scanner.next();
if ("Yes".equalsIgnoreCase(postinp)) {
   cost += postage;
   System.out.println("Postage will be added to your cost" );
}
else {
   System.out.println("Postage will not be added to your cost");
}

if块检查结果是否为某种形式的“是”而不考虑大小写。然后它假设costpostage变量(float s)可用并从某处初始化。在“是”的情况下,cost会增加postage

此外,由于您只是在学习它并不是什么大问题,但在某些时候您可能希望将邮资视为常量或配置文件中消耗的值。也许最初的成本也是如此。