Java loop can't iterate down string length [closed] - java

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.

Related

I have a logical error code and I can not find [closed]

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 11 months ago.
Improve this question
I have a logical error code and I can not find out where it would be happy to solve the code
public static int nameCheck(char[] names) {
int blankCount = 0;
for (int i = names.length; i > 1; i--) {
if (names[i - 1] == ' ') {
blankCount++;
}
}
return blankCount;
}
When a for loop 'loops', java first executes the 'incrementor' expression (here, i--), and then checks the condition (here, i > 1), and will abort the loop then and tehre if the condition no longer holds.
Thus, eventually i is 2, you check names[i - 1] (and java is 0-indexed, so names[1] returns the second character). Then, i is decremented to 1, and the loop ends.
Thus, this code fails to count the first character if it is blank.
Simply make that i > 0 to fix it.
You're actually writing your loop wrongly.
Perhaps your question isn't clear enough
It should be this way i guess.
public static int nameCheck(char[] names){ int blankCount = 0;
for (int i = 0; i > names.length; i--) {
if (names[i-1] == ' ') {
blankCount++;
}
}
return blankCount;
}

How can i count how many times the keywords user enter is the used in the essay. its doesn't check on the entire keyword [closed]

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.

for loop is skipping to the end? [closed]

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 am fairly new to Java, but my for loop is instantly skipping to the highest possible value in the following code:
System.out.println(i);
for(i = 0; i <= (difficulty - 2); i++);{
System.out.println(i);
nextMineX = (int) (10*Math.random());
nextMineY = (int) (10*Math.random());
for(y = 0; y <= 14; y++){
System.out.println(y);
if(nextMineX == minesX[y] && nextMineY == minesY[y]){
i = i-1;
} else{
minesX[i] = nextMineX;
minesY[i] = nextMineY;
}
}
}
The first for loop is screwing up, while the nested one is running fine. the variable i is initialized as 0, and difficulty is at 16. the output of this excerpt is as follows:
0
14
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
If anyone can help me with his that would be extremely appreciated. Since I'm new, it is probably something small and basic that I'm overlooking.
The problem is the semicolon at the end of the second line. It's valid to have a for loop with no body. It's also valid to have standalone a block of code inside brackets (this defines a scope for variables--if you defined a variable inside the brackets, it wouldn't be available outside). So Java is interpreting the beginning of your code like this:
for(i = 0; i <= (difficulty - 2); i++); // for loop is done, so i = difficulty - 2
{
System.out.println(i);
...
Your for loop statement ends with the semicolon you have
for(i = 0; i <= (difficulty - 2); i++); <- incorrect
for(i = 0; i <= (difficulty - 2); i++){ <- correct
//body
}
For loop is terminating cause of semicolon ;
for(i = 0; i <= (difficulty - 2); i++); //semicolon terminating loop
{...}
so you should use for loop like this
for(i = 0; i <= (difficulty - 2); i++) //remove semicolon prevent to terminate
{...}

Why does the modulus not help to find negative odd number? [closed]

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
What I am doing: Replacing odd numbers(values) in array with zeros.
Problem: when executing following code it replaces only positive numbers, ignoring negative.
Code:
public static int[] nullOddValues(int[] array) {
int[] resultArray = new int[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 != 0) {
resultArray[i] = 0;
} else {
resultArray[i] = array[i];
}
}
return resultArray;
}
You test the loop variable i for oddity when you (probably) want to test array[i]
if (array[i] % 2 != 0) {
Using modulus on X returns [0-X)
positive X (X > 0) -> it will return 0+
negative X (X < 0) -> it will return 0-
For your problem, I recommend using a bit operator
if((i & 1) == 0)
This will return true for even numbers (positive and negative), since it is checking the last bit of the number.

finding odd numbers in java [closed]

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];
}
}
}

Categories

Resources