2016-04-28 57 views
0

好所以我的程序是從用戶接收到一個URL到一個數據庫,並通過計算平均值並顯示它來處理這些數據。我的算法對此非常好,我遇到的問題是處理URL異常。如果用戶輸入無效的URL,我希望他們再次嘗試並輸入正確的URL,但是當用戶再次輸入URL時,URL中的數據都不會被處理,並且我一直在輸出中收到「NaN」。下面是try catch塊,因爲我相信問題在那裏,如果可以的話請幫忙。Try-Catch Block不處理異常我傾向於的方式

//測試URL // URL salary = new URL(「http://cs.armstrong.edu/liang/data/Salary.txt」);

System.out.println("Enter The URL to the File "); 
    Scanner UserInput = new Scanner(System.in); 


    try 
    { 

     //Ask The User to Input the URL 

     URL salary = new URL(UserInput.nextLine()); 



     Scanner Read = new Scanner(salary.openStream()); 



     while(Read.hasNextLine()) 
     { 

      for(int i = 0; i < Faculty.length; i++) 
      { 



       String Firstname = Read.next(); 


       String Lastname = Read.next(); 

       String rank = Read.next(); 

       double Salary = Read.nextDouble(); 


       if(rank.matches("assistant")) 

       { 
        Faculty[i] = new AssistantProfessor(Firstname, Lastname, rank, Salary); 
        allAssistantProff[i] = new AssistantProfessor(Firstname, Lastname, rank, Salary); 
        AssistantProfessors++; 
       } 

       if(rank.matches("associate")) 

       { 
        Faculty[i] = new AssociateProfessor(Firstname, Lastname, rank ,Salary); 
        allAssociateProff[i] = new AssociateProfessor(Firstname, Lastname, rank ,Salary); 
        AssociateProfessors++; 
       } 

       if(rank.matches("full")) 
       { 

        Faculty[i] = new FullProfessor(Firstname, Lastname, rank, Salary); 
        allFullProff[i] = new FullProfessor(Firstname, Lastname, rank, Salary); 
        FullProfessors++; 
       } 

        //System.out.println(Faculty[i]); 
        //System.out.println(allAssistantProff[i]); 
        //System.out.println(allAssociateProff[i]); 
        //System.out.println(allFullProff[i]); 



     } 


     } 


    } 



    catch(MalformedURLException ex) 
    { 

     System.out.println("invalid URL" + " Try Again "); 
     URL salary = new URL(UserInput.nextLine()); 
    } 
+0

那麼,你有什麼異常?我的意思是控制達到攔截? – tesnik03

+0

這不是一個調試服務。自己使用調試器。 – Raedwald

回答

0

您是否曾嘗試通過在彼此之後輸入2個有效的URL來運行代碼?

我問這個,因爲我沒有看到外面的一段時間,或者「跳回」會重新啓動「Scanner Read = new Scanner(salary.openStream());」線

如果你有一個外跳回,您聲明中的異常處理的局部變量的薪水,將在「}」在catch塊,這可能不是一個問題後壽

0

將被刪除您的嘗試成一個循環,像這樣:

System.out.println("Enter The URL to the File "); 
Scanner UserInput = new Scanner(System.in); 
Scanner Read; 
while (true) { 
    try { 
    URL salary = new URL(UserInput.nextLine()); 
    Read = new Scanner(salary.openStream()); 
    break; 
    } catch(IOException ex) { 
    System.out.println("Couldn't open URL. Try again."); 
    } 
} 
while(Read.hasNextLine()) { 
    /* Process your file as usual. */ 
}