有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何解决我的trycatch异常处理?

我的try-catch exception有问题。实际上,它的作用是提示用户输入一个文本文件的名称,比如Robot。但是如果说文件不存在,我必须确保应用程序会重新向用户输入文件名。希望你们能理解我仍然是一个新手,所以请随时提供建议或建议我的编码等。干杯

主要方法类:

import java.io.*;
import java.util.Scanner;
import java.util.Vector;

class TestVector3 {

public static void main(String [] args)
{
    System.out.println("Please enter the name of the text file to read: ");
    Scanner userInput = new Scanner(System.in);
    Vector <KillerRobot> robotDetails = new Vector <KillerRobot>();
    KillerRobot robot;

    Scanner fileInput = null;
    try
    {
        File textFile = new File(userInput.nextLine());
        fileInput = new Scanner(textFile);
    }
    catch (FileNotFoundException e)
    {
        System.out.println("Error - file not found!");
        System.out.println("Re-enter file name :");             //Reprompt user for name of the text file
        fileInput = new Scanner(userInput.nextLine());
    }

    while(fileInput.hasNext())
    {
        robot = new KillerRobot();

        String first = fileInput.next();
        robot.setName(first);

        String second = fileInput.next();
        robot.setMainWeapon(second);

        int third = fileInput.nextInt();
        robot.setNumberOfKills(third);

        robotDetails.add(robot);
    }

    for(KillerRobot i : robotDetails)
    {
        System.out.println(i);
    }

    fileInput.close();
}
}

KillerRobot类文件:

class KillerRobot {

private String name;
private String mainWeapon;
private int numberOfKills;

KillerRobot()
{
}

public String getName()
{
    return name;
}

public String getMainWeapon()
{
    return mainWeapon;
}

public int getNumberOfKills()
{
    return numberOfKills;
}

public String toString()
{
    return name + " used a " + mainWeapon + " to destroy " + numberOfKills + " enemies ";
}

public void setName(String a)
{
    name = a;
}

public void setMainWeapon(String b)
{
    mainWeapon = b;
}

public void setNumberOfKills(int c)
{
    numberOfKills = c;
}
}

共 (5) 个答案

  1. # 1 楼答案

    当您声明自己是初学者时,让我们先看看代码的相关部分,以确保我们讨论的是同一件事:

    Scanner fileInput = null;
    try {
        File textFile = new File(userInput.nextLine());
        fileInput = new Scanner(textFile);
    }
    catch (FileNotFoundException e) {
        System.out.println("Error - file not found!");
        System.out.println("Re-enter file name :"); 
        fileInput = new Scanner(userInput.nextLine());
    }
    

    你有一个输入,你想检查这个输入的条件,并要求一个新的输入,直到满足这个条件。可以使用如下循环解决此问题:

    Scanner fileInput = null;
    do {
        System.out.println("Enter file name :"); 
        try {
          fileInput = new Scanner(new File(userInput.nextLine()));
        } catch (FileNotFoundException e) {
          System.out.println("Error - file not found!");
       }
    } while(fileInput == null);
    

    那么,最后,为什么这样做有效呢?fileInput变量被设置为null,并将保持null,直到从标准输入成功读取给定文件,因为会引发异常,否则会阻止设置fileInput变量。这个过程可以无休止地重复

    另一方面,出于性能原因,实现基于异常的控制流通常不是一个好主意。如果文件通过File::exists存在,最好检查条件。但是,如果您在检查文件是否存在后读取该文件,则该文件可能同时被删除,从而导致赛车状态

    回复您的评论:在Java(或几乎任何编程语言)中,您可以内联表达式。这意味着不需要像中那样在两个不同的语句中调用两个方法

    Foo foo = method1();
    Bar bar = method2(foo);
    

    你只要打个电话就可以了

    Bar bar = method2(method1());
    

    通过这种方式,您可以为自己节省一些空间(如果代码变长,这一点会变得越来越重要),因为您不需要在代码的任何其他位置保存在foo中的值。类似地,您可以从

    File file = new File(userInput.nextLine())
    fileInput = new Scanner(file);
    

    进入

    fileInput = new Scanner(new File(userInput.nextLine()));
    

    因为file变量仅在创建Scanner时读取

  2. # 2 楼答案

    你可以调用main(),如下所示

     try
        {
            File textFile = new File(userInput.nextLine());
            fileInput = new Scanner(textFile);
        }
        catch (FileNotFoundException e)
        {
            System.out.println("Error - file not found!");
            main(args); // recursively call main() method 
        }
    

    现在,如果用户第一次尝试出错,那么您的代码将被要求重新输入文件名

    如何检查isFile是否存在

      File file = new File(filePathString); 
      if(file.exists() && !file.isDirectory()){
         System.out.println("file exist");
      }
    
  3. # 3 楼答案

    这真的是一个XY problem,因为您认为检查文件存在的唯一方法是通过捕获FileNotFoundException(因此询问try-catch异常处理),而其他方法可以帮助您以优雅的方式避免try-catch习惯用法

    要检查给定路径上是否存在文件,只需使用File.exists方法即可。还请参见File.isFile方法和/或File.isDirectory方法来验证目标文件对象的性质

    编辑:如raphw所述,此解决方案最好用于简单场景,因为在文件存在性检查期间发生并发文件删除的情况下,它可能会引发竞争条件。查看他的answer以了解如何处理更复杂的场景

  4. # 4 楼答案

    尝试将Try catch放入如下循环:

    Scanner fileInput = null;
    while (fileInput==null) 
    {
        try
        {
            System.out.println("Please enter the file name.");
            File textFile = new File(userInput.nextLine());
            fileInput = new Scanner(textFile);
        }
        catch (FileNotFoundException e)
        {
            System.out.println("Error - file not found!");
        }
    }
    

    接下来,您可以考虑将文件创建部分移动到单独的方法中,以便代码更干净

  5. # 5 楼答案

    不要爱上try catch,而是将其添加为您的功能。异常自然是针对运行时错误处理的,而不是针对逻辑构建的

    检查文件是否存在于给定位置

    File textFile = new File(userInput.nextLine());
    
    // Check if file is present and is not a directory
    if(!textFile.exists() || textFile.isDirectory()) { 
    
    System.out.println("Error - file not found!");
    
    //Reprompt user for name of the   text file
    System.out.println("Re-enter file name :");             
    fileInput = new Scanner(userInput.nextLine());
    
     }
    

    如果要持续提示用户直到输入正确的路径,可以将while循环替换为if循环