Java program keeps crashing - java

keeps crashing when i run it, its a palindrom tester ( if a word is the same spelt forwards and backwards) and i want it to remove any non word characters and become lower case. Can anyone spot the problem? or give some tips? im trying to avoid using any "try" "for" stuff etc.. just while and if statements for a project. here is my output:
Enter a possible palindrome :
p.oop
here it is : poop
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(Unknown Source)
at Driver.main(Driver.java:27)
import java.util.*;
public class Driver
{
public static void main(String[] args)
{
String str, another = "y";
int left, right;
Scanner scan = new Scanner(System.in);
while (another.equals("y"))
{
System.out.println("Enter a possible palindrome : ");
str = scan.nextLine();
String palindromToLowerCase = str.toLowerCase();
String finalPalindrom = palindromToLowerCase.replaceAll("\\W", "");
left = 0;
right = str.length() - 1;
System.out.println("here it is : " + finalPalindrom);
while (finalPalindrom.charAt(left) == finalPalindrom.charAt(right) && left < right)
{
str.toLowerCase();
left++;
right--;
}
System.out.println();
if (left < right)
{
System.out.println("that string is NOT a palindrom");
}
else
{
System.out.println("This string IS a palindrom");
}
}
}
}

change:
right = str.length() - 1;
to:
right = finalPalindrom.length() - 1;

Related

getting an error in my palindrome java program

I have created a palindorme java program which is getting an error.the error is saying int cannot be converted to boolean.
import java.util.Scanner;
public class palindrome
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int l,i;
String s,s1;
System.out.println("Enter your string");
s = sc.nextLine();
l = s.length();
for(i=0;l-i-1;i++)
{
s1 = s + s.charAt(i);
}
if(s1==s)
System.out.println("This is Palindrome");
else
System.out.println("This is not a Palindrome");
}
}
For loop condition seems wrong.
for(initial counter; condition to terminate; increase counter) {}
for(i=0; i<l; i++) {}
Along with the answer above you can try a different approach. You don't need to go all the string length to check a palindrome. A palindrome can be checked iterating half of the array length like this -
public void checkPalindrome(String strToCheck){
char[] arr = strToCheck.toCharArray();
int size = arr.length;
char [] original = Arrays.copyOf(arr,arr.length);
for (int i = 0; i < size / 2; i++) {
char temp = arr[i];
arr[i] = arr[size-i-1];
arr[size-i-1] = temp;
}
if(Arrays.equals(arr, original)) {
System.out.println("Palindrome");
} else {
System.out.println("Not a palindrome");
}
}
What are done here:
reversing the string first iterating the halfway
comparing the reversed string with the original using Arrays.equals() method.
There are quite a few things off here, first here is the fixed code:
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
int l,i;
String s = "",s1 = "";
System.out.println("Enter your string");
s = sc.nextLine();
l = s.length();
for(i = l - 1; i >= 0; i--)
{
s1 = s1 + s.charAt(i);
}
if(s1.equals(s))
System.out.println("This is Palindrome");
else
System.out.println("This is not a Palindrome");
}
The first thing to fix was your for loop, as you saw you were getting an error. This was fixed by setting the initial i to the length minus 1, changing the loop condition to i >= 0, and using i-- to subtract 1 from i each loop.
These changes to the loop were made so that the character starting from the last position in the String is the first one being return by s.charAt(i) so you can reverse the String. I think you were attempting to do something along these lines to add the characters starting from the end to a String.
I also changed s1 = s + s.charAt(i) to s1 = s1 + s.charAt() so the correct String is being appended. (This should probably be StringBuilder however).
s and s1 now have the initial condition of "" instead of nothing.
And finally you cannot compare String equality with ==, it must be s1.equals(s).
Test Run:
Enter your string
racecar
This is Palindrome

Starting with the last character and iterating backwards by 3

