Simple syntax error in my while loop - java

Hi doing some revising for an exam and came upon this past question.
Write a while loop to print the odd numbers between 0 and 10.
I've been toying about and trying to Google but its such a simple thing and its confusing me. I know its a simple syntax error somewhere.
I have tried moving the x++ about, tried moving the print statement about, just not getting it. can somebody shine light on this please. I would normally use a for loop as it would be easier but the question asks for a while loop.
public class OddNumbersWhile {
public static void main (String[]args){
int x = 0;
while (x <10){
if (x % 2 !=0) {
x++;
System.out.println(x);
}} }}

You should put your closing braces on separate lines.
And here's the problem: You're incrementing x in your if-statement thus resulting in an infinite loop once the if-statement fails to trigger since your while condition cannot be reached.
This is probably closer to what you're after.
public class OddNumbersWhile {
public static void main (String[]args){
int x = 0;
while (x <10){
if (x % 2 !=0) {
System.out.println(x);
}
x++;
}
}
}

try this
public class OddNumbersWhile {
public static void main (String[]args){
int x = 0;
while (x < 10){
if (x % 2 != 0) {
System.out.println(x);
}
x++;
}
}
}

you define x = 0, when the while loop begins, you say:
if (x % 2 !=0)
but x % 2 is = 0, because x is 0, so x++ will never run.
P.S.
Ok, N0ir gave you the code. I was trying to bring you to the solution using logic.

You should move x++ outside of the if statement.
public class OddNumbersWhile {
public static void main (String[]args){
int x = 0;
while (x <10){
if (x % 2 !=0) {
System.out.println(x);
}
x++;
}
}
}

Related

