[英]java loop break with if statement?
在嘗試做一些練習來學習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完成時如何
這是因為當用戶首次輸入有效值(在您的數組中)時,您沒有執行任何操作。
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
由於您的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)));
您不必以這種方式擺脫循環。 一旦退出循環,就知道您擁有有效的標題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.