error on using uppercase in palindrome prog in java - java

package Assignments;
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
int i=0,j=str.length()-1,count=0;
while(i!=j) {
if(str.charAt(i)!=str.charAt(j)) {
count++;
break;
}
i++;
j--;
}
if(count!=0) {
System.out.println("Not a Palindrome");
}
else {
System.out.println("Palindrome");
}
}
}
Upon entering Uppercase letter in input it is showing error. "assa" as input is working fine but "Assa" is showing error.
I know it is a minor fault somewhere but I am new to java. Can anyone help?
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:709)
at Assignments.Assignment1.main(Assignment1.java:12)

a and A are not the same character. If you don't care about the case, you could convert all the character to lowercase (or to upper case) explicitly when comparing them:
while (i != j) {
if (Character.toLowerCase(str.charAt(i)) != Character.toLowerCase(str.charAt(j))) {
count++;
break;
}
i++;
j--;
}
EDIT:
The updated exception in the question clarifies the problem - it is unrelated to upper/lower case discrepancies, but to a wrong handling of strings with an even number of characters. To handle this you could use the < operator instead of !=:
while (i < j) {

A and a are not the same character, so it is normal that the string doesn't match.
What you could do is, before processing the string to see if it's a palindrome, you convert it to lowercase:
str = str.toLowerCase();

Replace
if(str.charAt(i)!=str.charAt(j))
with
if(Character.toUpperCase(str.charAt(i))!=Character.toUpperCase(str.charAt(j)))
Alternatively,
Replace
if(str.charAt(i)!=str.charAt(j))
with
if(Character.toLowerCase(str.charAt(i))!=Character.toLowerCase(str.charAt(j)))
The key is to compare the characters in the same case.
Apart from this, you also need to
replace
while(i!=j)
with
while(i < j)
in order to avoid StringIndexOutOfBoundsException.

Related

a program which identifies the differences between pairs of strings

My problem is that I need to identify characters which differ between the two given strings in a visually striking way. Output the two input strings on two lines, and then identify the differences on the line below using periods (for identical characters) and asterisks (for differing characters). For example:
ATCCGCTTAGAGGGATT
GTCCGTTTAGAAGGTTT
*....*.....*..*..
I have tried to write two string with each other but I dont know how to make the program check for every character in the string and see if those match
This is what I have done so far :/
System.out.println("String 1: ");
String var1 = Scanner.nextLine();
System.out.println("String 2: ");
String var2 = Scanner.nextLine();
if (same (var1, var2))
System.out.println(".........");
else
System.out.println("********");
public static boolean same (String var1, String var2){
if (var1.equals(var2))
{
return true;
}
else
{
return false;
}
Can anyone help me with this?
You need to loop through your Strings and compare characters one by one. To run through your list you can make a for-loop. Use an int as counter and use the method length() to obtain your string size.
for(int i=0; i<string1.length(); i++ {
// do stuff
}
Then since you have a counter going through all position of your string, you can obtain the character at a specific position in this string using the method charAt()
char char1 = string1.charAt(i);
Then compare the character to check if they are the same. If they are print a dot . if they're not print an asterisk *
if(char1 == char2) {
System.out.print(".");
} else {
System.out.print("*");
}
In the above part I supposed your two string have the same size. If it's not the case, you can first determine which one is the smallest (and so which is the biggest) :
String smallestString;
String biggestString;
if(string1.size() > string2.sise()) {
smallestString = string2;
biggestString = string1;
else {
smallestString = string1;
biggestString = string2;
}
Then make your for loop go through the smallest String, otherwise you will face IndexOutOfBoundsException.
for(int i=0; i<smallestString.length(); i++ {
// do stuff
}
And the end of this for loop print asterisks for the characters that left in the biggest String
for(int j=smallestString.length(); j<biggestString.length(); j++) {
System.out.print("*");
}
This is what I've come up with.Mind you there are better ways to do this and I've just written it with as much effort as you put in your question.
public class AskBetterQuestion{
public static void main(String[] args) {
// TODO Auto-generated method stub
String w1="ATCCGCTTAGAGGGATT";
String w2="GTCCGTTTAGAAGGTTT";
char[] first = w1.toCharArray();
char[] second = w2.toCharArray();
int minLength = Math.min(first.length, second.length);
char[] out=new char[minLength];
for(int i = 0; i < minLength; i++)
{
if (first[i] != second[i])
{
out[i]='.';
}
else out[i]='*';
}
System.out.println(w1);
System.out.println(w2);
System.out.print(out);
}
}

To find smallest word in a string in java

This is the code that i have written for finding the smallest word in a string but whenever i try to run it in eclipse it shows me an (String index out of range -2147483648) error in nested while statement, that i had marked , i do not understand the cause of it since my program seems to be running well in the range i.e less than length of the input string.
Thanks in advance!!
import java.util.Scanner;
public class Minword {
public static String minLengthWord(String input){
// Write your code here
int count[]=new int[50],i,j=0,len=input.length();
String output = "";
for(i=0;i<len;i++)
{
if(input.charAt(i)!=' ')
{
count[j]++;
}
else
j++;
}
int minidx=0;
for(i=1;i<j;i++)
{
if(count[minidx]>count[i])
minidx=i;
}
int words=0;
i=0;
while(words<=minidx)
{
if(words==minidx)
{
***while(i<len && input.charAt(i)!=' ')***
{
output+=input.charAt(i);
i++;
}
}
else if(i<len && input.charAt(i)==' ')
words++;
i++;
}
return output;
}
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String input,output;
input=s.nextLine();
output=minLengthWord(input);
}
}
I have problems following your code, but to get the shortest word's length, you can use a Stream and min(). Your minLengthWord method could be like:
String f = "haha hah ha jajaja";
OptionalInt shortest = Arrays.stream(f.split(" ")).mapToInt(String::length).min();
System.out.println(shortest.getAsInt());
You are using the variable i, which is a signed int, so it ranges from -2147483648 to 2147483647.
The following case shows your problem:
i = 2147483647;
i++;
After the increment, i's value will be -2147483648 due to a int overflow. Check this question.
It seems you are getting a huge input, thus it is causing the problem.
Well, -2147483648 is the maximal integer + 1. You have a wrap around. The variable i got so big that it start on the negative side again.
You have to use a long if you want to process texts that are larger than 2 GB.
while(words<=minidx)
{
if(words==minidx)
{
***while(i<len && input.charAt(i)!=' ')***
{
output+=input.charAt(i);
i++;
}
}
else if(i<len && input.charAt(i)==' ')
words++;
i++;
}
Your problem is you when words and minidx are both 0, your outer while loop is always true and words are always equal to minidx, and i keeps increasing until reaches its maximum number.
you need to add break after your inner while loop and secondly, you need to change i<j to i<=j
Below is the corrected code:
int minidx = 0;
for (i = 1; i <= j; i++) { //-------------------------> change i<j to i<=j
if (count[minidx] > count[i])
minidx = i;
}
int words = 0;
i = 0;
System.out.println(minidx);
while (words <= minidx) {
if (words == minidx) {
while (i < len && input.charAt(i) != ' ') {
output += input.charAt(i);
i++;
}
break; //-------------------------> add break statement here.
} else if (i < len && input.charAt(i) == ' ') {
words++;
}
i++;
}
When I tried running your code with an input of "Hello World", minidx was 0 before the while loop. words is also 0, so words<=minidx is true and the loop is entered. words==minidx is true (they're both 0), so the if statement is entered. Because it never enters the else if (which is the only place words is changed), words is always 0. So the loop becomes an infinite loop. In the meantime, i just keeps growing, until it overflows and becomes negative.
Here's a version that makes use of Java 8's Stream API:
Remove all your code from minLengthWord Method and paste below code it will work and resolve your runtime issue too
List<String> words = Arrays.asList(input.split(" "));
String shortestWord = words.stream().min(
Comparator.comparing(
word -> word.length()))
.get();
System.out.println(shortestWord);

To find the substring from string without library.I know its an easy one but i cant find where I am getting struck with that if statement

package stringoperation;
import java.util.Scanner;
public class Stringops {
public static void main(String [] args)
{
String string ;
String sub ;
Scanner in = new Scanner(System.in);
System.out.println("enter a string");
string =in.nextLine();
System.out.println("enter a substring to identify");
sub = in.nextLine();
char[] array= string.toCharArray(); // converting string to array of char
char[] subarray = sub.toCharArray(); //converting sub string to array of char
int count=0;
for(int j=0;j<array.length;j++)
{
if(array[j]==subarray[count]) //till both are same it will run
{
if(count==sub.length()-1) //if substring size is reached thats mean matched break out
{
System.out.println("substring is present");
break;
}
j++;
}
if(array[j]!=subarray[count]) // otherwise make count as 0 to proceed again
{
count=0;
}
}
}
}
The if statement I checked still can't find the error. I am missing something. Just tell me what I am doing wrong.
Try using string.indexOf(sub) != -1, after you're certain that the input strings are in the format you expect; i.e. control characters such as newlines aren't appended to your input data. It's necessary to keep in mind that comparisons will be failed if the Strings you're comparing don't match exactly, i.e.
"example" != "Example".

Comparing a string array index to a string

I'm having trouble comparing an array that holds a word that's broken up into letters. Here is my code: (it's part of a hangman game)
public static void isGuessCorrect( String guess, String wordInPlay, String[] hangmanScores){
String[] letterGuessedAgainst = wordInPlay.split("");
for (int i = 0;i < letterGuessedAgainst.length; i ++)
System.out.print(letterGuessedAgainst[i]);
System.out.println("Letter guessed against is: "+letterGuessedAgainst[1]);//testing purposes
System.out.println("My guess is: "+guess.charAt(0));//testing purposes
for (int i = 0;i < letterGuessedAgainst.length; i++){
if (letterGuessedAgainst.equals(guess.charAt(0))){//this line isn't working
System.out.println("they're equal");//want it to return this
}//end if
else
System.out.println("they're not");//returns this instead
}//end for
}//end method
guess is a String
holds a letter
wordInPlay is the word that is in play
letterGuessedAgainst is the letter of the word that is being played
hangmanScores is an array that only holds "_", corresponding to the number of letters in the word
Any help would be immensely appreciated! Thanks!
The problem is that letterGuessedAgainst is an array and you are trying to compare a String[] vs char
if (letterGuessedAgainst.equals(guess.charAt(0))){//this line isn't working
First of all, you have to use the index i in the loop
letterGuessedAgainst[i]
Secondly, you need to compare against guess and not guess.charAt(0) since you will not be able to do equals() when comparing String and char
Since you already defined that guess is a String the contains only 1 character then you could do:
if (letterGuessedAgainst[i].equals(guess)) {
Updated your code to start working:
public static void isGuessCorrect(String guess, String wordInPlay, String[] hangmanScores) {
char[] letterGuessedAgainst = wordInPlay.toCharArray(); //Changed to Char Array
for (int i = 0; i < letterGuessedAgainst.length; i++) {
System.out.print(letterGuessedAgainst[i]);
}
System.out.println("Letter guessed against is: " + letterGuessedAgainst[1]);//testing purposes
System.out.println("My guess is: " + guess.charAt(0));//testing purposes
for (int i = 0; i < letterGuessedAgainst.length; i++) {
if (letterGuessedAgainst[i] == guess.charAt(0)) {//Made == since they are all Chars now
//System.out.println("Nice guess! Here are all the "+guess+"'s in the word.");
//System.out.println(hangmanScores);
System.out.println("they're equal");//want it to return this
}//end if
else {
System.out.println("they're not");//returns this instead
}
}//end for
}//end method
There is likely other places that can be improved but this fixes your direct problem.
Rather then splitting into a number of single character String(s), I suggest you use wordInPlay.toCharArray(); then you could iterate that char[] with a For-Each loop (and I believe you wanted to either search the entire String and say the character was found or not; not whether each individual character matches) and your code might look something like
public static void isGuessCorrect(String guess, String wordInPlay,
String[] hangmanScores) {
char[] letterGuessedAgainst = wordInPlay.toCharArray();
char ch = guess.charAt(0);
System.out.println("My guess is: " + ch);
boolean found = false;
for (char letter : letterGuessedAgainst) {
if (letter == ch) {
found = true;
break;
}
}
if (found) {
System.out.printf("%s contains guess %c%n", wordInPlay, ch);
} else {
System.out.printf("%s does not contain guess %c%n", wordInPlay, ch);
}
}
You're comparing a char (which charAt() returns) to a string, which they are not equal. I would suggest using either character arrays, or also using charAt() on letterGuessedAgainst.
Source:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
if (guess.length==0) return null; // some kind of error handling
char quessedChar = guess.charAt(0);
for (int i = 0;i < letterGuessedAgainst.length; i++){
if (letterGuessedAgainst.charAt(i) == quessedChar ){
//System.out.println("Nice guess! Here are all the "+guess+"'s in the word.");
//System.out.println(hangmanScores);
System.out.println("they're equal");//want it to return this
}//end if
else
System.out.println("they're not");//returns this instead
}//end for
I would suggest at first place some code to validate your input data. You will fail if you will pass an empty string for guess.
Secondly you are comparing String with a character. Use above code.
Wouldn't you need to do
if (letterGuessedAgainst[i].charAt(0).equals(guess.charAt(0))){
instead of comparing an array to a char

Get the first instance of a letter from the string

I am working on this very simple method I know I am very close to finish it, but I am missing a detail. I appreciate any help. Thank you.
/**
Gets the first letter in this string.
#return the FIRST LETTER, or "" if there are no letters.
add1=AD3F add2=EF4G result=32SFB (BUT THESE ARE RANDOM ONLY INTS AND CHARS)
*/
public String firstLetter()
{
String line = add1+add2+result;
for(int i=0; i<line.length(); i++){
char ch=new Character(line.charAt(i));
if(Character.isLetter(ch)){
System.out.println("This is the first letter"+ch);
return ch;
}
else
System.out.println("No it is not a character: "+ch);
return "";
}
Your return type is String, but you're only trying to return a single character. Why not make it return a char, with \0 as the "no characters" return value - or possibly throwing an exception...
You also need to think about the ends of blocks - your if statement, your else clause, the loop, and the method itself. I would strongly recommend:
Using braces for all cases, even when there's only a single statement in the block (as per the else clause
Paying attention to indentation. It makes all the difference in clarity for this sort of thing.
You need to move the else code outside the loop so that it is only executed when you have tested all of the characters:
public class FirstLetter
{
public static void main(String[] args)
{
System.out.println(firstLetter());
}
public static String firstLetter()
{
String line = "AD3F" + "EF4G" + "32SFB";
for (int i = 0; i < line.length(); i++)
{
char ch = line.charAt(i);
if (Character.isLetter(ch))
{
System.out.println("This is the first letter: " + ch);
return Character.toString(ch);
}
}
System.out.println("No character found");
return "";
}
}
This kind of problem is more obvious when you format the code clearly.
I have kept the return type as String as per your original, but see also Jon Skeet's comments about changing that to char.
Your logic should look like this:
char ch;
for (int i = 0; i < line.length(); i++) {
ch = new Character(line.charAt(i));
if (Character.isLetter(ch)) {
System.out.println("This is the first letter" + ch);
return String.valueOf(ch);
}
}
System.out.println("No letters, sorry.")
return "";
As soon as a letter is found, it is reported and returned. But if the end of the end of the line is reached (i.e. the for loop completes), then obviously no letter was found, so report that and return an empty string.

Categories

Resources