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

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.

Related

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.

Checking if two characters are the same using == (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++)

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.

How to iterate a string in order to validate values are in range using charAt()?

I am trying to iterate a string that contains the users inputed values. I want to validate that the user only enters 4 characters and that all of them are between 1 and 4. For example, prompts the user to enter 4 values using commas, therefore they can only enter 1,2,3,4. If they enter anything else, then they will be asked again. I have included the section of my code where I am trying to perform the validation. I am also experiencing an unreachable code error which does not make sense to me. This takes place after I close the while (true) loop.
//Entering by ROWS
//This is for a 4x4 board size using rows
if (dataSelection == 1) {
if (boardSize == 1) {
int row = 1;
while (row < 5)
{
String row1Values4x4 = "-1";
while (true)
{
Scanner firstRow4x4 = new Scanner(System.in);
System.out.println("Please enter four values using commas for row " + row); //this needs to loop
row1Values4x4 = firstRow4x4.next();
row1Values4x4 = row1Values4x4.replaceAll(" ",""); //this is in case user enters numbers with spaces
for (int i = 0; i < row1Values4x4.length(); i++) {
char c = row1Values4x4.charAt(i);
if (row1Values4x4.length() == 7 && c == 48) //I entered 48 in order to test if it is using ascii value (48 = 0) {
break;
}
}
} //I think I need to include another break in order to escape the second loop?
String strArray[] = row1Values4x4.split(","); //This is where I get an unreachable code error
int arraySidesInteger[] = new int[strArray.length];
for (int i = 0; i < strArray.length; i++) {
arraySidesInteger[i] = Integer.parseInt(strArray[i]);
}
fourArray[row-1] = arraySidesInteger;
for (int i = 0; i < fourArray.length; i++) {
for (int j = 0; j < fourArray.length; j++)
System.out.print(fourArray[i][j] + " ");
System.out.println();
}
row++;
}
Please let me know if there
Your comment is right; you need a second break in there. The break that exists only breaks out of the for loop, but not the while loop.
Perhaps instead of
while (true)
{
// do some stuff
for (/* some other stuff */)
{
// even more stuff
if (/* should we break */)
{
break;
}
}
}
you could try something like
boolean done = false;
while (!done)
{
// do some stuff
for (/* some other stuff */)
{
// even more stuff
if (/* should we break */)
{
done = true;
break;
}
}
}
Why not use the split method in strings
String s = userInput;
String[] inputArray = s.split(",");
for(int i = 0; i < inputArray.length; i++){
// check if the character is correct here
}

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!

Categories

Resources