Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Below is a simple program which searches for sequential characters. However I get an exception because I'm searching outside of the array index. I understand why it occurs but unsure how do I manage this?
public static void main(String [] args)
{
String term = "Popeye's fishCat";
String query = "P's SalmonCat";
int score = 0;
char [] termChar = term.toCharArray();
char [] queryChar = query.toCharArray();
if((queryChar[0]) == (termChar[0]))
{
score++;
}
for(int i = 0; i < queryChar.length; i++)
{
for(int j = 0; j < termChar.length; j++)
{
if(queryChar[i] == termChar[j] )
{
if((queryChar[i + 1]) == (termChar[j + 1])) //Causes an exception
{
System.out.println((queryChar[i + 1]) + " " + (termChar[j + 1]));
score++;
break;
}
}
}
}
System.out.println(score);
}
Adjust your loop conditions:
for(int i = 0; i < queryChar.length - 1; i++) {
for(int j = 0; j < termChar.length - 1; j++)
Note the added -1
If you always look at the next item in the loop, you can't loop to the last item, because it doesn't have a next item.
Just remove i +1 or j+1 in this bit
if((queryChar[i + 1]) == (termChar[j + 1])){
System.out.println((queryChar[i + 1]) + " " + (termChar[j + 1]));
score++;
break;
}
As legnth returns the size of the array, counting the first element as 1, but when getting elements from an array, the first is labeled zero. Using length - 1 ( the highest possible value in that loop, as when i = length the loop stops), and then adding 1, tries to refer to array[length], which doesn't exist. As it starts at zero, so the last element is array[length-1]
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
public class Sum_of_Numbers {
public static void main( String [] args) {
int sumOfEven = 0;
int sumOfOdd = 1;
int even_Times = 0;
int odd_Times = 0;
while ((even_Times < 12) || (odd_Times < 13)); {
sumOfEven = sumOfEven+2;
even_Times = even_Times+1;
sumOfOdd = sumOfOdd + 2;
odd_Times = odd_Times + 1;
System.out.println("The sum of even integers is " + sumOfEven);
System.out.println("The sum of odd integers is " + sumOfOdd);
}
System.out.println("The sum of even integers is " + sumOfEven);
System.out.println("The sum of odd integers is " + sumOfOdd);
}
}
When I run this code, the loop fails to start and I don't know why.
You've used the wrong syntax with the while statement and it's in an infinite loop
while ((even_Times < 12) || (odd_Times < 13)); {
The semi-colon is closing the statement, so only the conditions within the while loop are executed. even_Times and odd_Times don't increment, so it loops forever.
When the semi-colon is removed, the following { } block will execute within the while loop.
while ((even_Times < 12) || (odd_Times < 13)) {
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
class arr{
//array sorting to find maximum value
public static void main(String[]args){
int[] array={1,6,4,5,2};
int n;
int i,j;
for( i=0;i<(array.length*2);i++){
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
}
System.out.println(array[array.length]);
}
}
>
Can anyone tell me why i am getting runtime error and this sorting method will work or not?
Dont reinvent the wheel.., you are able to use arrays, so then use the array help class too...
:-)
public static void main(String[] args) {
final int[] array = { 1, 6, 4, 5, 2 };
System.out.println("Array before sort " + Arrays.toString(array));
Arrays.sort(array);
System.out.println("Array before sort " + Arrays.toString(array));
}
you will likely have an indexOutOfbounds exception because your second loop:
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
J loops through teh array then you attempt to index the array at J + 1 which on the last element in the array would push it out of bounds thus throwing an outOfBoundsException
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
Since array.length = 5 and j < array.length, the value array[j+1] in the last round of the inner loop cause array out of bound exception.
The swap needs another variable to hold array[j] before changing it.
e.g:
int x;
for( j=0;j<array.length - 1;j++){
if(array[j]>array[j+1]){
x = array[j];
array[j]=array[j+1];
array[j+1]=x;
}
}
The bubble sort algorithm can be implemented as follows
public static void sort(int[] arr){
int len = arr.length;
int k = 0;
for(int j = 0 ; j < len-1; j++){
for(int i= 0+k; i < len-1; i += 2){
if(arr[i] <= arr[i+1])
continue;
int tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
}
k++;
if ( k % 2 == 0)
k = 0;
} }
The inner loop must alternately start at indexes 0 and 1 so as not to always swap the same pairs (k variable).
The others have already pointed out why you're getting an exception.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I try to print the odd numbers in Java that are inside the array but this algorithm doesn't work ... May someone help me ?
The printing result is that :
"Exception in thread "main" .java.lang.ArrayIndexOutOfBoundsException: 7
at JavaArray.main(JavaArray.java:12)"
Code :
public class JavaArray {
public static void main(String[] args) {
int[] myArray = {1,3,4,5,8,9,10};
int i = 0;
for(i = 0; i < myArray.length; i++); {
if(myArray[i] % 2 == 1) {
System.out.println(myArray[i]);
}
}
}
}
Remove the semi-colon that is terminating your for loop
for (i = 0; i < myArray.length; i++);
^
Because you have placed semicolon after for loop, variable i increments till length of array(here 7). After that loop ends and you are trying to access myarray element through i which is 7 so it is giving out of bound exception.
Besides the extra ; you need to remove, you can consolidate by declaring the int in the loop declaration:
for (int i = 0; i < myArray.length; i++) {
.
.
.
}
Beside #Reimus point , you can also do it like below , sort the array if it's not sorted yet, in your case it is sorted . FYI, Instead of Collections.sort which is above O(N) complexity use a Hash Set.
public static void main(String[] args) {
int[] myArray={1,3,4,5,8,9,10};
Arrays.sort(str);
for (int i = 1; i < myArray.length; i++) {
if (str[i] == str[i - 1]) {
System.out.println("Dupe-num: " + str[i];
}
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Here is some basic code:
public static void main(String[] args) {
String string = "Hello!";
System.out.println("First loop.");
for (int i = 0; i < string.length(); i++) {
System.out.println("g");
}
System.out.println("Second loop.");
for (int i = (string.length() - 1); i <= 0; i--) {
System.out.println("g");
}
}
For some reason, the program won't go through the second loop at all. This is somewhat strange. Can you explain this, and how to fix it?
Your second loop should be looping backwards, while the index is still greater than or equal to zero, not less than or equal to zero. With <= 0, i is greater than zero on the first evaluation and the loop never runs.
Try:
for (int i = (string.length() - 1); i >= 0; i--) {
Change the for condition,the i is initial with value greater than 0 (length-1) and there is condition i <= 0 which is true in case length is equal to 1.But the length of string is 6 so change the condition as below :
for (int i = (string.length() - 1); i >= 0; i--) {
System.out.println("g");
}
Your problem is the condition in the second for loop
i <= 0
never happens. I don't understand why you would want to check that.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
items_arr = 4;
System.out.println("The elements in the array are: ");
for (int x = 0; x < items_arr; x++)
System.out.println("Array[" + x + "]=" + array[x]);
System.out.print("\n");
Scanner insert = new Scanner(System.in);
System.out.print("Enter an Element to Insert: ");
int input = insert.nextInt();
for (s = 0; s < items_arr; s++)
if (array[s] == input)
break;
items_arr++;
for (s = 0; s < items_arr; s++)
System.out.println("Array[" + s + "]=" + array[s]);
break;
The output is. The elements are
Array [0]= 1
Array [1]= 2
Array [2]= 3
Array [3]= 4
Enter an element to Insert: 5
Array [0]= 1
Array [1]= 2
Array [2]= 3
Array [3]= 4
Array [4]= 0
when I insert 5 it posts 0
any suggestions please.. thanks!
To insert in to the array you shuould be doing follwoing operation
array[s]=input
Two notes here
Arrays are fixed length, and you should be checking the array length before inserting values in to that,other wise you will get ArrayIndexOBException. Safer to sue List/Set
As better coding practise, and to improve the readablity, you should be enclosing the conditional/loop statements (such as if or for) - see eg below
eg: 1
for (int x = 0;x<items_arr;x++) {
System.out.println("Array["+x+"]="+array[x]);
}
eg 2:
for(int s = 0; s < items_arr; s++) {
if (array[s] == input) {
break;
}
}
You have not inserted 5 in your array,
do something after items_arr++
array[ items_arr] = input;
If you do not insert any thing then by default every element is 0
You should be using a Collection type; I would recommend an ArrayList - that is -
List<Integer> al = new ArrayList<Integer>();
for (int i = 1; i < 5; i++) {
al.add(i);
}
Scanner insert = new Scanner(System.in);
System.out.print("Enter an Element to Insert: ");
int input = insert.nextInt();
al.add(input); // And so on...
You are not updating/inserting the array with the new input.
for(s = 0; s < items_arr; s++)
if (array[s] == input)
break;
items_arr++;
just replace the above code with
array[ items_arr] = input;
items_arr++;