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
public class Main {
public static void main(String [] args) {
int i = 0;
do {
System.out.println(i);
i++;
} while (i==3);
}
}
// Outputs 0
Why do iterations stop at zero? while(i==3) is a condition, which tests for equality of i to 3. But then, even after incrementing the value of i as i++ why the output is only 0?
Because it'll print i, which is 0, then will increment it, and won't loop since 3 != 1:
do {
System.out.println(i); //i is 0, will print 0
i++; //i is now 1
} while (i==3); //false
Read The while and do-while Statements to better understand how the do-while loop works.
I'm carefully assuming that you meant to write while(i != 3);, if that's the case, your program will loop and will print 0 1 2.
Your condition would be i!=3. Change to while(i!=3). You have mistakenly put the wrong condition in the while loop. You have said it to loop the while only when i==3 otherwise to exit the loop. So you need to change it to
do {
System.out.println(i);
i++;
} while (i!=3);
Hope this clarifies!
Because you increment after printing.
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 2 years ago.
Improve this question
So, I just started to get my hands dirty on Java this week and I found something rather odd. I'll add the code and then walk you through.
import java.util.Scanner;
public class kids
{
public static void main(String[] args)
{
System.out.println("How old are you, doll?");
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
System.out.println("Doggie lover or a cat person?");
String animal = scanner.nextLine();
if(age < 18 && animal.contains("dog")) // 1st comparison
{
System.out.println("Hello cutie, welcome");
}
else if(age < 18 && animal.contains("cat")) // 2nd comparison
{
System.out.println("Oh, hi"); // This statement gets skipped
}
else if(age < 18 && animal.contains("cat")); // 3rd comparison
{
System.out.println("Hiya, Doggie lover!");
}
}
}
I've attached my output here
Output
So, I gave an input "dogcat" to the string animal. It is pretty clear or at least to me that the three comparisons should return TRUE but my output says otherwise. Seems like only the first and the third comparisons return TRUE but clearly if the third comparison returns TRUE since it contains the string "cat" so does the second comparison. Why is Java skipping my comparison here?
For input dogcat, it only executes the first if condition. Since other two conditions are given as else if conditions, they do not get executed.
Confusion happens because of the typo of having an semicolon just after the 3rd if condition. So the typo makes an empty statement for 3rd if condition.
The statements in the last set of curly braces are not a part of 3rd if condition due to the typo.
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 3 years ago.
Improve this question
I am trying here to measure how many white spaces there are in text typed in a JTextArea. I am getting an outofbounds exception. Why so?
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at ClassTest.main(ClassTest.java:11)
import javax.swing.*;
public class ClassTest {
public static void main(String [] args) {
JFrame frame = new JFrame();
JTextArea textarea = new JTextArea();
frame.setSize(300, 300);
frame.add(textarea);
frame.setVisible(true);
String text=textarea.getText();
int count = 0;
for(int i=0;i>=text.length();i++) {
char spacecount = text.charAt(i);
if(spacecount==' ') {
System.out.print(count++);
}
}
}
}
I believe it should be < not >= for the 'for' loop condition.
Your for loop is as follows:
for(int i=0; i>=test.length();i++){
char spacecount = test.charAt(i);
if(spacecount==' '){
System.out.println(count++);
}
}
Let us take a walk through the for loop. The first part says, we create an int called i and initialize it to 0;
i = 0;
Next part says, keep looping while this condition is true. So it will loop while
i >= test.length()
The next part says, after each iteration, let us add 1 to i. The only reason it could possibly run is
if test.length() == 0;
if test.length() == 1;
0 is not >= 1 so it won't run. That means, the only reason it could run is if the length is 0. Now if the string is of length 0, it would be "".
What is the charAt(0)? Nothing. There is no 0 index. If the String were "a". Then charAt(0) would return "a". It is reaching for something that does not exist and therefore will not run. So one of the problems is that you need to change the condition to < instead of >=. Next, it is recommended to use camel case for fields (such as spacecount) which means you should change it to spaceCount.
Lastly, it may not occur in this case but let us say, test = null. What happens? What is null.length()? Is that even possible? Well actually it will compile in the case that test = null; and then test.length() is executed. However, you cannot call such a method on a null value so you will get the dreaded runtime error, the "NullPointerException". This says, uh oh. We have a string that points to null. Well we cannot do anything with it. Here comes the exception. So in future code, it is recommended to be able to account for such cases. So what do we do? How do we check if a String == null? Well... String == null. So in the future, if it is possible for something to be null, put the for loop in an if statement that says:
if(test != null){
//put for loop here
} else{
//do something else
}
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 6 years ago.
Improve this question
Why I try to use the loop to display the numbers I had put into the ArrayList, it says Unreachable code what am I doing wrong.
private void nOther1() {
ArrayList<Integer> multiples = new ArrayList<Integer>();
int n = 1;
while (1 <= 100) {
multiples.add(n);
n++;
}
// UNREACHABLE CODE
for (int num : multiples) {
System.out.println(num);
}
}
Because
while (1 <= 100)
will never terminate since 1 is always <= 100, and the compiler knows that.
See Chapter 14.21. Unreachable Statements for detailed explanation.
This condition while(1 <= 100){ is always returning true
it would be the same as you do while(true){ so all behind that point is code that NEVER will be executed..
I think you wanted trying instead:
while(n <= 100){
multiples.add(n);
n++;
}
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 6 years ago.
Improve this question
public class LockPicker {
public static void main(String[] args) {
System.out.println ("Picking the lock...");
boolean lock = false;
while (lock==false)
{
int counter = 0;
int number = (int)(Math.random() * 99 + 1);
System.out.println(number);
if (number!=55){
lock = false;
++counter;
}else{
lock = true;
System.out.println("That took "+counter+" tries!");
}
}
}
}
Hello,
I have been set a task where I have to write a program that will generate random numbers between 10 and 99. The program
should continue to repeat until the number 55 is created. The program should output how
many attempts it made to get 55.
It works fine, and stops when it reaches 55. However, the counter always remains at 0. It never adds 1 onto the variable counter.
Move the int counter = 0; line before the while loop.
Everytime the loop runs, you are initializing the counter variable to 0, that is why it always remains 0.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
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.
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.
Improve this question
When I run it, computer counts only 1 3 5 7 9 ... indexes. For example, if I enter "Hello", computer counts 1-H,1-l and 1 o, it doesn't compute e and l(4th index).
What is wrong with it?
import java.util.*;
public class LetterCount {
public static void main(String[] args){
final int Numchars=26;
Scanner scan = new Scanner(System.in);
int[] upper=new int[Numchars];
int[] lower=new int[Numchars];
char current='a';
char current0='A';
int pox=0;
System.out.println("Enter a sentence");
String line=scan.nextLine();
for(int ch=0; ch<line.length(); ch++){
for(int other=0; other<26; other++){
if(line.charAt(ch)==(char)(current+other))
lower[other]++;
if(line.charAt(ch)==(char)(current0+other))
upper[other]++;
else
pox++;
}
ch++;
}
for(int another=0; another<lower.length;another++)
System.out.println((char)(another+'a')+" " +lower[another]);
for(int b=0; b<lower.length;b++)
System.out.println((char)(b+'A')+" " +upper[b]);
System.out.println("non alphabetic characters: "+pox);
}
}
It basically boils down to:
for (int ch = 0; ch < line.length(); ch++) { // Increment per iteration
doSomething();
ch++; // Increment within body
}
in which you increment ch twice!
You need to get rid of one of them and, since the usual way to do a for loop with known-in-advance number of iterations like this is to put the control variable modification into the for statement itself, I would suggest getting rid of the one in the loop body:
for (int ch = 0; ch < line.length(); ch++) {
doSomething();
}
I think you increments ch twice, at the end of for expression and at the end of for loop.