2015-09-11 3 views
-1

В этой программе я попытался получить входные данные из консоли, чтобы выбрать, следует ли просматривать или вставлять в базу данных. Когда я пытаюсь вставить данные в базу данных Как только я введу идентификатор сотрудника, он автоматически пропустит имя, и он попросит войти в отдел. Объясните мне?Невозможно правильно ввести Вход в Java

package jdbc.org; 
import java.sql.*; 
import java.util.*; 

public class EmpDetails 
{ 
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/Employee"; 


static final String USER = "root"; 
static final String PASS = ""; 

public static void main(String[] args) 
{ 
    int EmpID; 
    String Name, Dept, Email; 
    Connection con = null; 
    Statement s=null; 
    ResultSet rs=null; 
    int ch; 
    boolean flag=true; 
    Scanner sc=new Scanner(System.in); 
    try 
    { 
     Class.forName("com.mysql.jdbc.Driver"); 
     System.out.println("Successfully registered driver"); 

     System.out.println("Connecting to a selected database..."); 
     con = DriverManager.getConnection(DB_URL, USER, PASS); 
     System.out.println("Connected database successfully..."); 
    } 
    catch(Exception e) 
    { 
    System.out.println("Error1" +e); 

    }  
    do 
    { 
    System.out.println("Press 1 to INSERT into the DB"); 
    //System.out.println("Press 2 to DELETE from DB"); 
    //System.out.println("Press 3 to UPDATE into DB"); 
    System.out.println("Press 2 to VIEW ALL from DB"); 
    System.out.println("Press 3 to EXIT"); 
    System.out.println("Enter Your Choice"); 
    ch=Integer.parseInt(sc.nextLine()); 

    switch(ch) 
    { 
    case 1: 
     System.out.println("Enter Your Employee ID:\n"); 
     EmpID=sc.nextInt(); 

     System.out.println("Enter Your Name:\n"); 
     Name=sc.nextLine(); 

     System.out.println("Enter Your Department:\n"); 
     Dept=sc.nextLine(); 

     System.out.println("Enter Your Email:\n"); 
     Email=sc.nextLine(); 

     try 
     { 
      String query="Insert into Employee values('"+EmpID+"','"+Name+"','"+Dept+"','"+Email+"')"; 
      s=con.createStatement(); 
      s.executeQuery(query); 
      System.out.println("Row Inserted"); 

     } 
     catch(Exception e) 
     { 

      System.out.println("Error2" +e); 

      break; 
     } 

     case 2: 
      try 
       { 

       String query="select * from Employee "; 
       s=con.createStatement(); 
       rs=s.executeQuery(query); 
       boolean rec=rs.next(); 
       while(!rec) 

       { 
       System.out.println("No Record"); 
       }  

       do 
       { 
        EmpID=rs.getInt(1); 
        Name=rs.getString(2); 
        Dept=rs.getString(3); 
        Email=rs.getString(4); 

        System.out.print(EmpID+"\t"); 
        System.out.print(Name+"\t"); 
        System.out.println(Dept+"\t"); 
        System.out.println(Email); 
       }while(rs.next()); 

      s.close(); 
      con.close(); 

       } 
      catch(Exception e) 
       { 
       System.out.println("Error2" +e); 

       }  
       break; 
     case 3: 
       System.exit(1); 
       break; 

      default: 
       System.out.println("Default Case"); 


    } 
    System.out.println("Do You want to continue:Yes/No)"); 
    String str=sc.nextLine(); 
    if(str.equals("Yes")|| str.equals("Y")) 
    flag=true; 
    if(str.equals("No")||str.equals("N")) 
    flag=false; 

    }while(flag);  


} 

}

+2

Возможный дубликат [Пропуск nextLine() после использования next(), nextInt() или других методов nextFoo()] (http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next- nextint-or-other-nextfoo-methods) –

+0

Также я бы не назвал это [минимальным примером] (http://stackoverflow.com/help/mcve). – fabian

+0

Также почему вы разбираете 'ch' в' int ':' ch = Integer.parseInt (sc.nextLine()); '. Почему бы вам не использовать 'nextInt(); 'как вы это делали в своем блоке switch? –

ответ

1

Это происходит потому, что sc.nextInt() не потребляет новую строку. Так как

String tmp = sc.nextLine(); 
    try { empid = Integer.parseInt(tmp); } 
    catch (Exception e) { ... } 

или

System.out.println("Enter Your Employee ID:\n"); 
    EmpID=sc.nextInt(); 
    sc.nextLine(); /* consume new line here */ 

    System.out.println("Enter Your Name:\n"); 
    Name=sc.nextLine(); 

должен работать.

+0

Я почти пришел к такому же выводу: D вы были быстрее –

Смежные вопросы