简体   繁体   English

在 Java 中使用 while 循环来计算句子

[英]Using a while loop in Java to count sentences

UPDATE:更新:
Figured it out with the help of everyone and some friends!在大家和一些朋友的帮助下弄清楚了! I needed to catch the \\n character in the string variable as well as the empty string.我需要捕获字符串变量中的 \\n 字符以及空字符串。 Thank you to everyone who commented and helped!感谢所有评论和帮助的人!

This is for an assignment for Intro to Java, we haven't gotten to methods yet and when googling for help that was the only thing popping up so I figured I might as well attempt asking myself.这是 Java 入门的作业,我们还没有接触到方法,当使用谷歌搜索寻求帮助时,这是唯一弹出的东西,所以我想我不妨尝试问问自己。

Thanks in advance!提前致谢!

For our project we have to create a program that calculates the FRI of some simple texts and I'm having two problems.对于我们的项目,我们必须创建一个程序来计算一些简单文本的 FRI,我遇到了两个问题。

This first problem is that while counting sentences from a file using a Scanner object and a while loop my count is always wrong by +1.第一个问题是,在使用 Scanner 对象和 while 循环从文件中计算句子时,我的计数总是错误 +1。 I can see in the console print out that it's counting the empty string, the \\n that prints out (I'm printing to the console so I can see what the variable is being given, not because it's required) even though I have it set to only increase my accumulating variable if my string isn't empty.我可以在控制台打印出来它正在计算空字符串,打印出来的 \\n(我正在打印到控制台,所以我可以看到给出的变量是什么,而不是因为它是必需的),即使我有它如果我的字符串不为空,则设置为仅增加我的累积变量。

Any help would be appreciated!任何帮助将不胜感激! I'm not sure what parts of my code are needed, but...我不确定需要我的代码的哪些部分,但是...

/* Count Sentences */
//Scanner object to read inputText
Scanner countSentences = new Scanner(inputText);

// While loop to count sentences
while(countSentences.hasNext()){
    String sentence = countSentences.useDelimiter(SENTENCE_DELIMITERS).next();
    System.out.println(sentence);
    if(sentence.compareTo("") != 0){
        numSentences++;
    }
}

...is the bit where the sentence counting takes place. ...是进行句子计数的位。

Thanks again!再次感谢!

Entire code!全码! Edit:编辑:

DESCRIPTION:描述:
A program to calculate the Flesch Readability Index of a text一个计算文本 Flesch 可读性指数的程序

public class Readability {

