2017-04-08 82 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")) 

希望这会有所帮助。