【问题标题】:Problems with writing to a file and searching an array写入文件和搜索数组的问题
【发布时间】:2013-12-02 04:00:22
【问题描述】:

抱歉有任何错误,我尝试进行一些更正,以便更容易理解我在做什么以及我需要帮助的地方。我对 java 和这个网站很陌生。

我正在尝试编写一个程序,它将 5 个单独文件中的州数据(州名、州昵称、州人口、州花和州首府)组织到五个单独的并行数组中。代码将要求输入并向用户提供以逗号格式化的人口数据。我还在创建一种将所有信息写入输出文件的方法。

我遇到了一些问题。

我想知道是否可以在一些问题上寻求帮助?

首先,运行代码后state_data.txt文件为空。

其次,如果你在 askState 方法中输入了一个无效的选择而不是要求一个新的输入,我的程序就会崩溃

我将不胜感激!

 import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Scanner;

    /**
     *

     */

public class Project_3a {

    /**
     * @param args the command line arguments
     */
    static final int NUM_STATES = 50;

    public static void main(String[] args) throws FileNotFoundException {
        String[] stateNames = importFile("stateNames.txt");
        String[] nicknames = importFile("nicknames.txt");
        String[] populations = importFile("population.txt");
        String[] flowers = importFile("flowers.txt");
        String[] capital = importFile("capitals.txt");
        for (int x = 0; x < NUM_STATES; x++) 
         {

         createFile(stateNames, nicknames, capital, flowers, populations);
         char getWantsToContinue = 'y'; 
         while (getWantsToContinue == 'y' || getWantsToContinue == 'Y') 
         { 
           System.out.println(stateNames); 
           int index = askState(stateNames); 
           String unformattedPopulation = populations[index]; 
           String formattedPopulation = formatPopulation(unformattedPopulation);                   
           outPut(stateNames,nicknames, capital, flowers, formattedPopulation,index);             
         }
         getWantsToContinue = again();
    }

    public static String[] importFile(String fileName) throws
            FileNotFoundException {

        String[] array = new String[NUM_STATES];

        File inputFile = new File(fileName);
        Scanner scanner = new Scanner(inputFile);


        for (int i = 0; i < NUM_STATES; i++) {
            array[i] = scanner.nextLine();

        }
        return array;

    }

    public static int askState(String[] stateNames) {
        Scanner keyboard = new Scanner(System.in);
        String state;
        int statePosition = -1;
        System.out.println("Please enter a state that you would like to search:");
        state = keyboard.nextLine();
        {
            for (int i = 0; i < NUM_STATES; i++) {
                if (state.equals(stateNames[i])) {
                    statePosition = i;
                    return statePosition;
                }
            }
            System.out.println("Please enter a valid state:");

        }
        return statePosition;
    }

    public static String formatPopulation(String population) {
        String formattedPopulations = "";
        {
            for (int i = population.length() - 1; i >= 0; i--) {
                formattedPopulations = population.charAt(i) + formattedPopulations;
                if (i % 3 == 2 && (i + 1 != population.length())) {
                    formattedPopulations = "," + formattedPopulations;
                }
            }
            return formattedPopulations;
        }

    }

    public static void createFile(String[] stateNames, String[] nicknames,
            String[] capitals, String[] flowers, String[] populations) throws FileNotFoundException {
        PrintWriter stateData = new PrintWriter("state_data.txt");
        for (int i = 0; i < NUM_STATES; i++) {
            stateData.println(stateNames[i] + "\t" + nicknames[i] + "\t" + capitals[i]
                    + "\t" + flowers[i] + "\t" + formatPopulation(populations[i]) + "\n");
        }
        stateData.close();
    }

    public static void outPut(String[] stateNames, String[] nicknames,
            String[] capitals, String[] flowers, String formattedPopulation,
            int index) {
        System.out.println("State Name: " + stateNames[index]);
        System.out.println("Nickname: " + nicknames[index]);
        System.out.println("Capital: " + capitals[index]);
        System.out.println("Flower: " + flowers[index]);
        System.out.println("Population: " + formattedPopulation);
    }

    public static char again() {
        Scanner keyboard = new Scanner(System.in);

        char getWantsToContinue;
        System.out.println("Would you like to search another state?");
        System.out.println("Please enter Y for yes or N for no.");
        getWantsToContinue = keyboard.next().charAt(0);
        while (getWantsToContinue != 'y' && getWantsToContinue != 'Y'
                && getWantsToContinue != 'n' && getWantsToContinue != 'N') {
            System.out.println("Please enter a valid option (Yor N).");
            getWantsToContinue = keyboard.next().charAt(0);
        }
        if (getWantsToContinue == 'n' || getWantsToContinue == 'N') {
            System.out.println("Goodbye!");
        }

        return getWantsToContinue;

    }
}

【问题讨论】:

