I'm trying to get a user input and print the word starting from the last character and adding the previous one to the next line with one less space in the front, looking like it's aligned to the right.
but it shows there's an error in:
System.out.print(word.charAt(count));
Scanner input = new Scanner(System.in);
System.out.print("Enter word to print: ");
String word = input.nextLine();
System.out.println();
int line, space, count = -1;
for (line = word.length(); line > 0; line--){
for (space = line; space > 0; space--){
System.out.print(" ");
count++;
}
for ( ; count <= word.length(); count++){
System.out.print(word.charAt(count));
}
System.out.println();
}
error shows as:
Exception in thread "main java.lang.String.IndexOutOfBoundsException: S
at java.lang.String.charAt(String.java:658)
at HelloWorld.main(HelloWorld.java:22)
The problem is in your last for loop. count <= word.length() means that the loop will continue to run as long as count does not exceed word.length(), which is a problem because the index for each character in a String starts as 0, not 1.
So, for instance, if you enter a five-letter word, the for loop will run until count equals 5. On its final iteration, when count is equal to 5, it throws an IndexOutOfBoundsException because word only goes up to index 4 (the first character is at 0, the second is at 1, and so on, meaning the fifth character is at index 4).
So, instead of the exit condition for that for loop being count <= word.length(), it should be count < word.length().
Related
I am currently taking Programming 1 and learning Java. Here is my assignment...
Ask user to enter a number and then in a loop, find any 2 numbers that they are the same and next to each other. And then display the number in the loop. For example, if user enters 133455662, the program displays 356. For simplicity, assume user never will enter all three numbers the same and next to each other
Here is the code I've come up with, except I keep getting an error...
public static void main(String[] args){
String num = "";
String result = "";
System.out.println("Enter a number");
Scanner s = new Scanner(System.in);
num = s.next();
int len = num.length();
for(int n = 0;n<len;n++){
char c = num.charAt(n);
char c2 = num.charAt(n+1);
if(c == c2){
result = result + c;
}
}
System.out.println(num);
}
This is the error I get...
run: Enter a number 001123455 Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range:
9 at java.lang.String.charAt(String.java:658) at
CS120_Labs.Homework09_C.main(Homework09_C.java:18)
C:\Users\Fletcher\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1 BUILD FAILED (total time: 6 seconds)
Thanks again for anyone that can help!
Exception said that StringIndexOutOfBoundsException, so you need two changes to make it work:
Add "-1" to fix error "for (int n = 0; n < len - 1; n++) {"
And also at the end of the program you need change from "num" to "result" System.out.println(result);
public static void main(String[] args) {
String num = "";
String result = "";
System.out.println("Enter a number");
Scanner s = new Scanner(System.in);
num = s.next();
int len = num.length();
for (int n = 0; n < len - 1; n++) {
char c = num.charAt(n);
char c2 = num.charAt(n + 1);
if (c == c2) {
result = result + c;
}
}
System.out.println(result);
}
I think all you need to do is to change your for line like (updated to len-1):
for(int n = 0; n<len-1; n++){
...
}
Change your for loop as
for(int n = 0; n < len - 1; n++)
since you are looking up the character at index n and len+1 in the for-loop body, you should loop from 0 to len-1
In addition to the other answers here that just "give" you the solution, I wanted to add:
This is a common problem when you first start out using structures that are "0" indexed. For example, if we have the letters A-I:
0 1 2 3 4 5 6 7 8
A B C D E F G H I
There are 9 letters there, so length() will return 9. The problem is, the letter at the first position isn't 1, it's 0. If in a loop you count all the way up to 9, the last iteration of the loop's charAt line will say "Take the character at position 9" but 9 is out of range of available positions, hence the exception String index out of range: 9.
This can happen anytime you are referencing an object in a structure that has positional indexes. When you see an exception like this, the first thing to check is why did my code try to access an index that didn't exist. In this case, the answer is the upper bound of the for loop. There are other possibilities; for example, your index variable (in this case i) is modified inside the loop, or if the lower bound is negative.
My code below is giving the following error and I can't figure out why. I am trying to reorder the entered word ("Polish" for example) in the order of:
(First letter, last letter, second letter, second last letter, third letter... so on) so the output should be "Phosli".
Updated code
public static String encodeTheWord(String word1)
{
int b = 0;
int e = word1.length()-1;
String word2 = "";
for (int i=0; i<e; i++)
{
word2 = word2 + word1.charAt(b) + word1.charAt(e);
b+=1;
e-=1;
}
System.out.println(word2);
return (word2);
}
For a word with an even amount of characters (Polish), the order of the characters becomes 051423, so the maximum value of b is 2 and the minimum value is e is from 5 to 3. Thus, your loop should decrement e and increment b twice (so you run the loop for word1.length() / 2 times). Also,
int e = word1.length();
Would need to be:
int e = word1.length() - 1;
For words of an uneven length (word1.length() % 2 > 0) you need an extra check or you will repeat the middle character.
your for loop is wrong, you can get a char at index 0, until the word1.length()-1...
must be
for (int i=0; i<word1.length()-1; i++)
the same applies for this...
word1.charAt(e);
because you defined e as word1.length()
My NEW sample text i was testing: My mom is a good cook. Although sometimes at around noon she will leave and forget to make me lunch and some pop. #Old homework become relevant again
my problem is just that i am not getting the correct output, as my method only prints *Mom a noon i
This is all GUI based.I am reading in a file and checking for palindromes and printing them out in my JTextArea afterwards using Stacks and Queue's.
Issue is, all of this is working and when i start the program and attach the text file, i only get the first palindrome. SO it will print "mom" which is my first testcase, but it won't go to any of the other palindromes following it?
I thought i might have got bogged down in my code blocking at some point but after tinkering with it for a day now i'm sort of stuck.
EDIT 1: I am now getting more results
my method is,
public void fileDecode() throws FileNotFoundException
{
if (fileChoice.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
file = fileChoice.getSelectedFile();
scanInput = new Scanner(file);
while(scanInput.hasNext())
{
int nextPalindrome = 0;
int counter = 0;
String token = scanInput.next();
Stack<Character> stk = new Stack<Character>();
Queue<Character> que = new LinkedList<Character>();
for (int i = 0; i < token.length(); ++i)
{
stk.push(token.charAt(i)); //pushing all char's onto the stack/queue
que.add(token.charAt(i));
}
for (int j = 0; j < token.length(); ++j)
{
char tempStk = stk.pop(); //removing them one at a time and checking if they are equal and incrementing counter
char tempQue = que.remove();
if (tempStk == tempQue)
{
counter++;
}
}
if (counter == token.length())
{
build.append(token + " "); //if the counter # was the same as the token's length, than it is indeed a palindrome and we append it into our StringBuilder that we pass to the JTextArea
nextPalindrome = token.length();
}
}
}
}
You set counter to 0 outside your while loop, so the count of the second word is going to start at the count of the first word. Move counter = 0 inside the while loop and it should work.
Also, nextPalindrome doesn't appear to be used, and even if it is, if you set it at the bottom of the loop, it's immediately set to 0 at the top, so it will only remain non-zero if the last word is a palindrome.
Also, think about what's happening in the second for loop. You're looping over all the characters and comparing the one from the stack and the one from the queue. If ever those are different, you know you don't have a palindrome, so once you find a difference, it's pointless to continue with the loop. You also already have a loop counter, j, so you don't need another one. So I'd rewrite the second loop and following condition as follows:
for (int j = 0; j < token.length(); ++j)
{
char tempStk = stk.pop(); //removing them one at a time and checking if they are equal and incrementing counter
char tempQue = que.remove();
if (tempStk != tempQue)
break;
}
if (j == token.length())
That works because the only way j can equal token.length() after the loop is done is if the loop completed, which can only happen if no pairs of characters aren't equal (in other words, all pairs of characters are equal, which is what you want).
I am iterating over a file and getting the number of characters in each word. When I find the length of each word it is putting the int value of the amount of characters into that array index position. I can't figure out why or how to solve it. I have then even tried to re-iterate over the array and divide each int by it's index position, but couldn't figure out why I kept getting a / by 0 exception. Below is my code. The txt file I am using has 1 two letter word and 2 three letter words. The output is Frequency of words with 2 characters is 2 (should be 1) and Frequency of words with 3 characters is 6 (should be 2). For this assignment we only need to count the frequency for all words <23 characters and group all above 23 characters into the the last array index position. Below is my code. Any help would be greatly appreciated.
private final int WORDLENGTH = 23;
private int[] wordLengthCount = new int [WORDLENGTH];
while (token.hasMoreTokens()){
token1 = token.nextToken();
for (int t = 0; t<token1.length(); t++){
wordLengthCount[token1.length()-1]++;
}
This code here
token1 = token.nextToken(); //Getting your token
for (int t = 0; t<token1.length(); t++) //For each character in token
{
wordLengthCount[token1.length()-1]++; //Increment count array
}
Is incrementing the count array for the number of characters in your String token1. Hence
1 * 2 character word = 2
2 * 3 character word = 6
You don't need your for loop here, just do this in your while loop
token1 = token.nextToken(); //Get token
wordLengthCount[token1.length()-1]++; //Increment your count array
while(token.hasMoreTokens()){
token1 = token.nextToken();
wordLengthCount[token1.length()-1]+=1;
}
You don't need to to iterate over every character for each token. Just reference the index in your array referred to by the number of letters in the word you are examining.
So here you'll see for a 3 letter word:
wordLengthCount[3 -1] +=1;
//so wordLengthCount[2] = 1 now
Or for a 2 letter word:
wordLengthCount[2 -1] +=1;
//so wordLengthCount[1] = 1 now.
If you want to know the number of characters, you can get them by multiplying the index of the element you are examining by the value of that index like so:
//this will give you number of 3 letter word characters in file.
wordLengthCount[2] *= 3;
//or more useful, print out all frequencies and the number of characters in file
//which contributed to frequency
for(int i=0;i<wordLengthCount.length;i++){
System.out.println("Frequency for "+(i+1)+" letter words = "
+wordLengthCount[i]+", characters = "+(wordLengthCount[i]*(i+1)));
}
I'm trying to make this program to count the number of consecutive characters
and I'm getting the error that says:
"String index out of range."
import javax.swing.*;
public class Project0 {
public static void main(String[] args){
String sentence;
sentence = JOptionPane.showInputDialog(null, "Enter a sentence:"); /*Asks the user to
enter a sentence*/
int pairs = 0;
for (int i = 0; i < sentence.length(); i++){ //counts the pairs of consecutive characters
if ( sentence.charAt(i) == sentence.charAt(i+1)) pairs++;
}
JOptionPane.showMessageDialog(null, "There were " + pairs + " pairs of consecutive characters");
}//main
}// Project0
The last element in your loop is 100% guaranteed to cause a problem. Perhaps only go to the length - 1 in your loop?
Consider the code:
for (int i = 0; i < sentence.length(); i++){
if ( sentence.charAt(i) == sentence.charAt(i+1)) pairs++;
}
String s = "AABBCC";
first loop, i = 0 : compare s[0] to s[1]
first loop, i = 1 : compare s[1] to s[2]
first loop, i = 2 : compare s[2] to s[3]
first loop, i = 3 : compare s[3] to s[4]
first loop, i = 4 : compare s[4] to s[5]
first loop, i = 5 : compare s[5] to s[6] // WOAH, you can't do that! there is no s[6]!!
sentence.charAt(i+1) will cause this as i + 1 > sentence.length() at the last step of the for-loop
You need to change the upper limit of your for loop to not go all the way to the end because the way you look for consecutive characters is "look at the ith character, and then look at the next
one". Once you get to the end, there is no "next one", so just stop at the next to last one.
for (int i = 0; i < sentence.length()-1; i++)