为什么运行时错误读取文件

时间:2014-10-25 03:46:45

标签: java java.util.scanner

嗨,我问的是为什么问题

我想知道为什么我的代码无法工作,我希望它输出,逻辑和/或运行时错误?

我需要它做的是读取一个文本文件,然后输出输入用户输入的次数。我已经预先输入了一个单词,所以每次输入都没有麻烦。

我只需要澄清如何使用扫描仪类读取文本文件 感谢此处的代码。

import java.util.Scanner;
import java.io.*;
public class P6B
{
public static void main (String args[]) throws IOException
{
    //vaiables
    Scanner reader = new Scanner ( new File("README.TXT"));
    Scanner txtString = new Scanner (reader.nextLine());
    //Scanner input = new Scanner (System.in);
    int CountWord = 0;
    String word;

    System.out.println( reader.next() + "\nThis program will read a text file with 50 random   words"
                        + "\nWhat word would you like to look up that may be repeated: ");
    word = "the";  //input.nextLine();
    while ( txtString.hasNext())
    {

        while (txtString.equals(word)){
            System.out.println( "TEST2" );
            CountWord++;
            reader.next();
        }
    }//to get words and return the value of how many times it was found
    if ( CountWord != 0)System.out.println( "\nI have found your word " + CountWord + " times.");
    else if ( CountWord == 0) 
        {
            System.out.println ( "\nNo word found in the text file." );
        }//end of if if error
 }//end of main method
 }//end of class assignment

好的,看到你的意见我将推出运行时错误。我再次检查,现在我不再遇到运行时错误。

这让我感到困惑。

这是我的输出:

The
This program will read a text file with 50 random words
What word would you like to look up that may be repeated: 

No word found in the text file.

WHY 困惑我。

这是文本文件。

The woolly mammoth (Mammuthus primigenius) was a species of mammoth, the common name for the     extinct elephant genus Mammuthus. The woolly mammoth was one of the last in a line of mammoth  species, beginning with Mammuthus subplanifrons in the early Pliocene. M. primigenius diverged from  the steppe mammoth, M. trogontherii, about 200,000 years ago in eastern Asia. Its closest extant relative is the Asian elephant.
The appearance and behaviour of this species are among the best studied of any prehistoric animal because of the discovery of frozen carcasses in Siberia and Alaska, as well as skeletons, teeth, stomach contents, dung, and depiction from life in prehistoric cave paintings. Mammoth remains had long been known in Asia before they became known to Europeans in the 17th century. The origin of  these remains was long a matter of debate, and often explained as being remains of legendary  creatures. The mammoth was identified as an extinct species of elephant by Georges Cuvier in 1796.
The woolly mammoth was roughly the same size as modern African elephants. Males reached shoulder   heights between 2.7 and 3.4 m (9 and 11 ft) and weighed up to 6 tonnes (6.6 short tons). Females  averaged 2.6–2.9 metres (8.5–9.5 ft) in height and weighed up to 4 tonnes (4.4 short tons). A newborn calf weighed about 90 kilograms (200 lb). The woolly mammoth was well adapted to the cold environment during the last ice age. It was covered in fur, with an outer covering of long guard hairs and a shorter undercoat. The colour of the coat varied from dark to light. The ears and tail were short to minimise frostbite and heat loss. It had long, curved tusks and four molars, which were replaced six times during the lifetime of an individual. Its behaviour was similar to that of modern elephants, and it used its tusks and trunk for manipulating objects, fighting, and foraging. The diet of the woolly mammoth was mainly grass and sedges. Individuals could probably reach the age of 60. Its habitat was the mammoth steppe, which stretched across northern Eurasia and North America.
The woolly mammoth coexisted with early humans, who used its bones and tusks for making art, tools, and dwellings, and the species was also hunted for food.[1] It disappeared from its mainland range at the end of the Pleistocene 10,000 years ago, most likely through a combination of climate change, consequent disappearance of its habitat, and hunting by humans, though the significance of these factors is disputed. Isolated populations survived on Wrangel Island until 4,000 years ago, and on St. Paul Island until 6,400 years ago. After its extinction, humans continued using its ivory as a raw material, and this tradition continues today. It has been proposed the species could be recreated through cloning, but this method is as yet infeasible because of the degraded state of the remaining genetic material.

2 个答案:

答案 0 :(得分:1)

