I wrote a program to test split words on a sentence. But, it errors me: out of bound!
String text = in.nextLine();
String[] pieces = text.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
It's the result:
the end oksg
the
end
oksg
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at LineByLine.main(LineByLine.java:13)
Command execution failed.
Line 13 is the "for" loop line.
Related
I have a task where I need to print words from an array in reverse(the word itself). This is what the task states :
Create an array of words called ‘wordList’ and assign the values ‘Stressed’, ‘Parts’, ‘Straw’, ‘Keep’, ‘Wolf’
Create a string called ‘reversedWord’ and do not assign it a value.
Similar to the above challenge, however, instead of reversing a sentence, reverse the order of the letters
within each string.
a. You will need to create a for-loop to access each word in turn. Immediately within the loop set
‘reversedWord = “”;’
b. Then create another for-loop inside of the first one to iterate backwards through the current
word. Update the value of ‘reversedWord’ on each iteration.
c. Print the reversed word on the screen.
STRETCH CHALLENGE: Handle the word so that it reads properly backwards. (Stressed becomes Dessert)
I don't know wether I'm just not understanding the wording of the task or not, but this is the code I have at the moment:
String[] wordList = {"Stressed", "Parts", "Straw", "Keep", "Wolf"};
String reversedWord;
for (int i = wordList.length; i >= 0; i++) {
reversedWord = "";
for (int j = wordList[i].length() - 1; i >= 0; j--) {
reversedWord += wordList[i].charAt(j);
System.out.println(reversedWord);
}
}
It gives me this error when i run it:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at Main.main(Main.java:22)
Any help explanation would be helpful.
There are a few issues here. In the line
for (int i = wordList.length; i >= 0; i++) {
you are setting i to be the length of the wordList, which is 5. Remember, though, that array indexes start at 0. So the valid indexes of wordList are 0, 1, 2, 3, and 4, but not 5. To fix this, you can just subtract 1 from the length.
for (int i = wordList.length - 1; i >= 0; i++) {
The next problem is that you are increasing i at the end of each loop. Since it seems like you're trying to iterate backwards, you're gonna want to decrease i, not increase it.
for (int i = wordList.length - 1; i >= 0; i--) {
There is a simpler solution using Java's StringBuilder class:
public static void main(String[] args) {
String[] wordList = {"Stressed", "Parts", "Straw", "Keep", "Wolf"};
for (int i = 0; i < wordList.length; i++) {
String word = wordList[i]; // Get the word from array
word = new StringBuilder(word).reverse().toString(); // use StringBuilder to reverse the word
wordList[i] = word; // put word back in the array
}
System.out.println(Arrays.asList(wordList));
}
This outputs
[dessertS, straP, wartS, peeK, floW]
UPDATE:
For the words to read properly (first character in uppercase), You could do something like this:
word = word.toLowerCase();
word = word.replace(word.substring(0,1), word.substring(0,1).toUpperCase());
wordList[i] = word; // put word back in the array
There are more effective ways to do this, but is simpler for you to understand. This obviously outputs:
[Desserts, Strap, Warts, Peek, Flow]
substring(0,1) returns the first character (substring from index 0 to index 1; where the last index is not inclusive) as a String. Then, you are replacing the same substring with the uppercase substring.
I have a program that asks the user for a String sentence and output its maximum occuring character and its occurences.
My issue here is that the function that counts the max character and its occurrences only counts that maximum character and its occurrences only for a single word(that is all lowercase) and not a full sentence or a word that starts with an uppercase.
If the user inputs a sentence, the program keeps having an index out of bounds in the freqLetter array (frequent letter array) in which I have no idea why it undergoes an out of bounds, does it have something to do with the whitespaces of the sentence? Should I create another loop in iterating the array or should I make another array?? (I am sometimes confused in manipulating indexes of arrays).
Code:
static void maxOccuringChar(char str[]) { // function that counts that max character and its occurences
char maxChar = ' ';
int freqLetter[] = new int[26];
int lengthString = str.length;
int maximum = -1;
for (int i = 0; i < lengthString; i++)
freqLetter[str[i] - 'a']++; // I'm not sure why it becomes out of bounds for some reason
for (int i = 0; i < 26; i++)
if (maximum < freqLetter[i]) {
maximum = freqLetter[i];
maxChar = (char)(i + 'a');
}
System.out.print(maxChar + " = " + maximum); // returns result
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char[] StringInput = in.nextLine().toCharArray(); // user inputs the given String sentence and puts into character array
maxOccuringChar(StringInput); // calls function and returns the maximum character and and its occurences
}
Output 1:
Elephant
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -28 out of bounds
for length 26
Output 2:
I am confused
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -24 out of bounds
for length 26
Output 3: // works fine here
hello
l = 2
Process finished with exit code 0
Your response would be highly appreciated and would indeed help me on this one!
Thank you very much everyone!!!
The problem occurs because the space code is 32. Change your loop to skip spaces
for (int i = 0; i < lengthString; i++) {
if(str[i] == ' ') {
continue;
}
freqLetter[str[i] - 'a']++;
}
ASCII Table
Also you can solve this using streams
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = in.nextLine();
System.out.println(input.chars()
.mapToObj(x -> (char) x)
.collect(Collectors.groupingBy(x -> x, Collectors.counting()))
.entrySet()
.stream()
.max(Comparator.comparingLong(Map.Entry::getValue))
.get());
}
Output:
123333
3=4
But it would count spaces as well. If you don't want to, then add this line after mapToObj(...)
.filter(c -> c != ' ')
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.
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().
I' re-doing an exam for practicing and i've almost completed it. The only problem i have is with this part:
int z=0,x=0;
String line="";
RandomAccessFile read = new RandomAccessFile(s, "rw");
while((read.readLine())!=null)
z++;
read.seek(0);
while(x<z){
line=read.readLine();
StringTokenizer stk = new StringTokenizer(line, " ");
if(line.charAt(0)=='r'){
nr=z;
nc=stk.countTokens()-1;
valori = new int[nr][nc];
while(stk.hasMoreTokens()){
stk.nextToken();
for(int i=0; i<nr; i++)
for(int j=0; j<nc; j++)
valori[i][j] = Integer.parseInt(stk.nextToken());}
}
else if(line.charAt(0)=='c'){
nr=stk.countTokens()-1;
nc=z;
valori = new int[nr][nc];
while(stk.hasMoreTokens()){
stk.nextToken();
for(int i=0; i<nr; i++)
for(int j=0; j<nc-1; j++)
valori[j][i] = Integer.parseInt(stk.nextToken());}
}x++;
Basically i have to read a file where i have the description of a matrix as follows:
c 0 1 0
c 0 0 1
c 0 0 0
c 1 0 0
And the resulting matrix would be
|0|0|0|1|
|1|0|0|0|
|0|1|0|0|
After reading the file i have to build the matrix with a 2d int array, i used the same code from another exercise but when using stk.nextToken() i get java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(Unknown Source)
I cannot find the error, 2d arrays are correctly initialized and filled.
Thanks in advance for any help.
The "Unknown Source" part of the exception is an effect of running your code through the jre instead of the JDK. If you run with the JDK, your runtime environment will have access to the debug info and proper line numbers will be printed instead.
a quick look suggests that this section is in error:
nr=stk.countTokens()-1;
nc=z; //z == # of rows
//first pass through = hasMoreTokens == true (a total of 4: C,0,1,0)
while(stk.hasMoreTokens()){
//first token - C
stk.nextToken();
//this will iterate 3 times
for(int i = 0; i < nr; i++)
//this, too, will iterate 4 times - a total of 12 times considering
// the outer loop
for(int j = 0; j < nc-1; j++)
// after 3 passes, this will throw the exception
valori[j][i] = Integer.parseInt(stk.nextToken());}
}x++;
This error means that there are no more tokens in the StringTokenizer remaining, and you are asking for a one more token. "Unknown source" is not relevant to your problem - this just means you have no access to the source code of the Java system library but I doubt it will be helpful.
This happens because the line you read from the file contains less space delimited tokens than you expect.
The error happens because you are tokenizing one single line, and in the two for loops you are reading columns and rows.
Instead of using the StringTokenizer with while loops I would recommend to use the .split command:
int j=0;
// read all rows
while((read.readLine())!=null) {
String line=read.readLine();
String[] columns=line.split(" ");
// read columns of each row
int i=0;
for (String column: columns) {
if (!column.equals("c")) {
valori[j][i] = Integer.parseInt(column);
}
i++;
}
j++;
}
PS: Pseudo code above, untested.