简体   繁体   中英

Pattern/Array issue in java

I am studying for an upcoming test next month and looking at some basic problems. This one is a program that requires entering a few sentences and reprinting any that contain a certain string, 'pattern' in this case.

My attempt is below and it compiles however I receive the following error when trying to run it:

  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at Grep.main(Grep.java:18) 
import java.util.Scanner;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Grep {

    public static void main(String[] args) {

        Pattern pattern = Pattern.compile("[Pp]attern");
        String sentences[] = new String[10];
        Scanner scanner = new Scanner(System.in); 

        System.out.println("Please enter some sentences: ");

        for (int i = 0; i <= sentences.length; i++) {
            String s = scanner.next(); 
            sentences[i] = s;
        }

        for (int i = 0; i < sentences.length; i++) { 
            Matcher matcher = pattern.matcher(sentences[i]);
            while (matcher.find()) {
                System.out.println(sentences[i]);
            }
        }
    }
}
for (int i = 0; i <= sentences.length; i++) {

How many items are in the array? What is the last index? What is the last index your loop uses? How many sentances in total does your loop access?

for (int i = 0; i <= sentences.length; i++) {

<=必须为<因为您从0开始并且有10个项目,所以i必须从0到9。

Try

for (int i = 0; i < sentences.length; i++)

and you'll be fine :)

The problem is in line :18 of your code which is for (int i = 0; i <= sentences.length; i++) it should be for (int i = 0; i < sentences.length; i++)

as you your own in the next for loop in your code has used < instead of <=

Try this. It works.

Tips: Make sure you use nextLine() so that the input will read full sentences. And I switched your while loop for an if statement within the for loop. No need for two loops there. And I also condensed your first for loop to just one line. No need to create a string variable if you only need it for a second. Just skip that step entirely and get to the point! Good luck, Hope this helps!

Below Is A Program That Mirrors Yours But Now Works

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Grep 
{
    public static void main(String[] args) 
    {
        Pattern pattern = Pattern.compile("[Pp]attern");
        String sentences[] = new String[3];
        Scanner scanner = new Scanner(System.in);

        System.out.println("Please enter some sentences: ");

        for (int i = 0; i < sentences.length; i++) 
            sentences[i] = scanner.nextLine();

        for (int i = 0; i < sentences.length; i++) 
        { 
            Matcher matcher = pattern.matcher(sentences[i]);
            if (matcher.find()) 
                System.out.println(sentences[i]);
        }
    }
} 

Below Is How I Would Write This Same Program. Comments Included For Clarification

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Grep 
{
    public static void main(String[] args) 
    {
        // Initialize and Declare Variables
        Pattern pattern = Pattern.compile("[Pp]attern");
        String sentences[] = new String[3];
        Scanner scanner = new Scanner(System.in);
        int foundCount = 1;


        // Present A Title For The End User
        System.out.println("This Program Will Catch Sentences With The Term Pattern.\n");


        // Read The Inputs From The Users
        for (int i = 0; i < sentences.length; i++)
        {
            System.out.print("Enter Sentence #" + (i+1) + ":  ");
            sentences[i] = scanner.nextLine();
        }


        // Line Break
        System.out.println();


        // Write Sentences That Include The Term Pattern
        for (int i = 0; i < sentences.length; i++) 
        { 
            Matcher matcher = pattern.matcher(sentences[i]);
            if (matcher.find())
            {
                System.out.println(foundCount + ")  " + sentences[i]);
                foundCount++;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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