2017-04-08 25 views
0

所以我要接受來自用戶的文件名。然後我想檢查字符串的最後四個字符是否是「.txt」。如果不是,則在用戶輸入的字符串末尾附加「.txt」。如果是,跳過。簡單。if語句檢查文件名是否正確(追加名爲「.txt」)不工作

但它不工作 - 當我輸入「exampledata.txt」它仍然添加「.txt」並引發FileNotFoundException - 我不明白爲什麼。我採取了相同的計算並將其打印出來/在調試器中驗證;我的方法調用子字符串是正確的。

相關代碼:

import java.util.*; 
import java.io.*; 

public class MappingApp { 
    public static void main(String[] args) { 
     Scanner sc = new Scanner(System.in); 
     String userInput; 
     System.out.print("Enter file to read from: "); 
     userInput = sc.nextLine(); 

     if ((userInput.substring(userInput.length()-4, userInput.length())) != ".txt") { 
      userInput += ".txt"; 
     } 

     try { 
      File f = new File(userInput); 
      BufferedReader br = new BufferedReader(new FileReader(f)); 
     } 
     catch (FileNotFoundException e) { 
      System.err.println(e); 
     } 
    } 
} 
+3

你可以簡單地使用Java API的字符串的方法的endsWith檢查,如果userInput與名爲「.txt」或沒有結束。 –

回答

0

通常你不會比較字符串=或== 嘗試改變

if ((userInput.substring(userInput.length()-4, userInput.length())) != ".txt") 

if (!(userInput.substring(userInput.length()-4, userInput.length()).equals (".txt")) 

希望這會有所幫助。