【发布时间】:2016-02-03 02:52:39
【问题描述】:
我的问题是,当我运行这个程序时,我必须按 2 两次或 3 次才能运行 else if 语句。我尝试将输入切换为字符串,它也有同样的问题。 (you can ignore all the code except the (sc.nextInt()==1)/(sc.nextInt()==2)/(sc.nextInt()==3)) 这些是我遇到问题的地方。谢谢
Scanner sc = new Scanner(System.in);
int running = 0;
do
{
System.out.println("What would you like to do?");
System.out.println("(1)Enter hourly employee");
System.out.println("(2)Enter commissionary employee");
System.out.println("(3)Terminate program");
System.out.println();
if (sc.nextInt()==1){
System.out.println("Enter their first name. \n");
hour.firstName= sc.next();
System.out.println("Enter their last name. \n");
hour.lastName= sc.next();
System.out.println("Enter their Id #. \n");
hour.id= sc.nextInt();
System.out.println("Enter their wage amount. \n");
hour.wage= sc.nextInt();
System.out.println("Enter how many hours they will be working. \n");
hour.hrs= sc.nextInt();
System.out.println("employee "+ hour.id + "'s name is " + hour.firstName + " "+ hour.lastName + " their id is "+ hour.id);
System.out.println("employee "+ hour.id + "'s wage is " + hour.wage + "$ and will be working "+ hour.hrs +" hours per week.");
running++;
}
//have to type 2 twice here
else if (sc.nextInt()== 2){
System.out.println("Enter their first name. \n");
com.firstName= sc.next();
System.out.println("Enter their last name. \n");
com.lastName= sc.next();
System.out.println("Enter their Id #. \n");
com.id= sc.nextInt();
System.out.println("Enter their base salary. \n");
bcom.baseSalary= sc.nextInt();
System.out.println("Enter their wage commission rate. \n");
com.cRate= sc.nextInt();
System.out.println("Enter their expected gross sales goal. \n");
com.gSales= sc.nextInt();
System.out.println("employee "+ com.id + "'s name is " + com.firstName + " "+ com.lastName + " their id is "+ com.id);
System.out.println("employee "+ com.id + "'s base salary is "+ bcom.baseSalary + "$ their commission rate is \n" + com.cRate + "% and is estimated to make "+ com.gSales +"$ in gross sales.");
running++;
}
//have to type 3 three times here
else if (sc.nextInt()== 3)
{
running++;
}
}while(running < 1);
【问题讨论】:
-
尝试将 running++ 移到 if/else if 块之外。
-
if链的每个分支都会增加running。为什么要循环迭代? -
尝试:
int input = sc.nextInt();,然后是if (input==1)if (input==2)if (input==3) -
@Heron Yang 谢谢。 duffymo 和 elliott frisch 的运行调用是在 if 语句完成后终止循环。谢谢大家。