Pattern/Array issue in java - 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?

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++;
}
}
}
}

for (int i = 0; i <= sentences.length; i++) {
The <= needs to be < because you are starting from 0 and you have 10 items, so i has to go from 0 to 9.

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
for (int i = 0; i < sentences.length; i++)
and you'll be fine :)

Related

How to reverse the word after getting a Capital letter at the end of the word in JAVA?

Suppose you have a String and a CAPITAL letter in that indicates ending of a word. For example, if you have wElovEcakE where E, E and K indicates end of the words wE, lovE and cakE respectively. You need to reverse each word (as you know where it ends). Don’t reverse the String as a whole. To illustrate, if we give wElovEcakE as input output should be EwEvolEkac. See wE became Ew, lovE became Evol and so on....
And the way i tried to approach with ..
import java.util.Scanner;
public class Alternative {
public static void main(String[]args) {
Scanner robo=new Scanner (System.in);
System.out.println("Enter a word ");
String word=robo.nextLine();
char[] array=word.toCharArray();
for(int i =0;i<array.length;i++){
int count =0;
for(int j=0;j<=("EMPTY");j++) // here i am trying to operate a loop where it will work up to the Capital letter.
count ++;
}
//Code incomplete
}
}
}
Above i have mentioned "EMPTY" in the condition part ... i want to operate a loop where my loop will work up to the capital letter , then i will count all the letter that i have counted up to capital letter then last step will be like i will make another loop where i will reverse all the letter where condition for the loop will <=count ;Example:lovE (counted 4 letters i will reverse four times back).
Can you guys help me to write the condition at "EMPTY" part if you think that my approach is correct ..
Can you guys help me to solve the problem in any other way ?
test if this works for you:
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
String textInvert = "";
int indexAnt = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
String wordSplit = word.substring(indexAnt, i + 1);
for (int j = wordSplit.length() - 1; j >= 0; j--)
textInvert += wordSplit.charAt(j);
indexAnt = i + 1;
}
}
System.out.println(textInvert);
Here is my solution with Regex pattern
String[] in = "wElovEcakE".replaceAll("([A-z]+?[A-Z])","$1,").replaceAll(",$","").split(",");
String out = "";
for(String current: in){
StringBuilder temp = new StringBuilder();
temp.append(current);
out+=temp.reverse();
}
System.out.println(out);
Result:
EwEvolEkac
Here is a solution that makes use of the StringBuilder class to hold and reverse each found word.
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word:");
String word = robo.nextLine();
robo.close();
String upperCase = word.toUpperCase(); //used to find uppercase letters
StringBuilder builder = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
char nextChar = word.charAt(i);
builder.append(nextChar);
if (nextChar == upperCase.charAt(i)) {
String subWord = builder.reverse().toString();
System.out.print(subWord); //It's not clear what to do with the found words
builder = new StringBuilder();
}
}
System.out.println();
Example
Enter a word:
makEmorEpiE
EkamEromEip
You can try this solution:
String textInvert = "wElovEcakE";
String revertText = textInvert
.chars().mapToObj(c -> (char) c)
.reduce(new LinkedList<>(Arrays.asList(new StringBuilder())), (a, v) -> {
a.getLast().append(v);
if (Character.isUpperCase(v)) {
a.add(new StringBuilder());
}
return a;
}, (a1, a2) -> a1)
.stream()
.map(s -> s.reverse())
.reduce(StringBuilder::append)
.map(StringBuilder::toString)
.get();
System.out.println(revertText);
public class Alternative {
public static void main(String[] args) {
Scanner robo = new Scanner(System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
char[] array = word.toCharArray();
int count = -1;
for (int i = 0; i < array.length; i++) {
if (Character.isUpperCase(array[i])) { //find the upper case letters in the word
for (int j = i; j > count; j--) //loop through the letters until the last count variable value is encountered
System.out.print(array[j]); //print the reversed values
count = i; //assign the last encountered uppercase letter's index value to count variable
}
}
}
}

Scanner - Matrix of char in Java

I just started learning this language and I have a problem trying to create a Matrix of type char from user input.
For example I want to read this as my input:
3 // this is an int n that will give me a square matrix[n][n]
.#.
###
.#.
For this example, this is what I have:
//...
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
char[][] matrix = new char[n][n]
for(int i = 0; i < n; i++){
matrix = stdin.nextLine();
}
Obviously this is wrong, and I know that. I'm just not seeing a way to correctly read this input.
If anyone could help me I would appreciate it.
ps: if possible, keep it simple, because like I said, I just started learning java :)
First, you need to add stdin.nextLine(); after reading n to skip the new line character.
Second, this is what you need inside your loop:
matrix[i] = stdin.nextLine().toCharArray();
This reads next line and converts it to an array of chars.
This is a runnable version of your question with output
import javafx.application.Application;
import javafx.stage.Stage;
import java.util.Arrays;
import java.util.Scanner;
public class MainNoFXML extends Application {
#Override
public void start(Stage stage) {
System.out.println("Enter Matrix Size:");
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
char[][] matrix = new char[n][n];
stdin.nextLine();
for(int i = 0; i < n; i++) {
System.out.println("Enter "+n+" Number of Chars");
System.arraycopy(stdin.nextLine().toCharArray(), 0, matrix[i], 0, n);
}
System.out.println("\nYour Matrix:");
for(int i = 0; i < n; i++)
System.out.println(Arrays.toString(matrix[i]));
}
public static void main(String[] args) { launch(args); }
}
Output:
Enter Matrix Size:
3
Enter 3 Number of Chars
.#.
Enter 3 Number of Chars
###
Enter 3 Number of Chars
.#.
Your Matrix:
[., #, .]
[#, #, #]
[., #, .]
First of all, thank you for all your answers.
I emailed my teacher and this was the solution he gave to me, if anyone is wondering:
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
stdin.nextLine();
char[][] matrix = new char[n][n]
for(int i = 0; i < n; i++){
String line = stdin.nextLine();
for(int j = 0; i < n; j++){
matrix[i][j] = line.charAt(j);
}
}
see code sample:
public class MatInput {
public static void main(String[] args) {
int matX = 3;
int matY = 3;
String matrix [][]=new String[matX ][matY];
Scanner input = new Scanner(System.in);
System.out.println("enter the strings for the Matrix");
for(int row=0;row<matX;row++){
for(int col=0;col<matY;col++){
matrix[row][col]=input.nextLine();
}
System.out.println("");
}
for(int r=0;r<matrix.length; r++) {
for (int c=0; c<matrix [r].length; c++) {
System.out.print(matrix [r][c] + " ");
}
System.out.println("");
}
input.close();
}
}

Counting dashes in sample data

I'm doing a task in which I am told to check for the '-'s in sample data, when a - is found in the data and there are adjacent dashes within the hashes, this only counts for 1 occurrence, e.g. in this sample data the answer would be 4.
I started by creating a 2D array to populate it then I was going to check for the dashes in the array but I am a bit puzzled as to how I would go about actually counting the occurrences, Any help would be appreciated.
Here's what I have so far;
Scanner input = new Scanner(System.in);
int a = input.nextInt(); //no. of rows
int b = input.nextInt(); //no. of columns
String arr[][] = new String[a][b]; //array of strings of 10 x 20
for(int i = 0; i<a; i++){
for(int j = 0; j<b; j++){
arr[i][j] = input.next();
}
}
//for test purposes
for(String[] s : arr){
for(String e : s){
System.out.print(e);
}
}
Here's the sample input:
10 20
#################---
##-###############--
#---################
##-#################
########---#########
#######-----########
########---#########
##################--
#################---
##################-#
Simplest way to use regex. Consider each row as string, trim string and then allow only 20 characters in string(based on your column count).
Other approaches could be to use DSL algos.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test {
public static void main(String... args) throws Exception {
Scanner input = new Scanner(System.in);
int a = input.nextInt(); // no. of rows
int b = input.nextInt(); // no. of columns
Pattern pattern = Pattern.compile("#(--+)#");
int count = 0;
for (int i = 0; i < a; i++) {
String temp = input.next().trim();
if (temp.length() > b) {
temp.substring(0, b);
}
Matcher matcher = pattern.matcher(temp);
if (matcher.find()) {
count++;
}
}
System.out.println(count);
}
}

Java Take String input from console

I was trying to take string input in java. My input should be like this
3
1,1,bugs#bunny.com,123 Sesame St.,New York,NY,10011,12345689010
1,2,bugs#bunny.com,123 Sesame St.,New York,NY,10011,12345689010
1,3,bugs#bunny.com,123 Sesame St.,New York,NY,10011,12345689010
So, I tried this
Scanner in = new Scanner(System.in);
int TotalNumber = in.nextInt();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.next();
}
in.close();
for (int counter = 0; counter < Data.length; counter++) {
System.out.println(Data[counter]);
}
My output is showing this
1,1,bugs#bunny.com,123
Sesame
St.,New
What is my problem ? How take input string line properly ?
Update
I found my solution at here Scanner issue when using nextLine after nextXXX
next() breaks at a whitespace. Instead, you should use nextLine() to input the entire line to your string:
int TotalNumber = in.nextInt();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.nextLine();
}
Try with Data[Counter] = in.nextLine();
What about:
import java.util.Scanner;
import java.lang.String;
public class Test
{
public static void main(String[] args)
{
char[] sArray;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a Palindrome : ");
String s = scan.nextLine();
s = s.replaceAll("\\s+", "");
sArray = new char[s.length()];
for(int i = 0; i < s.length(); i++)
{
sArray[i] = s.charAt(i);
System.out.print(sArray[i]);
}
}
}
Try this (Mureinik modified code)..
int TotalNumber = in.nextInt();
in.nextLine();
String[] Data = new String[TotalNumber];
for (int Counter = 0; Counter < TotalNumber; Counter++) {
Data[Counter] = in.nextLine();
}
You need a nextLine() after taking the int because you will press enter after taking int and that enter is read by nextLine() in the Data[0].

Repeating number in java to next line

I have a Java program that reads from a file like such
6 fun. 3 hello 10 <> 2 25 4 wow!
The number represents how many times the word will be repeated so output would be
fun.fun.fun.fun.fun.fun.
hellohellohello
<><><><><><><><><><>
2525
wow!wow!wow!wow!
However, mine is printing all on one line
import java.io.*;
import java.util.*;
public class Words {
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("aa1234.txt"));
printStrings(input);
}
public static void printStrings(Scanner input) {
while (input.hasNext)) {
int times = input.nextInt();
String word = input.next();
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
}
}
}
I've been playing around with input.nextLine() and whatnot, but don't understand how to get to the next line after it prints the repeated words. Help?
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.println();
print one new line after printing all the same words in one line.
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.println();
You can use System.out.print("\n") to print a line end.
Like this :
while (input.hasNext)) {
int times = input.nextInt();
String word = input.next();
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.print("\n");
}
You can also use the System.out.println() to print a line and automatically append a line end. For example, build the string before print it :
while (input.hasNext)) {
int times = input.nextInt();
String word = input.next();
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= times; i++) {
builder.append(word);
}
System.out.println(builder.toString());
}
Notice the use of StringBuilder, much more faster and consuming less memory than a classical string concatenation.
Issue:
mine is printing all on one line
Solution:
Because you have used System.out.print(), using that it will print everything on the same line. If you would want to have a line break then use System.out.println()
Use System.out.println to print the word on separate lines:
System.out.println(data)
Print a new line after the inner for loop. Something like this
while (input.hasNext())
{
int times = input.nextInt();
String word = input.next();
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.println();
}
make your function like below
public static void printStrings(Scanner input) {
while (input.hasNext)) {
int times = input.nextInt();
String word = input.next();
for (int i = 1; i <= times; i++) {
System.out.print(word);
}
System.out.println();
}
}

Categories