Is there a clear way of initializing a loop that is terminated when a number is entered as a String?

huangapple go评论71阅读模式
英文:

Is there a clear way of initializing a loop that is terminated when a number is entered as a String?

问题

import java.util.Scanner;

public class PayrollTester {
    public static void main(String[] args) {
        String empID;
        float gross;
        float ste;
        float fed;
        Scanner scnr = new Scanner(System.in);
        System.out.println("Enter your Employee ID: ");
        empID = scnr.nextLine();
        System.out.println("Enter your Gross Pay: ");
        gross = scnr.nextFloat();
        System.out.println("Enter your State Tax Rate: ");
        ste = scnr.nextFloat();
        System.out.println("Enter your Federal Tax Rate: ");
        fed = scnr.nextFloat();

        Payroll empID1 = new Payroll(empID, gross, ste, fed);

        System.out.println("The Net Pay for Employee " + 
        empID1.getEmplyeID() + " is " + empID1.calcNetPay());
    }
}
英文:

So it's been about 6 months since I've done anything with coding as well as I'm still relatively new to it. I'm doing some review and the program asks for several attributes, in which one is a string asking for an employee's ID #. It is supposed be in a loop, in which the loop is terminated when the user enters 0 for their employee ID. I have the program working up until this point and I haven't created the loop yet which is where I am stuck.

`import java.util.Scanner;`
`public class PayrollTester {`
  `public static void main(String[] args) {`
    `String empID;`
    `float gross;`
    `float ste;`
    `float fed;`
    `Scanner scnr = new Scanner(System.in);`
    `System.out.println("Enter your Employee ID: ");`
    `empID = scnr.nextLine();`
    `System.out.println("Enter your Gross Pay: ");`
    `gross = scnr.nextFloat();`
    `System.out.println("Enter your State Tax Rate: ");`
    `ste = scnr.nextFloat();`
    `System.out.println("Enter your Federal Tax Rate: ");`
    `fed = scnr.nextFloat();`

    `Payroll empID1 = new Payroll(empID, gross, ste, fed);`



   `System.out.println("The Net Pay for Employee " + 
    empID1.getEmplyeID() + " is " + empID1.calcNetPay());`
 `}`
`}`

答案1

得分: 2

你可以使用一个 while(true) 循环,然后在他们输入员工编号后紧接着使用一个 if 语句来检查他们输入的值是否等于0。

while(true){
    // 获取他们的员工编号

    if (empiID.equals("0")){
        break;
    }

    // 获取更多用户输入
}
英文:

You can just do a while(true) loop and then you have an if statement right after they enter their employee id that checks to see if the value they entered is equal to 0.

while(true){
    //get their employee id
    

    if (empiID.equals("0")){
        break;
    }

    //get more user inputs
}

huangapple
  • 本文由 发表于 2020年9月11日 02:23:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63835608.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定