gpt4 book ai didi

java循环中断与if语句?

转载 作者:行者123 更新时间:2023-12-01 22:48:46 24 4
gpt4 key购买 nike

在尝试做一些学习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

关于java循环中断与if语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24983742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com