Checking if two characters are the same using == (Java) - java

I am trying to check if two characters are equal in a while loop but get this error when I run it:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:686)
at Practice.main(Practice.java:27)
My code:
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("String: ");
String firstIndex = input.next();
System.out.print("String Two: ");
String secondIndex = input.next();
int seqStart = -1;
int secCheck = 0;
int start;
if (firstIndex.length() >= secondIndex.length()) {
for (int firstCheck = 0; firstCheck <= firstIndex.length(); firstCheck++) {
if (firstIndex.charAt(firstCheck) != secondIndex.charAt(0)) {
continue;
}else if (firstIndex.charAt(firstCheck) == secondIndex.charAt(0)) {
start = firstCheck;
while (firstIndex.charAt(firstCheck) == secondIndex.charAt(secCheck)) {
for (int check = 0; secCheck < secondIndex.length(); check++) {
firstCheck++;
secCheck++;
if (check == secondIndex.length()) {
seqStart = start;
secCheck = (secondIndex.length() + 10);
}
}
}
}
}
}
System.out.println(seqStart);
}
}
The program is supposed to check if one String is contained within another and if so, it returns the location of where the second String started in the first. If not, it returns -1.
Any help would be greatly appreciated!

Your for loop says this:
for (int firstCheck = 0; firstCheck <= firstIndex.length(); firstCheck++)
The problem is that middle statement, firstCheck <= firstIndex.length(). The loop will run with firstCheck equal to firstIndex.length(). Then, when you use firstIndex.charAt(firstCheck), it will be out of range, because strings are zero-indexed, so there's no character at the position equal to the length of the string. You can fix that like this:
for (int firstCheck = 0; firstCheck < firstIndex.length(); firstCheck++)

Related

Why is my program constantly ending? How do I fix this?