I am trying to create a code that takes any string and relays it back to me backwards missing every 3rd character and including the very last character.
EX: "123456789" should return "963" &
"Hello, World!" should return "!r lH"
import java.util.Scanner;
public class cypher {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String reverse = "";
System.out.println(str.length());
for (int i = str.length() - 1; i >= 0; --i) {
reverse = reverse + str.charAt(i - 3);
}
System.out.println(reverse);
}
}
The code above is what I have so far. However when I run this code I get this error message: "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1"
I don't understand because the string length is 10 so why is it not able to do this? Could someone explain this to me and give me a suggestion on how to fix this?
I suggest just iterating the characters in the string, starting from the last position, and moving backwards in increments of 3:
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String reverse = "";
for (int i=str.length()-1; i >= 0; i=i-3) {
reverse += str.charAt(i);
}
System.out.println(reverse);
Your current approach is failing because the loop just takes single, not triple steps. Also note that you might want to use StringBuilder instead of String to build the reverse string. This might be more efficient (though the JVM itself might substitute StringBuilder on its own).
You current logic is str.charAt(i - 3) and continue while i >= 0. The str.charAt(i - 3) statement will generate java.lang.StringIndexOutOfBoundsException when i is less than 3, thus you should change your code to this.
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String reverse = "";
System.out.println(str.length());
for (int i = str.length() - 1; i >= 0; i = i - 3) {
reverse = reverse + str.charAt(i);
}
System.out.println(reverse);
}
According to your current logic str.charAt(i - 3) here when value of i becomes less than 3, your code will try to access and index that is a -ve number and thus throws this exception.
You'll have to check if i - 3 >= 0 before using str.charAt(i - 3) else break out of the loop.
I tried this code in my system and it works fine. Try this:
import java.util.Scanner;
public class cypher {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String reverse = "";
System.out.println(str.length());
for (int i = str.length() - 1; i>= 0; i-=3) {
reverse = reverse + str.charAt(i);
}
System.out.println(reverse);
}}
Changed your code a little and this works fine now.
You were getting the java.lang.StringIndexOutOfBoundsException because your for loop decremented by a single step every time instead of the required step of 3. As a result when the string has less than 3 characters left the value of variable i becomes negative and an exception is thrown when the charAt(i) function is called with a negative value.
import java.util.Scanner;
public class cypher {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String reverse = "";
System.out.println(str.length());
int i = str.length() - 1;
while(i >= 0)
{
reverse = reverse + str.charAt(i);
i-=3;
}
System.out.println(reverse);
}
}

Why won't while loops find a palindrome in java?

i dont know if i am just doing this wrong, but using eclipse ill run it and enter a word but it won't return anything. i suck at coding so please help.
import cs1.Keyboard;
public class Palindrome
{
public static void main (String[]args)
{
System.out.print("Enter a word: ");
String w = Keyboard.readString();
int a = 0;
char n = w.charAt(a);
char j = w.charAt(w.length()-1);
while(a < j);
{
if (j!=n)
System.out.println("This word isnt a palindrome... try again.");
if (j==n)
{
j--;
a++;
}
System.out.println("This is a palindrome!");
}
}
}
Try writing
char j = w.charAt(w.length() - a);
and, when incrementing a in the while loop, update the indexes
n = w.charAt(a);
j = w.charAt(w.length()-1);
Also, make sure Keyboard.readString() returns a String. Try using Scanner.

out of bounds error with word count

