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.
Related
this is a lab for class I'm trying to do. Here's the instructions:
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
"Hello there
Hey
done"
the output is:
"ereht olleH
yeH"
And here's what I have right now:
public class LabProgram {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
String[] inputs = new String[100];
String input;
int i = 0;
while (true) {
input = scnr.nextLine();
if(input.equals("Done") || input.equals("done") || input.equals("d"))
break;
inputs[i] = input;
i++;
}
for (int j = 0; j < i; j++) {
int length = inputs[j].length();
String reverse = "";
for (int k = length - i; k >= 0; k--) {
reverse = reverse + inputs[j].charAt(k);
}
System.out.print("\n" + reverse);
}
}
}
Current output
What am I doing wrong??
Iterate through the array, and reverse elements at every index.
This solution is time consuming but does your job
for (int j = 0; j < inputs.lenght; j++) {
int length = inputs[j].length();
char a;
String rev = "";
for(int i =0; i< length; i++){
a = inputs[j].charAt(i);
rev = a + rev;
}
System.out.println(rev);
}
*Try to use StringBuilder And use method reverse -- #Artur Todeschini
To add to what Artur said, an ArrayList of StringBuilders could do the trick quite well:
for(StringBuilder nextEntry : stringBuilderList)
{
nextEntry.reverse();
}
The enhanced for-loop will go through each entry in the ArrayList, and the StringBuilder's reverse will change the order of the letters.
EDIT TO SHOW FORMATTING
ArrayList<StringBuilder> stringBuilderList= new ArrayList<>();
*note. given that this is for a lab, its probably for learning purposes and using built-in classes that does all the work for you are usually not the intended solution. -- #experiment unit 1998X
Try to use StringBuilder
And use method reverse
This is another "ArrayList and StringBuilder-less" version.
Create two Strings, one filled and one empty:
String nextString = stringArray[i],
template = new String();
Loop through the length of the String, adding the next character in from the end each time through.
int length = nextString.length() - 1;
for(int j = 0; j < length; j++)
{
template += nextString.charAt(length - j);
}
Add the whole String to the String array's index
stringArray[i] = template;
NOTE
This is an inner loop for a String array and is NOT complete code
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.
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++)
package learning;
import java.util.* ;
public class Learning {
public static void main(String[] args) {
String normal , cipher;
String shiftstr;
int shiftint, s;
System.out.println("Welcome To Ceasar Shift Creator");
Scanner in = new Scanner(System.in);
normal = in.nextLine();
char[] proc = normal.toCharArray();
int length;
length = normal.length();
System.out.println("Ok now tell me how many times you want it to be shifted ");
shiftstr = in.nextLine();
shiftint = Integer.parseInt(shiftstr);
s = 0;
for(int i =0; i < length ; i++){
while( s < shiftint){
proc[i]++;
s++;
}
System.out.print(proc[i]);
}
}
I wanted the whole word to be shifted forward the same no. of times as the user mentions. But only the first letter is shifted. I know I haven't done it quite correctly but still help me...
The inner while loop is only entered once, when i is 0. That's why only proc[0] is changed.
You don't need the inner loop:
for(int i =0; i < length ; i++){
proc[i]+=shiftint;
System.out.print(proc[i]);
}
s need to be set back to 0 in the for-Loop.
for (int i = 0; i < length; i++) {
while (s < shiftint) {
proc[i]++;
s++;
}
System.out.print(proc[i]);
s=0;
}
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
}