2013-09-25 136 views
1

所以我在java中有这个简单的代码。但是,当我试图“再次使用该程序”写在代码中,它总是跳过第一项是输入名称。我该如何解决?迭代后跳过一行

下面的代码:

import java.util.Scanner; 
public class Try{ 
public static void main(String args[]){ 
    Scanner sc=new Scanner(System.in); 
    int salary; 
    String name, perform; 
    int choice = 1; 
    do{ 
     System.out.println("Enter your name:");  
     name=sc.nextLine(); 
     System.out.println("Enter your performance:"); 
     perform=sc.nextLine(); 
     System.out.println("Enter your salary:"); 
     salary=sc.nextInt(); 

     System.out.println("Name: "+name); 
     System.out.println("Performance: " + perform); 
     System.out.println("Salary:" + salary); 

     System.out.println("Do you want to use the program again?\n[1]Yes\n[2]No"); 
     choice=sc.nextInt(); 
    }while (choice < 2); 
} 
} 

回答

6

您需要nextInt()后使用sc.nextLine(),因为nextInt()不消耗换行符(不像nextLine())。所以在循环开始时总会有额外的换行符(在第一次迭代之后)。

1

使用

salary=Integer.parseInt(sc.nextLine()); 

choice = Integer.parseInt(sc.nextLine()); 

,而不是使用sc.nextInt();

您还需要考虑与包裹块try{} catch(...)这些线路,以避免超过整数其他投入。