I'm trying to write my own Java word count program. I know there may already be a method for this, but I'd like to get it work. I'm getting an out of bounds error at line 14. I'm trying to use an input word to count how many times it appears in an input string. So I'm looping up to stringlength - wordlength, but that's where the problem is.
Here is the code:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print( "Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
First of all, two Scanners are not necessary, you can do many inputs with the same Scanner object.
Also, this if condition
if (match(substring, word) == true)
can be rewritten like
if (math(substring, word))
I would also recommend you to use i++ to increase the loop variable. Is not strictly necessary but is "almost" a convention. You can read more about that here.
Now, about theIndexOutOfBoundsException, I've tested the code and I don't find any input samples to get it.
Besides, there is an issue, you are missing one iteration in the for:
for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1'
String substring = string.substring(i, i + word.length());
// System.out.println(substring);
if (match(substring, word)) {
count++;
}
}
You can test it by putting a print statement inside the loop, to print each substring.
I'm not getting an out of bounds error, can you tell me what values you were using for word and string?
I have identified a bug with your program. If word is equal to string, it still returns count 0. I suggest adding one more iteration and using regionMatches instead. RegionMatches makes your match method obsolete and will return false if word.length() + i is equal or greater than string.length(), avoiding out of bounds issues.
As you can see I also moved the calculations to a seperate method, this will make your code more readable and testable.
And as Christian pointed out; you indeed do only need one Scanner object. I've adapted the code below to reflect it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter word : ");
String word = sc.nextLine();
System.out.print("Enter string: ");
String string = sc.nextLine();
int count = calculateWordCount(word, string);
System.out.println("There are " + count + " repetitions of the word " + word);
}
private static int calculateWordCount(String word, String string) {
int count = 0;
for (int i = 0; i < string.length() - word.length() + 1; i++) {
if (word.regionMatches(0, string, i, word.length())) {
count++;
}
}
return count;
}

Picking out parentheses out of a String in Java

I am new to Java and trying to finish a program that will read a statement by the user and and scan to see if the amount of LEFT parenthesis match the RIGHT. The person who started the program created a stack but never made any use of it so I left it alone since I'm not very good with stacks. However, I was able to create a loop to to go through every character in the String to find the parenthesis, compare them, then print out if they are even or not. However I am having trouble with the while loop that goes through the String to find all parentheses. It's not working for some reason and I don't understand why. Any explanation on how to make this work will be greatly appreciated.
import java.util.*
public class ParenMatch
{
public static void main (String[] args)
{
Stack s = new Stack();
String line; // the string of characters to be checked
Scanner scan = new Scanner(System.in);
System.out.println ("\nParenthesis Matching");
System.out.print ("Enter a parenthesized expression: ");
line = scan.nextLine();
char parenline[] = new char[line.length()];
int x;
while(x < parenline.length) {
parenline[x] = line.charAt(x);
x++;
}
int l,r,i,morel,morer = 0;
while (i > parenline.length) {
if (parenline[i] == "(" )
l++;
if (line.charAt(i) == ")")
r++;
i++;
}
if (l > r) {
morel = l-r;
System.out.println("There are " +morel+ " more left parentheses than right");
}
if (r > l) {
morer = r-l;
System.out.println("There are " +morer+ " more right parentheses then left");
}
if (r == l) {
System.out.println("The amount of left and right parentheses are even.");
}
}
}
You need to initialize x so for example.
int x = 0;
You cannot increment an uninitialized variable.
Also to define parenline instead of looping and adding the char at the locations in the string just using one of the strings native methods:
char parenline[] = line.toCharArray();
Sorry if i explained this badly.
You had following mistakes:
not initializing
using double quote instead of single quote
checking whether i is greather than parenline.length
This is the correct code block:
int x=0;
...
int l,r,i,morel,morer;
l=r=i=morel=morer= 0;
while (i < parenline.length) {
if (parenline[i] == '(' )
l++;
if (line.charAt(i) == ')')
r++;
i++;
}
I made some changes to your code, it works fine.
However, the approach using Stack is better because allows you not only see if the amout of parenthesis is equal, but to see if the expression is correct. For example, if you have something like that: (x+y))+(x-(y+x) then your program can't tell that this is an incorrect expression because the amount of opening and closing parenthesis is equal.
import java.util.*;
public class Stackpr {
public static void main (String[] args)
{
String line; // the string of characters to be checked
Scanner scan = new Scanner(System.in);
System.out.println ("\nParenthesis Matching");
System.out.print ("Enter a parenthesized expression: ");
line = scan.nextLine();
int l = 0;
int r = 0;
for (int i = 0; i < line.length(); i++){
if (line.charAt(i) == '(')
l++;
else if (line.charAt(i) == ')')
r++;
}
if (l > r)
System.out.println("There are " + (l-r) + " more left parentheses than right");
else if (l < r)
System.out.println("There are " + (r - l)+ " more right parentheses then left");
else
System.out.println("The amount of left and right parentheses are even.");
}
}

Categories

Resources