他们是完全相同的方法,但一个工作,另一个不工作 [英] They are exact same methods but one works and another does not

查看:151
本文介绍了他们是完全相同的方法,但一个工作,另一个不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class L20 {
public static void main(String[] args) throws IOException{
    Scanner input=new Scanner(System.in);

    System.out.println("Enter file name");
    String in=input.nextLine();
    try{
        textWriter(in);
        textReader(in);
        textChanger(in);

    }catch(Exception e){

    }

}

public static void textWriter(String path) throws IOException{
    String[] alphabet=    
 {"a","b","c","d","e","f","g","h","i","j","k","m","l","n","o","p","q","r","s","t","u","v","w","x","y","z"};
File file=new File(path);
Writer output=null;
    Random number=new Random();
    output=new BufferedWriter(new FileWriter(file));
    int lines=10+number.nextInt(11);
    for(int i=0;i<lines;i++){
    int it2=1+number.nextInt(9);
    int n1=number.nextInt(26);
    int n2=number.nextInt(26);
    int n3=number.nextInt(26);

    String t2=Integer.toString(it2);
    String t1=alphabet[n1]+alphabet[n2]+alphabet[n3];
    String text=t1+t2;
    output.write(text);
    ((BufferedWriter) output).newLine();
    }
    output.close();
    System.out.println("Your file has been written");
}

public static void textReader(String path) throws IOException{
    File file=new File(path);
    Scanner input;
    input=new Scanner(file);
    String line;
    while((line=input.nextLine())!=null){
        System.out.println(line);
    }
    input.close();
}

private static void textChanger(String path) throws IOException{
    File file=new File(path);
    Scanner input2;
    input2=new Scanner(file);
    String line;
    while((line=input2.nextLine())!=null){
        System.out.println(line);
    }
    input2.close();
}

}

textWriter工作正常。
textReader和textChanger完全一样!但textReader工作正常,textChanger没有!为什么?我甚至为每种方法重命名了扫描仪。似乎Text.txt只能被读取一次??

textWriter works fine. textReader and textChanger are exactly the same! But textReader works fine and textChanger does not! WHy? I even have renamed the scanner for each method. It seems the Text.txt can only be read for once??

推荐答案

问题是你的程序在 textReader textChanger 根本没有被调用。而不是:

The problem is that your program is crashing silently in textReader and textChanger is not being called at all. Instead of this:

while((line=input.nextLine())!=null){
    System.out.println(line);
}

你应该使用这个:

while(input.hasNextLine()){
    System.out.println(input.nextLine());
}

Scanner.nextLine()将不会返回 null ;它将抛出 NoSuchElementException

Scanner.nextLine() will not return null if there is no more input; it will throw a NoSuchElementException.

一般情况下,不要以静默方式捕获异常。至少调用 printStackTrace()或记录问题!

In general, don't silently catch exceptions. At least call printStackTrace() or log the problem!

这篇关于他们是完全相同的方法,但一个工作,另一个不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