我修改了你的代码。

  1. 您只需要一个Scanner个对象和一个循环。
  2. 您的内部while循环应替换为if语句,以增加您的计数器。
  3. 无论区分大小写,您都可能需要计算匹配的单词。如果是这种情况,则需要拨打equalsIgnoreCase()而不是equals()
  4. 由于您未指定遇到的运行时问题类型,因此我几乎无法弄清楚您收到该错误的原因。
  5. 我通过在Notepad ++中打开文档并验证其中的计数来验证程序。

    public class P6B
    {
        public static void main(String args[]) throws IOException
        {
            Scanner reader = new Scanner(new File("README.TXT"));
    
            int CountWord = 0;
            String word = "the";
            while (reader.hasNext())
            {
                String line = reader.next();
                if (word.equalsIgnoreCase(line))
                {
                    CountWord++;
                }
            }
            reader.close();
            if (CountWord != 0)
                System.out.println("I have found your word " + CountWord
                    + " times.");
            else if (CountWord == 0)
            {
                System.out.println("No word found in the text file.");
            }
        }
    }
    

    节目输出:     我已经找到了28次你的话。

    更新:计算多个单词

    public class P6B
    {
        public static void main(String args[]) throws IOException
        {
            System.out.print("Enter words to search separated by spaces: ");
            Scanner input = new Scanner(System.in);
            String in = input.nextLine();
    
            if (in.length() > 0)
            {
                int count = 0;
                String[] words = in.split("\\s");
                for (String word : words)
                {
                    Scanner reader = new Scanner(new File("README.TXT"));
                    while (reader.hasNext())
                    {
                        String line = reader.next();
                        if (word.equalsIgnoreCase(line))
                        {
                            count++;
                        }
                    }
                    System.out.println("I have found the word \'" + word + "\' "
                            + count + ((count == 1) ? " time." : " times."));
                    count = 0;
                    reader.close();
                }
            }
            input.close();
        }
    }
    

    如果您尝试以下操作:

    Enter words to search separated by spaces: the woolly foo
    

    您将获得以下输出:

    I have found the word 'the' 28 times.
    I have found the word 'woolly' 6 times.
    I have found the word 'foo' 0 times.
    

答案 1 :(得分:0)

这是工作示例。你需要做的就是从用户那里获取输入并将其存储在String中,然后逐行读取文本文件,如果该行等于userinput值,则在代码中增加count变量1。有很多冗余代码。

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

public class P6B {

    public static void main(String args[]) throws IOException {
        Scanner reader = new Scanner(new File("C:\\Users\\Madhawa.se\\Desktop\\workingfox\\m2.txt"));
        Scanner input = new Scanner (System.in);
        int CountWord = 0;
        String word = null;

        System.out.println("\nThis program will read a text file with 50 random   words"
                + "\nWhat word would you like to look up that may be repeated: ");

         String text = input.next();
        while (reader.hasNext()) {
            word=reader.nextLine();
            if (text.equals(word)) {
                CountWord++;
            }
        }//to get words and return the value of how many times it was found
        if (CountWord != 0) {
            System.out.println("\nI have found your word " + CountWord + " times.");
        } else if (CountWord == 0) {
            System.out.println("\nNo word found in the text file.");
        }//end of if if error
    }
}

文本文件内容。

book
book
book
shel
groceries

输出>>

This program will read a text file with 50 random   words
What word would you like to look up that may be repeated: 
book

I have found your word 3 times.

正在更新...

如果你的文本文件包含一行中的文本序列,则需要用空格分割行。

看一下......我添加了split("\\s+");,其中包含单行中的单词。如果要匹配忽略大小写的单词,请使用.equalsIgnoreCase代替.equals

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

public class P6Bxx {

    public static void main(String args[]) throws IOException {
        Scanner reader = new Scanner(new File("C:\\Users\\Madhawa.se\\Desktop\\workingfox\\m2.txt"));
        Scanner input = new Scanner (System.in);
        int CountWord = 0;

        System.out.println("\nThis program will read a text file with 50 random   words"
                + "\nWhat word would you like to look up that may be repeated: ");

         String text = input.next();
        while (reader.hasNext()) {
            String[] words = reader.nextLine().split("\\s+");
            for(String word : words){
                if (text.equals(word)) {
                    CountWord++;
                }
            }
        }//to get words and return the value of how many times it was found
        if (CountWord != 0) {
            System.out.println("\nI have found your word " + CountWord + " times.");
        } else if (CountWord == 0) {
            System.out.println("\nNo word found in the text file.");
        }//end of if if error
    }
}

文本文件

The woolly mammoth (Mammuthus primigenius) was a species of mammoth, the common name for the     extinct elephant genus     
Mammuthus. The woolly mammoth was one of the last in a line of mammoth  species, beginning with Mammuthus subplanifrons in the    
early Pliocene. M. primigenius diverged from  the steppe mammoth, M. trogontherii, about 200,000 years ago in eastern Asia. Its 
closest extant relative is the Asian elephant.

输出>>

This program will read a text file with 50 random   words
What word would you like to look up that may be repeated: 
mammoth

I have found your word 3 times.