Loop and if statement do not give desired output [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 5 years ago.
Improve this question
public class Shuffle1 {
public static void main(String[] args) {
int x = 3;
if(x > 2) {
System.out.print("a");
}
while(x > 0) {
x = x - 1;
System.out.print("-");
}
if(x == 2) {
System.out.print("b c");
}
if(x == 1) {
System.out.print("d");
x = x - 1;
}
}
}
I'm learning Java from a book called "Head First Java", and I was using TextEdit as recommended in the book. I am supposed to be able to compile the code to get an answer of a-b c-d, but instead each time I compile it, I get a result of a---. I have checked it thoroughly myself and would really appreciate if anyone could help me.
Here is the original question from the book.
So if x is 3, I'll take you through what happens:
Print's out "a" because 3 > 2
Decrements x to 0, printing "--" on the way because it took 2 decrements to satisfy break condition, x > 0
That means it would correctly print a--. To achieve a-b c-d, you must the if statements inside the loop, like this:
while(x > 0) {
x = x - 1;
System.out.print("-");
if(x == 2) {
System.out.print("b c");
}
if(x == 1) {
System.out.print("d");
x = x - 1;
}
}
Now the execution cycle is:
x > 2, so print "a"
Goes into the loop
x becomes 2
Prints "-"
x is 2, so print "b c"
Continue iteration
Next iteration, x becomes 1
Print "-"
x is 1 so print "d"
x is now 0
Terminate loop
This gives the following desired result: a-b c-d.
This will print as per your expectation.
public class Shuffle1 {
public static void main(String[] args) {
int x = 3;
if(x > 2) { //First time x=3, which is true
System.out.print("a"); // print a
}
while(x > 0) { // x=3, which is true
x = x - 1; //first loop, x=2, then second loop x=1
System.out.print("-"); //prints "-"
if(x == 2) { // x=2, which is true
System.out.print("b c"); //prints "b c"
}
if(x == 1) { // as x=2, so it won't get display in first loop, but when it loop for second time, x become 1, which is true.
System.out.print("d");
x = x - 1;
}
}
}
}

Java code not printing to console in Eclipse

I have this java code in eclipse. When I run it, I assume I should get something back in the console at the bottom of eclipse. This is not the case. The console at the bottom of eclipse is blank.
package com.veggiedogtreats.javacode;
public class doobeedoobeedo {
/**
* #param args
*/
public static void main(String[] args) {
int x = 1;
while (x < 0) {
System.out.println("Doo");
System.out.println("Bee");
x = x + 1;
}
if (x == 2 ) {
System.out.print("Do");
}
}
}
you have the while loop set to x < 0, it should be x > 0. The way you have it, it will never enter the while loop
Your while condition is wrong. it should read while ( x > 0 ) instead of while ( x < 0 )
Your program only prints to the console when x is less than zero and when x is 2.
x always has a value of 1.
int x = 1; // x is 1
while (x < 0) { // 1 is not less than zero, doesn't enter the loop
System.out.println("Doo");
System.out.println("Bee");
x = x + 1;
}
if (x == 2 ) { // 1 is not two, doesn't enter the if
System.out.print("Do");
}
Maybe you wanted something like this:
while (x < 0) { .... }
your conditions are not satisfied and hence the sysout statements are not executed. Either change the initial value of x or the conditions so that the sysout statements are executed atleast once.
Neither of the conditional statements are true. 1 is not less than zero or equal to 2.

Pong Paddle. Need to carry through the bottom value of count to the top the next time it is initialized

public void update(){
/*
* Purpose: Called each frame update (i.e. 30 times a second)
* Preconditions: None
* Postconditions: return nothing
*/
int count = 0 ;
int x = 0;
if (checkPaddle() == true){
count++;
}
if (count % 2 == 0) {
x = -7;
}
else {
x = 7;}
paddleLocation.y= paddleLocation.y + x;
}//end update
I want the count that is on the bottom to be the initial value at the top of the method. I can't wrap my head around how to do this.
I suppose you could just make the count a member variable and then you could remove the line int count = 0; to prevent the count from reseting during each update:
int count = 0; // Declare it here or in your constructor
public void update() {
int x = 0;
if (checkPaddle() == true) {
count++;
}
if (count % 2 == 0) {
x = -7;
} else {
x = 7;
}
paddleLocation.y = paddleLocation.y + x;
}
Aye, I think you want to make count a private field for this.
On an unrelated note; there is some room for improvement in your code. I would personally get rid of all the empty lines, they take up screenspace. Also, you named your change variable x, which is kinda ambiguous. Since you are using y to denote the y position of the paddle, one might think you mean the x-position for x, while in fact you mean the deltaY. (Change in y-pos).
Lastly, checkPaddle() already returns a boolean value, you don't need to check if it equals true. It looks convoluted.

Recursive method - Java

Addition information:
Chip doesn't support multiplication, only addition. I should work around this problem by creating a recursive method, mult(), that performs multiplication
of x and y by adding x to itself y times. Its arguments are x and y and its return
value is the product of x and y. I should then write the method and a main() to
call it.
It's pure logical thinking, but I get lost every time I try to think what to do.
I am stuck at the math part..
What I have, that doesn't work and I know the math is wrong, but I am not good at this:
public static void mult(int x, int y) {
x = 0;
y = 0;
if (y > 0) {
for (int i = 0; i < y; i++) {
x = x * (x * y);
return mult(x, y);
}
}
}
When I hear "recursion", I expect to see two things:
A function calling itself with modified arguments each time.
A stopping condition right at the top that tells the function when to stop, avoiding an infinite stack.
So where are yours? Start with writing those down in words before you write code.
One possibility is to use an accumulator which will store the current value of the multiplication. I replace missing statements by ??? :
public static void main(String []args){
System.out.println(mult(2,5));
}
public static int mult(int x, int y) {
if(???) return ???;
else return multAcc(???,???,???);
}
private static int multAcc(int x, int y, int acc){
if(???) return ???;
else return multAcc(???, ???, ???);
}
... by adding x to itself y times.
You could actually do that, instead of multiplying. Oh, and maybe if you don't set both x and y to zero, you would have something to add ;-)
One last thing: If you want a recursive solution, you don't need the for-loop.
Java has no TCO by design, so using recursion for linear (not tree-like) processes is very bad idea. Especially for such task, which will most likely become a bottleneck in your program. Use loop instead.
Oh, it must be recursive anyway? Looks like a homework task. Do it yourself then.
All you need to remember is that a multiplication is a repeated addition (assuming that both operands are >= 0), so we have:
The base case is when y is zero
If y is not zero, then add x one more time, and subtract 1 from y
Notice that as long as y is positive, it'll eventually have a value of zero. So basically we keep adding x a total number of y times; this is what I mean:
public static int mult(int x, int y) {
if (y == 0)
return 0;
return x + mult(x, y-1);
}
The same code can be written in a tail-recursive style, too - meaning: there's nothing to do after the recursive call returns, and this is important for certain languages that support a so-called tail-call optimization:
public static int mult(int x, int y, int accumulator) {
if (y == 0)
return accumulator;
return mult(x, y-1, x + accumulator);
}
The above will get called as follows, noticing that the last parameter is always initialized in zero:
mult(10, 5, 0)
=> 50
public static int mult(int x, int y) {
if (y == 0) {
return 0;
}
if (y > 0) {
return x + mult(x, y - 1);
} else {
return -x + mult(x, y + 1);
}
}
this was the solution by the way

Expected this loop to be infinite but it is not

Here is my Java code:
public class Prog1 {
public static void main(String[] args) {
int x = 5;
while (x > 1) {
x = x + 1;
if (x < 3)
System.out.println("small x");
}
}
}
And this is the output:
small x
I was expecting an infinite loop... Any idea why it is behaving this way?
There is an infinite loop. Just in some time, x get so bit that it overflows the limit of a signed int, and it goes negative.
public class Prog1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 5;
while (x > 1) {
x = x + 1;
System.out.println(x);
if(x < 3)
System.out.println("small x");
}
}
}
x starts out 5. Then as you loop through it goes to 6, 7, 8, etc. Eventually it hits the largest possible int. The next x=x+1 sets it to the most negative int, negative 2 billion-whatever. This is less than 3 so the message is output. Then you execute the while condition again which now fails, exiting the loop.
So while it appears to be an infinite loop, it isn't really.
Is this a homework problem? Why would you have written such odd code?
Java integers are signed, and they overflow (as in C and many other languages).
Try this to check this behaviour:
public class TestInt {
public static void main(String[] args) {
int x = Integer.MAX_VALUE;
System.out.println(x);
x++;
System.out.println(x);
}
}
X is overflowing the limits of an int. Check the value by adding a println statement for x
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 5;
while (x > 1) {
x = x + 1;
if(x < 3){
System.out.println(x);
System.out.println("small x");
}
}
My jvm showed x as -2147483648

Categories