    public static void main(String[] args) throws IOException{
        final double FIRST_CONSTANT = -1.015;               //First constant of FRI formula
        final double SECOND_CONSTANT = 84.6;                //Second constant of FRI formula
        final double THIRD_COSTANT = 206.835;               //Third constant of FRI formula
        final String SENTENCE_DELIMITERS = "[.:;?!]";       //Sentence delimiters
        final String WORD_DELIMITERS = "[.:;?! ,\t,\n]";    //Word delimiters
        
        int numSentences = 0;                               //Number of sentences in inputText
        int numWords = 0;                                   //Number of words in inputText
        int numSyllables = 0;                               //Number of syllables in each word in inputText
        
        String standardText = "This is just a test.";       //Standard Text for testing
        String inputText = "";                              //Holds the text being tested currently
        
        /* Ask user if they want to run a text analysis */
        int choice = JOptionPane.showConfirmDialog(null, "Do you want to run a text analysis?", "Start the Flesch Reading Ease Test", JOptionPane.YES_NO_OPTION);
        
        /* Message Displayed if 'No' selected, and program exits */
        if(choice == JOptionPane.NO_OPTION) {
            JOptionPane.showMessageDialog(null, "The program exits. Good Bye!");
            System.exit(0);
        }
        
        /* If user selects 'Yes' */
        // Ask user if they have a text file or wish to use the standard text
        choice = JOptionPane.showConfirmDialog(null, "Answer \"Yes\" if you want to read the text from a file!\nAnswer \"No\" if you want a test run on a standard text.", "Select the input!", JOptionPane.YES_NO_OPTION);
        
            /* If user selects 'Yes' */
            if(choice == JOptionPane.YES_OPTION){
                // Ask user for filename
                String inputFileName = JOptionPane.showInputDialog("Enter input file name with extension!\nInclude the path if file is not in the project folder!");
                
                    // User presses cancel, set inputText to standardText 
                    if(inputFileName == null){
                        inputText = standardText;
                    }
                    
                    // User presses enter, create file object using user input as filename
                    else{
                        File file = new File(inputFileName);
                    
                    // Check if file exists, if file exists create scanner object to read text from file
                    if(file.exists()){
                        Scanner readFile = new Scanner(file);
                        
                        // Read the file line by line and collect the concatenated lines in the variable inputText
                        while(readFile.hasNext()){
                            String fileSentences = readFile.nextLine();
                            inputText += fileSentences + "\n";
                        }
                    }
                    // If file doesn't exist, set inputText to the standardText
                    else {
                        inputText = standardText;
                    }
                    }
            }
        
            /* If user selects 'No' */
            else{
                inputText = standardText;
            }    
        
            /* Count Sentences */
            //Scanner object to read inputText
            Scanner countSentences = new Scanner(inputText);
            
            // While loop to count sentences
            while(countSentences.hasNext()){
                String sentence = countSentences.useDelimiter(SENTENCE_DELIMITERS).next();
                System.out.println(sentence);
                if(sentence.length() != 0){
                    numSentences++;
                }
                System.out.println(numSentences); //This println prints the correct number to the console
            }
            System.out.println(numSentences);  //This println prints +1
            
            //Close countSentences scanner
            countSentences.close();
            
            /* Count Words */
            //Scanner object to read inputText
            Scanner countWords = new Scanner(inputText);
            
            // While loop to count words and increment syllable count per word (rule #3: each word has at least one syllable)
            while(countWords.hasNext()){
                String word = countWords.useDelimiter(WORD_DELIMITERS).next();
                
                if(word.compareTo("") != 0){
                    numWords++;
                    //numSyllables++;
                }
                
                // For loop to count syllables as each word is read
                for(int k = 0; k < word.length(); k++){
                    char letter = word.charAt(k);
                    
                    
                }
            }
            
    //Test//
    System.out.println(inputText);
    System.out.println(numSentences);
    System.out.println(numWords);
    System.out.println(numSyllables);
    }
    
}

Here is the working program.这是工作程序。 It gave me result as 2.它给了我结果为 2。

import java.util.Scanner;
    public class Scannerd {

      public static String inputText = "What!? That is awful!";

      public static String SENTENCE_DELIMITERS = "[.:;?!]";

            public static void main(String... arg) {
              int numSentences = 0;

              Scanner countSentences = new Scanner(inputText);

              // While loop to count sentences
              while (countSentences.hasNext()) {
                String sentence = countSentences.useDelimiter(SENTENCE_DELIMITERS).next();
                System.out.println(sentence);
                if(sentence.compareTo("") != 0){
                  numSentences++;
                }

              }
              System.out.println("#ofSentences"+numSentences);
            }
    }

Looks like it uses the default delimiter in the beginning since the custom delimiter is used inside the loop.看起来它在开始时使用默认分隔符,因为自定义分隔符在循环内使用。 Try this.试试这个。

import java.util.Scanner;
public class TestScanner {

  public static String inputText = "What!? That is awful!";

  public static String SENTENCE_DELIMITERS = "[.:;?!]";

        public static void main(String... arg) {
          int numSentences = 0;

          Scanner countSentences = new Scanner(inputText);
          countSentences.useDelimiter(SENTENCE_DELIMITERS);
          // While loop to count sentences
          while (countSentences.hasNext()) {
            //String sentence = countSentences.useDelimiter(SENTENCE_DELIMITERS).next();
              String sentence = countSentences.next();
            System.out.println(sentence);
            if(sentence.compareTo("") != 0){
              numSentences++;
            }

          }
          System.out.println("#ofSentences"+numSentences);
        }
}

Try using hasNextLine() and nextLine() methods.尝试使用 hasNextLine() 和 nextLine() 方法。

/* Count Sentences */
//Scanner object to read inputText
Scanner countSentences = new Scanner(inputText);

// While loop to count sentences
while(countSentences.hasNextLine()){
    String sentence = countSentences.useDelimiter(SENTENCE_DELIMITERS).nextLine();
    System.out.println(sentence);
    if(sentence.compareTo("") != 0){
        numSentences++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM