为什么我的扫描仪(system.in)运行两次

时间:2016-04-08 14:07:35

标签: java if-statement

我是java新手,上周一直在自学。我找不到if else语句运行两次的原因。这是整个代码,我知道很简单但仍在努力学习。

package tickets;

import java.util.Scanner;


public class tickets {
public static void main(String[] args) {
//program designed to ask how many visitors
//are in a party of people and work out
//the total cost of the entry tickets.
    double adult = 12.50;
    double consession = 9.90;
    double child = 6.25;
    double percentage = 0.80;

System.out.println("please enter the amount of adults");
Scanner adult1 = new Scanner (System.in);

//adding code that would give a percentage discount for 
//4 adults or more
{   
if ( adult1.nextInt() >= 4
{
double adult2 =( adult1.nextInt() * percentage);
            }else {
double adult2 = (adult * adult1.nextInt());



System.out.println("please enter the amount of consessions");       
    Scanner consession1 = new Scanner (System.in);
            double consession2 = (consession *consession1.nextInt());

    System.out.println("please enter the amount of children");
    Scanner child1 = new Scanner (System.in);
            double child2 = (child * child1.nextInt()); 

    System.out.println( "total"+" " + (adult2 +consession2 + child2) ); 
    System.out.println("hope you enjoy your visit today!");
    //woop woop it works!!!!!!!!!!
        }

    }
}

}

2 个答案:

答案 0 :(得分:3)

你的程序要求两个输入的原因是因为adult1是你的扫描仪的名称,而在你的if语句中条件是用户输入是> = 4然后从用户再次获取一个Integer输入并乘以使用百分比并将其存储在adult2中,而不应按如下方式进行

public static void main(String[] args) 
{

  double adult = 12.50;
  double consession = 9.90;
  double child = 6.25;
  double percentage = 0.80;
  double adult2 = 0.0 // you dont need to redeclare below

  System.out.println("please enter the amount of adults");
  Scanner adult1 = new Scanner (System.in);

    // remove this unneccessary bracket {  
    int num = adult1.nextInt();
    if ( num >= 4)
    {
      adult2 =( num * percentage);
    }
    else
    {
      adult2 = (adult * num);
    }
    System.out.println("Adult2 is " + adult2);
}

答案 1 :(得分:2)

int存储在扫描仪中,并在if和计算中使用该值。您每次拨打nextInt()时都会多次拨打int

输入if或else后,您将等待停止程序的整数类型的更多输入。