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];
}
}
}
Related
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 5 years ago.
Improve this question
This question is pretty specific for my problem, that is why I am creating a new question. The second method in this program is supposed to make a row of the number 1 2 3 4 5 6 7 8 9 10. The only problem I am having is that I don't know how to print this out in the main method.
public class Uppgift1_6a
{
public static void main(String[] args)
{
for(int k = 0; k < 10; k++)
{
int tal = Numberline(k);
System.out.print(tal);
}
}
public static int Numberline(int tal1)
{
int tal = 1;
for(int i = 1; i < 11; i++)
{
tal = tal1 + i;
}
return tal;
}
}
Right now it prints out all the number from 11 to 19. And if I change it, it only prints out either 10 or 11.
Look closely at the code:
public static int Numberline(int tal1)
{
int tal = 1;
for (int i = 1; i < 11; i++)
{
tal = tal1 + i;
}
return tal;
}
The for loop literally does absolutely nothing - you're only returning the final result. The final result is always exactly equal to tal1 + 10; again, what the for loop did up this point makes no difference. (I'd encourage you to step through the code with a debugger to convince yourself of that fact).
If you want it to print out the values as you're going through the for loop, you need to do something like:
for (int i = 1; i < 11; i++)
{
// You may need to modify this line too, depending on what values you want printed
tal = tal1 + i;
// Print the value here
System.out.print(tal);
}
because the way you've written it it'll only print out the final value of tal (the one you returned).
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
public static int keywordsChecker(String essay,String key) {
int count = 1;
String[] k=key.split(",");
for (int i = 0; i < k.length-1; i++) {
if (essay.contains(k[i])) {
count++;
}
}
return count;
}
To take into account that each keyword searched for may occur more than once, and to count such occurrences, you may use this inside your for loop:
int indexOfOccurrence = essay.indexOf(k[i]);
while (indexOfOccurrence > -1) {
count++;
indexOfOccurrence = essay.indexOf(k[i], indexOfOccurrence + 1);
}
There are a couple of other issues in your code: I believe you need to initialize count to 0 (not 1). And to count also the last keyword in key your for loop should be for (int i = 0; i < k.length; i++) (without subtracting 1 from k.length). If you want, using <= would also work: for (int i = 0; i <= k.length-1; i++), but this is non-standard, so I would not recommend it.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Firstly, can you tell me which piece of code is better of selection sort? Then if you know better ways for selection sort, can you please share?
Note: Please inspect the second code closer because it is more complex than it looks.
class SelectionSort {
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
.
class SelectionSort {
public static double[] selectionSort(double[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < i; j++) {
if (array[j] > array[i]) {
double temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
}
}
Both methods will solve your problem but the second one it's clearly and I think it will be faster. Why? Because it has to make less actions to complete the problem: in the first one you have 2 loops (like in the second one), but also it has to make 2 ifs vs 1 if in the second one. I'm not really secure about that but, if the program have to make less actions, it will be faster (just an assumption).
Also, I think it will be faster because in the first one, you through all the j elements, some of them unnecesary (you have to make an extra if), and in the second one you just go through the elements that you need so it is more efficient too.
So, in conclusion, I think the best practice that you have to use it's the second one.
I expect it will helps you a bit!
Performance wise, both are similar, O(n2). The second code is a bit cleaner though.
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 needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have gone through all the questions in this forum that are corresponding to this topic, and I felt to raise a different question as this question is not answered clearly. Here is my scenario:
I have this class Test1:
public class Test1 {
public static void main(String args[]) {
int i=0, j=2;
do {
i= i+1;
j--;
} while(j>0);
System.out.println(i);
}
}
Now this is my question:
a) If I replace the increment operation of 'i= i+1' with ++i, I get the desired output as
1
2
But if I replace the increment operation of 'i= i+1' with i++, I get the desired output as
0
0
I do understand the difference of using prefix and postfix operators in for loop, but why is the value not getting incremented at all in do-while loop?
Using i = i++; will never change i value.
Use just:
i++;
Why? because:
i = i++;
is similar to doing something like this:
temp = i; // temp is 0.
i = i+1; // increment i
i = temp; // assign temp (which is 0) to i.
Take a look at a similar post-increament question and even another one.
++i
This will increment i, then return it.
i++
This will return i, then increment it.
Example
Here is a link to an ideone example of this.
int i = 5;
System.out.println(i++);
// Outputs 5
int j = 5;
System.out.println(++j);
// Outputs 6.
x = i++; is a shortcut for x = i; i = i + 1;
x = ++i; is a shortcut for i = i + 1; x = i;
that's it.
Actually in your sample, there should be no difference between i++ and ++i, if you replace i = i+1 by one of two. Chris noted the difference correctly, I'll just add a sample, where this is important:
int i = 0;
method(i++);
Will call method with the original value of 0 and increment i afterwords. In method, however, you'll see the original value 0.
int i = 0;
method(++i);
Will increment i and then call method. So in method you'll get the value of 1. That does not change the fact that after method, i has the value 1 in both cases.
Others have noted correctly that
i = ++i;
and
i = i++;
are different things actually!