2011-02-13 151 views
1

好,所以我在另一个僵局与我的程序。我需要重复它,但我不明白我正在阅读的文字中如何去做。它只涵盖重复的价值,如成绩簿计划。无论如何,我需要程序继续重复,直到用户输入“stop”作为员工姓名。这是我的代码到目前为止:重复程序帮助?

package payroll_program_2; import java.util.Scanner;

public class payroll_program_2 { 
     public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 
     float hours;           
     float rate;            
     String name; 
     float total_pay; 


    System.out.println("Please enter employee name");  
     name = input.nextLine(); 
      if("stop".equals(name)) 
      { return; 
      } 

    System.out.println("Please enter hourly rate");    
     rate = input.nextFloat();        
     if (rate <0)            
      {              
       System.out.println("Pay rate cannot be negative"); 
       System.out.println("Please enter hourly rate"); 
       rate = input.nextFloat(); 
      } 
    System.out.println("Please enter hours worked");    
     hours = input.nextFloat();        
     if (hours <0) 
      { 
       System.out.println("Hours cannot be negative"); 
       System.out.println("Please enter hours worked"); 
       hours = input.nextFloat(); 
      } 
    System.out.println("Employee's total pay for this week"); 
     total_pay = hours*rate;         

    System.out.printf("The total pay for %s is $%.2f\n", name, total_pay);   


     } 

}

回答

1
while (true) {...}
+0

这就是它。这么简单,但我没有从书中得到它。谢谢你们:) – g3n3rallyl0st 2011-02-13 07:07:14

1

你可以简单地包括:

,而(真){

}

在你的代码,并为每个输入说。

if(“stop”.equals(input)) break;

+0

即时尝试做 - while循环,但我想从智慧人士的一些输入比我大声笑。即时通讯品牌新和不知情。它真的很难从书中学到这一点...... – g3n3rallyl0st 2011-02-13 06:41:04

2

您需要添加一个while环或for循环,如:

while (true) { 
    // .. read some input ... 
    if (/* input is "stop" */) { 
     break; // this causes the loop to exit 
    } 
} 
0

断裂想法将正常工作,但另一种方式来做到这将是包装在整个事情

while(! name.equals("stop")){...}

,一切输入名称后以类似的if语句

(if(! name.equals("stop"))){...} 

因此它不会执行。打破循环可能更容易,但我知道有一些人在使用break语句时皱眉。

0

你应该有while语句

hasNextLine()方法检查了线需要从标准输入读取以下。

while (input.hasNextLine()) 
{ 

    // your code goes here 
}