import java.util.;
import java.io.;
public class Hangman {
public static void main(String[] args) throws Exception {
// read file and title
System.out.println("H A N G M A N");
System.out.println("________________________");
ArrayList<String> words = new ArrayList<String>();
ArrayList<Integer> indexes = new ArrayList<Integer>();
ArrayList<String> spaces = new ArrayList<String>();
File file = new File("C:\\Users\\nithi\\OneDrive\\Documents\\temp\\hangmanwords.txt");
Scanner reader = new Scanner(file);
Scanner input = new Scanner(System.in);
int numLives = 7;
while(reader.hasNextLine())
{
words.add(reader.nextLine()); // read a file using the Scanner class in this way.
}
int num = (int)(Math.random() * words.size()) + 1;
String word = words.get(num);
for(int i = 0; i < word.length(); i++)
{
spaces.add("_ ");
}
for(int i = 0; i < spaces.size(); i++)
{
System.out.print(spaces.get(i));
}
while(numLives > 7)
{
if(numLives == 0)
{
break;
}
System.out.println("Enter guess of letter: ");
String letterGuess = input.nextLine();
if(word.contains(letterGuess)) // if the word contains the letter guessed, then we must go through the word to find the indexes of each of the parts that contain the letterGuess. Replace all the indexes of the word with the letterGuess inputted.
{
for(int i = 0; i < word.length() - 1; i++)
{
if(word.substring(i, i + 1) == letterGuess)
{
indexes.add(word.indexOf(letterGuess));
}
}
for(int i = 0; i < word.length() - 1; i++)
{
if(word.charAt(indexes.get(i)) == '_')
{
word.replaceAll("_ ", letterGuess);
}
}
}
}
}
}
I have a problem with program constantly ending when running. How do I make it so it does not do this, and actually goes through until the end of my code?
I have tried getting rid of comments, I have tried commenting out certain parts of code, but all attempts have not resolved my issue. Is there anything I am missing here?
Your issue is that you start off by setting numLives to 7 and then you run a while loop for while (numLives > 7). This while loop will never run as the condition is never true.
I would suggest replacing the 7 with 0, meaning that the while loop will run for as long as the variable numLives is greater than 0. This also means that you can get rid of the check for if numLives is equal to 0 (see below):
while(numLives > 7)
{
if(numLives == 0)
{
break;
}
to
while(numLives > 0)
{
However, this will run forever as numLives is never decreased from 7. To fix this, I would suggest adding an else statement after the if statement that checks if the letter is in the word. Inside this else statement, you would decrease numLives (i.e. numLives--;), as the letter is not in the word.

New to programming, getting a run time error don't know why

Basically summarized in the title. https://ideone.com/E2BMS8 <-- that's a link to the code. I understand if you don't want to click it though so I'll paste it here as well. will just be disorganized. The code is supposed to flip the letters but keep words in the same position. I would like to figure that part out on my own though. Just need help with the run time error.
import java.util.*;
class Ideone {
public static void main (String[] args) throws java.lang.Exception {
Scanner input = new Scanner(System.in);
String sent, accum = "";
char check, get;
int len, count = 0;
System.out.print("Please enter the sentance you want reversed: ");
sent = input.nextLine();
len = sent.length();
for (int i = 0; i < len; i++) {
check = sent.charAt(len - i);
count += 1;
if (check == ' ') {
for (int p = 0; p < count; p++) {
while (p < count) {
get = sent.charAt(len - p);
accum += (get + ' ');
}
}
}
}
System.out.println("Reversed: " + accum);
}
}
The error String index out of range is cause because of the len is one more than the index range. Remove one on the index such I did below:
import java.util.*;
public class Ideone {
public static void main (String[] args) throws java.lang.Exception {
Scanner input = new Scanner(System.in);
String sent, accum = "";
char check, get;
int len, count = 0;
System.out.print("Please enter the sentance you want reversed: ");
sent = input.nextLine();
len = sent.length();
for (int i = 0; i < len; i++) {
check = sent.charAt(len - i - 1);
count += 1;
if (check == ' ') {
for (int p = 0; p < count; p++) {
get = sent.charAt(len - p - 1);
accum += (get + ' ');
}
}
}
System.out.println("Reversed: " + accum);
}
}
This is a classical "off by one" error -- something you will run into a lot as you find your programming feet. The issue in this case is the 0-based indexing. That is, the first character of a string is at index 0, and the last is at index "string length - 1". If we use sent = "Test"; as an example, then:
sent.charAt(0) == 'T'
sent.charAt(1) == 'e'
sent.charAt(2) == 's'
sent.charAt(3) == 't'
sent.charAt(4) == ??? // "That's an error, Jim!"
Note that index 4 -- which perhaps confusingly is also the length of the string -- is out of bounds. So, what happens during the first iteration of the loop, when i == 0:
check = sent.charAt(len - i); // ERROR! Because ...
==> = sent.charAt((4) - (0));
==> = sent.charAt( 4 ); // Doh!
I leave it to you to figure out how you might fix it.

Array out of bounds in Java?

I'm trying to run this code but I keep getting an out of bounds error. This is just the sub class for the super class "Simpler." The user enters in a string then the string is broken down into a char array. The array should not be smaller than the string yet I am getting this error. Can you tell me what I'm doing wrong? Thanks!
import java.util.*;
public class Encrypt extends Simpler
{
public void encryption()
{
boolean loop = true;
while(loop==true)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the phrase you'd like to encrypt: ");
String inPhrase = scan.nextLine();
char[] chars = inPhrase.toCharArray();
char tempArray[] = new char[chars.length+1];
tempArray = chars;
chars = new char[tempArray.length];
for (int i = inPhrase.length(); i<inPhrase.length(); i--)
{
if(chars[i]=='a')
{
chars[i]='1';
}
else if(chars[i]=='b')
{
chars[i]='2';
}
else if(chars[i]=='c')
{
chars[i]='3';
}
else if(chars[i]=='d')
{
chars[i]='4';
}
else if(chars[i]=='z')//I skipped some lines here for convienence
{
chars[i]='{';
}
else if(chars[i]==' ')
{
chars[i]='}';
}
}
String outPhrase = new String(chars);
System.out.println(outPhrase);
}
}
}
I think your for loop statement should look like this:
for (int i = 0; i < inPhrase.length(); i++)
if you're counting up, and like this:
for (int i = inPhrase.length() - 1; i >= 0; i--)
if you're counting down.
update
On looking back over it, I think there is more to it than that though.
I think your code needs to be rewritten:
String inPhrase = scan.nextLine();
char[] chars = inPhrase.toCharArray();
char tempArray[] = new char[chars.length()];
for (int i = 0; i < chars.length(); i++)
{
if(chars[i]=='a')
{
tempArray[i]='1';
}
.
.
.
.
}
String outPhrase = new String(tempArray);
No stop condition in the for loop, in this line:
for (int i = inPhrase.length(); i<inPhrase.length(); i--)
i gets 1, 0, -1, ... and wouldn't stop if -1 wouldn't throw an out of bounds exception
In for loop just changing the condition from i < inPhrase.length() to i >= 0 will do the job.
First thing:
for (int i = inPhrase.length(); i<inPhrase.length(); i--)
you never enter your loop because you assign i = n & entry condition is i < n.
it should be
for (int i = inPhrase.length()-1; i>=0; i--)
Now, this also removes your arrayoutofbound exception because earlier, you tried to access chars[n] which is actually the n+1 th character of that array.

Deleting Duplicate Characters in a String

Hi I need to fix this code to delete characters that repeat immediately in the string. For example: If I type aaabbbcccdeeff, it has to return abcdef at the end. However on the computer in class it returns something of a, "out of range (number)", the number being dependent on how many characters I used. On my mac however it just returns a number like 3 as an output and gives no error message. I am on Eclipse.
Please help, I didn't understand what the professor said and he rarely helps. The code is (somewhat helped by professor):
package firstProgramSimple;
import java.awt.Toolkit;
import java.util.Scanner;
public class SimpleVersion {
public static void main(String[] args) {
Scanner kb = new Scanner(System. in );
System.out.println("Entre String");
String string = kb.nextLine();
//System.out.println(string);
int length = string.length();
for (int i = 1; i < length; i++) {
if (string.charAt(i) != string.charAt(i - 1)) {
System.out.print(i);
} else if (string.charAt(i) != string.charAt(i)) {
System.out.print(i);
}
}
}
}
You need to print string.charAt(i) and not i.
Also, this piece of code is unnecessary since it will always return false:
//string.charAt(i) is always equal to itself
else if ( string.charAt(i) != string.charAt( i )) {
System.out.print(i);
Since you start at i = 1, the char at index 0 will never be printed. Before the for-loop, you should add this line:
System.out.print(string.charAt(0));
You are printing your loop counter and not the value of the char at the position of the counter:
System.out.print(i);
Should be:
System.out.print(string.charAt(i));
You will get an arrayOutOfBoundsException for inputs of size < 2. You might want to add this line once you have the string initialised:
if(string == null || string.length() < 2){
System.out.println(string);
return;
}
Something like this:
public static void main(String[] args) {
Scanner kb = new Scanner(System. in );
System.out.println("Entre String");
String string = kb.nextLine();
//System.out.println(string);
int length = string.length();
if(length < 2) {
System.out.println(string);
return;
}
System.out.print(string.charAt(0));
for (int i = 1; i < length; i++) {
if (string.charAt(i) != string.charAt(i - 1)) {
System.out.print(string.charAt(i));
}
}
}
Just replace your for loop like bellow:
System.out.print(string.charAt(0));
for (int i = 1; i < length; i++) {
if (string.charAt(i) != string.charAt(i - 1)) {
System.out.print(string.charAt(i));
}
}
The idea is, print the beginning character first, then print the character at i th position, only if its different then its previous character. Simple!

interviewstreet.com - String similarity

I'm trying to solve the string similarity question on interviewstreet.com. My code is working for 7/10 cases (and it is exceeding the time limit for the other 3).
Here's my code -
public class Solution {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String v1 = user_input.next();
int number_cases = Integer.parseInt(v1);
String[] cases = new String[number_cases];
for(int i=0;i<number_cases;i++)
cases[i] = user_input.next();
for(int k=0;k<number_cases;k++){
int similarity = solve(cases[k]);
System.out.println(similarity);
}
}
static int solve(String sample){
int len=sample.length();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(sample.charAt(j-i)==sample.charAt(j))
sim++;
else
break;
}
}
return sim;
}
}
Here's the question -
For two strings A and B, we define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings "abc" and "abd" is 2, while the similarity of strings "aaa" and "aaab" is 3.
Calculate the sum of similarities of a string S with each of it's suffixes.
Input:
The first line contains the number of test cases T. Each of the next T lines contains a string each.
Output:
Output T lines containing the answer for the corresponding test case.
Constraints:
1 <= T <= 10
The length of each string is at most 100000 and contains only lower case characters.
Sample Input:
2
ababaa
aa
Sample Output:
11
3
Explanation:
For the first case, the suffixes of the string are "ababaa", "babaa", "abaa", "baa", "aa" and "a". The similarities of each of these strings with the string "ababaa" are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.
For the second case, the answer is 2 + 1 = 3.
How can I improve the running speed of the code. It becomes harder since the website does not provide a list of test cases it uses.
I used char[] instead of strings. It reduced the running time from 5.3 seconds to 4.7 seconds and for the test cases and it worked. Here's the code -
static int solve(String sample){
int len=sample.length();
char[] letters = sample.toCharArray();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(letters[j-i]==letters[j])
sim++;
else
break;
}
}
return sim;
}
used a different algorithm. run a loop for n times where n is equals to length the main string. for each loop generate all the suffix of the string starting for ith string and match it with the second string. when you find unmatched character break the loop add j's value to counter integer c.
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Solution {
public static void main(String args[]) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(in.readLine());
for (int i = 0; i < T; i++) {
String line = in.readLine();
System.out.println(count(line));
}
}
private static int count(String input) {
int c = 0, j;
char[] array = input.toCharArray();
int n = array.length;
for (int i = 0; i < n; i++) {
for (j = 0; j < n - i && i + j < n; j++)
if (array[i + j] != array[j])
break;
c+=j;
}
return c;
}
}
I spent some time to resolve this question, and here is an example of my code (it works for me, and pass thru all the test-cases):
static long stringSimilarity(String a) {
int len=a.length();
char[] letters = a.toCharArray();
char localChar = letters[0];
long sim=0;
int sameCharsRow = 0;
boolean isFirstTime = true;
for(int i=0;i<len;i++){
if (localChar == letters[i]) {
for(int j = i + sameCharsRow;j<len;j++){
if (isFirstTime && letters[j] == localChar) {
sameCharsRow++;
} else {
isFirstTime = false;
}
if(letters[j-i]==letters[j])
sim++;
else
break;
}
if (sameCharsRow > 0) {
sameCharsRow--;
sim += sameCharsRow;
}
isFirstTime = true;
}
}
return sim;
}
The point is that we need to speed up strings with the same content, and then we will have better performance with test cases 10 and 11.
Initialize sim with the length of the sample string and start the outer loop with 1 because we now in advance that the comparison of the sample string with itself will add its own length value to the result.
import java.util.Scanner;
public class StringSimilarity
{
public static void main(String args[])
{
Scanner user_input = new Scanner(System.in);
int count = Integer.parseInt(user_input.next());
char[] nextLine = user_input.next().toCharArray();
try
{
while(nextLine!= null )
{
int length = nextLine.length;
int suffixCount =length;
for(int i=1;i<length;i++)
{
int j =0;
int k=i;
for(;k<length && nextLine[k++] == nextLine[j++]; suffixCount++);
}
System.out.println(suffixCount);
if(--count < 0)
{
System.exit(0);
}
nextLine = user_input.next().toCharArray();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories

Resources