【问题标题】:Why is my program giving me the wrong output when I run it?为什么我的程序在运行时给我错误的输出?
【发布时间】:2015-03-29 14:35:23
【问题描述】:

我正在制作一个程序,在其中查看一个包含 11 个名称的文本文件,检查文件中是否存在某个名称,添加新名称,删除名称,然后关闭文件以更新它。

这是 directory.txt 中的数据:(每个名称都换行)

迈克
吉姆
巴里
克里斯蒂安
文森特
成军
苏珊

瑟琳娜

这是我的帮助类目录,其中包含我们可以对名称执行的所有可能操作。

import java.util.*;
import java.io.*;
public class Directory {
   //public static void main(String[] args) {
   final int maxDirectorySize = 1024;
   String directory[] = new String[maxDirectorySize];
   int directorySize = 0;
   File directoryFile = null;
   Scanner directoryDataIn = null;

   public Directory(String directoryFileName) {
      directoryFile = new File(directoryFileName);
      try {
         directoryDataIn = new Scanner(directoryFile);
      }
      catch (FileNotFoundException e) {
         System.out.println("File is not found, exiting!" + directoryFileName);
         System.exit(0);
      }
      while (directoryDataIn.hasNext()) {
         directory[directorySize++] = directoryDataIn.nextLine();
      }
   }
   public boolean inDirectory(String name) {
      boolean inDir = true;
      for (int i = 0; i < directory.length; i++) {
         if (name.equalsIgnoreCase(directory[i])) {
            inDir = true;
            break;
         }
         else {
            inDir = false;
            break;
         }
      }
      return inDir;
   }
   public boolean add(String name) {
   if (directory.length == 1024)
      return false;
      boolean added = true;
      for (int i = 0; i < directory.length; i++) {
         if (directory[i].equalsIgnoreCase(name)) {
            added = false;
            break;
         }
         else {
            directory[directorySize++] = name;
            added = true;
            break;
         }
      }
      return added;
   }          

   public boolean delete(String name) {
      for (int i = 0; i < directory.length; i++) {
         if (directory[i].equalsIgnoreCase(name)) {
            directory[i] = null;
            return true;
         }   
         else
            return false;
      }
      return false;
   }

   public void closeDirectory() {
      directoryDataIn.close();
      PrintStream directoryDataOut = null;
      try {
          directoryDataOut = new PrintStream(directoryFile);
      }
      catch (FileNotFoundException e) {
         System.out.printf("File %s not found, exiting!", directoryFile);
         System.exit(0);
      }
      String originalDirectory[] = {"Mike","Jim","Barry","Cristian","Vincent","Chengjun","susan","ng","serena"};
      if (originalDirectory == directory)
         System.exit(0);
      else
         for (int i = 0; i < directorySize; i++)
            directoryDataOut.println(directory[i]);
         directoryDataOut.close();
   }
}

这是我正在运行的用户界面类。类 DirectoryWithObjectDesign

import java.io.*;
import java.util.*;
public class DirectoryWithObjectDesign {
   public static void main(String[] args) { //throws IOException 
   String directoryDataFile  = "Directory.txt";
   Directory d = new Directory(directoryDataFile);
   Scanner stdin = new Scanner(System.in);
   System.out.println("Directory Server is Ready!");
   System.out.println("Format: command name");
   System.out.println("Enter ^Z to end");
   while (stdin.hasNext()) {
      String command = stdin.next();
      String name = stdin.next();
      if (command.equalsIgnoreCase("find")) {
         if (d.inDirectory(name))
            System.out.println(name + " is in the directory");
         else 
            System.out.println(name + " is NOT in the directory");
      }
      else if (command.equalsIgnoreCase("add")) {
         if (d.add(name))
            System.out.println(name + " added");
         else 
            System.out.println(name + " cannot add! " + "no more space or already in directory");
      }
      else if (command.equalsIgnoreCase("delete")) {
         if (d.delete(name))
            System.out.println(name + " deleted");
         else
            System.out.println(name + " NOT in directory");
      }
      else {
         System.out.println("bad command, try again");
      }
   }
   }
}   

最后,这是我得到的错误输出:

 ----jGRASP exec: java DirectoryWithObjectDesign

Directory Server is Ready!
Format: command name
Enter ^Z to end
find mike
mike is in the directory
find serena
serena is NOT in the directory
find susan
susan is NOT in the directory
find barry
barry is NOT in the directory
add melissa
melissa added
add joey
joey added
delete joey
joey NOT in directory
delete ng
ng NOT in directory
delete serena
serena NOT in directory
<eof>

 ----jGRASP: operation complete.

我试图弄清楚如何修复它并尝试了一些不同的方法,但我仍然得到错误的输出。我看不出问题出在哪里或如何解决。谁能帮忙?

