在尝试做一些练习来学习java时,我写了一个简单的程序来计算工作小时数并给出应得的工资。
package horulycalc;
import java.util.Arrays;
import java.util.Scanner;
public class HorulyCalc {
public static void main(String[] args) {
Scanner param = new Scanner(System.in);
String [] titles = {"Developer","Designer","Data Entry","Manager","CEO"};
System.out.println("Hello and welcome to Job Counter");
System.out.println("Please enter you Job Title");
String title = param.nextLine();
while(!Arrays.asList(titles).contains(title)){
System.out.println("Please enter valid Job Title");
title = param.nextLine();
if(Arrays.asList(titles).contains(title)){
System.out.println("Please enter your Hours for this week :");
String count = param.nextLine();
System.out.printf("Your Salary is : $ %f",HoursMath(HourRate(title),Integer.parseInt(count)));
break ;
}
}
}
public static int HourRate(String jobTitle){
int rate = 0;
switch(jobTitle){
case "Developer":
rate = 10 ;
break;
case "Designer":
rate = 8 ;
break ;
case "Data Entry":
rate = 6;
break ;
case "Manager":
rate = 15 ;
break;
case "CEO":
rate = 36;
break ;
}
return rate ;
}
public static float HoursMath(int rate ,int count){
float total ;
total = rate * count ;
return total ;
}
}
如果我第一次添加错误的职位名称,程序运行正常,我的意思是输入不包含在职务名称数组中。
当我第一次输入有效的职位时,例如" CEO"程序中断和netbeans如何完成
答案 0 :(得分:2)
那是因为当用户第一次输入有效值(在你的数组中)时你没有做任何事情。
System.out.println("Please enter you Job Title");
String title = param.nextLine(); // read title..
while(!Arrays.asList(titles).contains(title)){ // while title is not present in array.
}
// nothing here--> what if title is present in the array / list?
//So,Put this code here :. The below lines of code will be executed only hen you have a valid entry.
System.out.println("Please enter your Hours for this week :");
String count = param.nextLine();
System.out.printf("Your Salary is : $ %f",HoursMath(HourRate(title),Integer.parseInt(count)));
break
答案 1 :(得分:1)
由于你的while循环已经测试了有效的标题,你也不应该在循环内测试它。
这更简单:
while(!Arrays.asList(titles).contains(title)){
System.out.println("Please enter valid Job Title");
title = param.nextLine();
}
System.out.println("Please enter your Hours for this week :");
String count = param.nextLine();
System.out.printf("Your Salary is : $ %f",HoursMath(HourRate(title),Integer.parseInt(count)));
你不必以这种方式摆脱循环。一旦你离开了循环,你知道你有一个有效的标题。