  • “我将不胜感激并提供帮助!” 如有任何问题,我们将不胜感激!你有问题吗?你有什么问题?
  • 我的问题是如何解决我上面提到的两个问题。
  • 问题应该以'?'结尾。为了引起那些搜索“?”的人的注意。在文本中,如果没有,请立即转到下一个帖子,edit the question 在适当的位置添加它们
  • 使用while 循环为用户输入添加条件语句。广告让您的代码更具可读性以获得更好的帮助
  • 我尝试进行一些更改,以便读者更好地理解我的要求。

标签: java arrays file loops


【解决方案1】:

我只想补充我在您的代码中发现的问题。

(1)。我发现的第一个问题是函数importFile

  for (int i = 0; i < NUM_STATES; i++) {
        array[i] = scanner.nextLine();

    }

这个循环在我看来是错误的。您正在尝试从文件中扫描一行 50 次,并且您希望它存储在字符串的索引位置中的每一行。这是荒谬的。 另外,您真的确定必须始终运行循环 50 次吗? (这在我看来也是错误的)。

所以,据我所知,我认为您的意思是从文件 1 中读取 50 个字符并将其放入大小为 50 的字符串数组中,这意味着您必须一次读取一个字符。

所以我的解决这个问题的建议是:

(a). Read one character at a time.
(b). If you are not sure about the size of each file, iterate through it till the EOF.

(2)。我在createFile 方法中发现的第二个问题。

您正在创建一个新文件并插入所有文件中的第一个字符。然后是第二个。然后是第三个……直到第 50 个字符。

如果一个相应的文件在第 50 个字符之前没有任何数据怎么办。这将在您的结果文件中输入错误的数据。 这可能不会导致编译时异常,但可能会导致不希望出现的运行时异常。

(3)。在main 方法中:

     for (int x = 0; x < NUM_STATES; x++) 
         {

         **createFile(stateNames, nicknames, capital, flowers, populations);**
         char getWantsToContinue = 'y'; 
         while (getWantsToContinue == 'y' || getWantsToContinue == 'Y') 
         { 
           System.out.println(stateNames); 
           int index = askState(stateNames); 
           String unformattedPopulation = populations[index]; 
           String formattedPopulation = formatPopulation(unformattedPopulation);                   
           outPut(stateNames,nicknames, capital, flowers, formattedPopulation,index);             
         }

这意味着createFile 方法被调用了50 次。哪个总是创建相同的“state_data.txt”文件 50 次? (这是干什么用的?)

寻找其他问题。同时,开始着手纠正它。

【讨论】:

    【解决方案2】:

    您可能对如何使用Scanner 实例读取文件感到困惑。在您的 importFile 方法中,您假设至少有 50 行数据并使用 scanner.nextLine() 读取它。你必须检查是否有下一行然后读取它,否则会在没有下一行时抛出NoSuchElementException。代码应该是

    while(scanner.hasNext()){
    scanner.next();
    }
    

      while(scanner.hasNextLine()){
        scanner.nextLine();
        }
    

    同样,在您的createFile 方法中,您确定所有参数String arrays 的长度为50For 循环始终被编程为运行 50 次以创建 String 文字,其中假定传递给该方法的所有数组的索引值 (0-49) 为 50。当没有找到索引值时,这将导致RuntimeException - ArrayIndexOutOfBoundException。在执行此操作之前,您需要通过检查所有数组 length 是否应为 50 来处理此问题。最好,您应该使用StringBuilder 而不是连接String instance inside aloop. In youraskState` 方法,当用户键处于无效状态时,您没有条件循环来重新请求输入。

    while(invalidState(state)){
    System.out.println("Please enter input");
    state = keyboard.nextLine();
    }
    

    另一件重要的事情是你调用createFile 方法五十次,这根本不需要,因为你有所有不同的文件数据在数组中。将数组传递给createFile 方法一次就足够了,然后编写逻辑将全部数据写入单个文件中

    for (int x = 0; x < NUM_STATES; x++) 
             {
    
             createFile(stateNames, nicknames, capital, flowers, populations);
    

    我建议您必须完全调试您的程序,以确保您的代码以您认为的相同方式运行。希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 2011-01-11
      • 1970-01-01
      • 2014-07-19
      相关资源
      最近更新 更多