【问题讨论】:

  • 有趣的是,您已经修复了 inDirectory 方法,但其他方法仍然存在同样的问题 (`NullPointerException` thrown while searching text file)。
  • 代码不完整。我们如何分析缺失的内容?
  • 请不要从问题中删除问题代码。这使阅读变得非常混乱,并使问题对未来的访问者毫无用处。 @Shree OP 已经编辑了代码,并在有人回滚了第一次删除后再次删除了它。我已将帖子标记为 mod 注意。

标签: java


【解决方案1】:

这个逻辑是错误的:

   public boolean inDirectory(String name) {
      boolean inDir = true;
      for (int i = 0; i < directory.length; i++) {
         if (name.equalsIgnoreCase(directory[i])) {
            inDir = true;
            break;
         }
         else {
            inDir = false;
            break;
         }
      }
      return inDir;
   }

只有当它是目录中的名字时,您才能找到该名称。

您应该只在找到匹配项或检查目录中的所有名称后才退出循环:

   public boolean inDirectory(String name) {
      boolean inDir = false;
      for (int i = 0; i < directory.length; i++) {
         if (name.equalsIgnoreCase(directory[i])) {
            inDir = true;
            break;
         }
      }
      return inDir;
   }

【讨论】:

  • 我只是这样修复它,但仍然得到相同的错误输出。它只读取文本文件(mike)的第一行,其他所有内容“不在目录中”@eran
  • @dinax 我建议你调试你的程序。也许你没有正确阅读文本文件。
  • “我只是这样修复它,但仍然得到相同的错误输出。”,那么你做错了。该修复有效。
  • 忘记更新 @tom ,所以 inDirectory 现在工作正常。只是添加功能一直在告诉“无法添加,没有更多空间”。同样,当我尝试删除目录中的名称时,我不断收到“名称不在目录中”
  • @dinax 既然我猜你足够聪明,可以解决剩下的问题,我只告诉你有问题的行:关于 add: if (directory.length == 1024);关于 deleteelse return false;(这与您原来的inDirectory 中的问题相同)。
【解决方案2】:

Kapeller,也许这个程序会对你有所帮助。我使用新的 java.nio api 设计了这个程序。看一看 :)。进行必要的更改以满足您的需求。

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.LinkOption;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.FileOutputStream;

import java.util.Collection;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.LinkedHashSet;

import static java.lang.System.*;

public final class NameSearcher{
    private String sourceFile;
    private final Collection <String> fileContent   = new LinkedHashSet<>();
    private Thread EXISTENCE_WATCHER                = null;
    private Path sourcePath                         = null;

    public String getSourceFile(){ return this.sourceFile; }

    public void   setSourceFile(final String value){ 
        this.sourceFile = value; 

        sourcePath = Paths.get(sourceFile);

        if(Files.exists(sourcePath,LinkOption.NOFOLLOW_LINKS)){
            //Setting up the file watcher thread !!!
            EXISTENCE_WATCHER = new Thread(()->{ 
                try{
                    if(!Files.exists(sourcePath,LinkOption.NOFOLLOW_LINKS)) {
                        EXISTENCE_WATCHER.join();
                        System.exit(-2);
                    }
                    Thread.sleep(5000);
                }catch(InterruptedException cause){ cause.printStackTrace();}
            });

            //Reading from the file
            try(Scanner reader = new Scanner(sourcePath.toFile())){

                while(reader.hasNext()) fileContent.add(reader.next());

            }catch(IOException cause){cause.printStackTrace();}
        }else{
            out.println("Sorry, the specified source file cannot be found !!!. Program exits now !!!");
            System.exit(-1);
        }
    }

    public Boolean contains(final String key){
        return fileContent.contains(key);
    }
    public void addName(final String name){

        if(!fileContent.contains(name))
                fileContent.add(name);
    }
    public Boolean deleteName(final String name){
        return fileContent.remove(name);
    }
    @Override
    public void finalize(){
        out.println("\nInvoked finalization ....");
        out.println("\nFile Buffer up on finalize entry");
        fileContent.stream().forEach(out::println);
        out.println("--------------------------------");
        try(    PrintWriter writer = new PrintWriter(new FileOutputStream(sourcePath.toFile()));
                Scanner     comparisonReader = new Scanner(sourcePath.toFile());
            ){      

            while(comparisonReader.hasNext()){
                String file_token = comparisonReader.next();
                 if(fileContent.contains(file_token)) fileContent.remove(file_token);               
            }

            fileContent.parallelStream().forEachOrdered(token -> {writer.append(token); writer.println(); out.println("Elem -> "+token);});

        }catch(IOException cause){
            cause.printStackTrace();
        }finally{
            if(EXISTENCE_WATCHER.isAlive()){
                try{
                    EXISTENCE_WATCHER.join();                   
                }catch(Exception cause){ cause.printStackTrace();}
            }
            fileContent.clear();            
            sourcePath  = null;
        }
    }
    public static void main(String[] args) {
        NameSearcher obj = new NameSearcher();
        obj.setSourceFile("test.txt");
        out.printf("Contains check for Line1 : %b",obj.contains("Line1"));
        obj.addName("Jai");
        obj.addName("Matha");
        obj.finalize();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多