greater than or equal java for loop nested - java

If I only put y>x; y--; in the inner loop it prints 5432 but when I put y>=x; y--; in the inner loop it prints 54321. What happened there?
What does y>=x; y--; mean? It means y is greater than or equal to x right? But why did it print 54321?
public class TestClass {
public static void main (String[] args) {
int x;
int y;
for(x=1; x<=5; x++){
for(y=5; y>=x; y--){
System.out.print(y);
}
System.out.println();
}
}
}

if y > x and x is 1 then 1 will not be included in you printed list as y will never be less then x which is 1. When you made it = x then you allowed 1 to be allowed by y

Related

Creating a method must check which of the two numbers is larger, and execute an increasing count from the smallest to the largest

Ok so i need to Create a method in the LogicalOp class, which will receive two number parameters. The method must check which of the two numbers is larger, and execute an increasing count from the smallest to the largest. (Eg: if x is the first parameter and int y is the second, if x is greater than y, then the count is from y to x).
I have tried different methods but they either did not do anything or go for an infinite loop. I don't know how to stop a loop from x to y if the x is smaller then y and from x the count starts to y and then stop there to the biggest number i imputed in console.
public void getForthExercise() {
System.out.println("Give the x parameter and y ");
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int y = in.nextInt();
if (x > y) {
for (int i = x; i >= y; i++)
System.out.println(i);
} else if (x < y) {
for (int i = y; i >= x;i++ )
System.out.println(i);
So if i imput x=25 and y=5 || y
Let's give you a hint how to simplify the problem: you do not need to care about x < y, or y > x for looping.
You only care: about the smaller number of that pair, and the larger number!
In other words: you simply have to loop from min(x, y) to max(x, y).
Think about it: for what needs to be printed, does it really matter whether x is 5 or 25, or whether y is 25 or 5? No, the only thing that matters is: you got 5, and 25. Which one came in first, and which one second, that doesn't change anything about the expected output!
Have a look at this:
int min = Math.min(x, y);
int max = Math.max(x, y);
for(int i = min; i < max; i++) {
System.out.println(i);
}

Multiples of 7 between 98 and 266

The statement says:
Write a list of multiples of 7 between 98 and 266, both
including
I put this code:
import java.util.*;
public class Multiples7 {
public static void main (String[] args) {
Scanner entrada;
int x;
entrada = new Scanner(System.in);
while (x >= 98 && x <= 266) {
if (x % 7 == 0){
System.out.println(x);
}
}
}
}
and I get this error that I don't understand:
variable x might not have been initialized
Why x not start?
To solve the question asked: you simply need to initialize x, which is currently uninitialized. To initialize a variable, you have to assign it a value. For example x = 0;.
However, that still is not going to cause your program to print the correct result.
One way to accomplish what you actually want to do is iterate the numbers between 98 and 266 print them when they are divisible by 7.
for(int y = 98; y <= 266; ++y) if (y % 7 == 0) System.out.println(y);
alternately, you can start at 98 (14 * 7) and then increment it by 7, printing as you go.
int y = 98;
while(y <= 266) {
System.out.println(y);
y+=7
}
You need to read the value of x or initialize it yourself. This error is shown because there is a chance that the program might get over without x being initialized.
Just initialize it :
int x = 0;
or read from scanner
x = entrada.nextInt();
Alternatively, you could use a for loop, which includes initialization.
for (int x = 98; x <= 266; x++) {
if (x % 7 == 0) {
System.out.println(x);
}
}
You have only declared x but did not initialize it. Insted of int x do int x = 0;. Replace 0 with the desired value.
You need to give X a starting value or it might as well not exist.
For example if X should start at 0 then use:
int x = 0;
you need to initialize x so it has a starting value and is not empty when your programm starts(int x = 98;). Also you should increment x inside your while loop (x++; or you will have an infinity loop always printing the same line.
int x = 98;
entrada = new Scanner (System.in);
while ( x >= 98 && x <= 266) {
if (x % 7 == 0){
System.out.println(x);
}
x++;
}
It could be a single for loop. Initialize x at 98, increment by 7 and stop when x is greater then 266. Something like,
for (int x = 98; x <= 266; x += 7)
System.out.printf("%d = 7 * %d%n", x, x / 7);

Simple syntax error in my while loop

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

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

Is there a difference between x++ and ++x in java?

Is there a difference between ++x and x++ in java?
++x is called preincrement while x++ is called postincrement.
int x = 5, y = 5;
System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6
System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6
yes
++x increments the value of x and then returns x
x++ returns the value of x and then increments
example:
x=0;
a=++x;
b=x++;
after the code is run both a and b will be 1 but x will be 2.
These are known as postfix and prefix operators. Both will add 1 to the variable but there is a difference in the result of the statement.
int x = 0;
int y = 0;
y = ++x; // result: x=1, y=1
int x = 0;
int y = 0;
y = x++; // result: x=1, y=0
Yes,
int x=5;
System.out.println(++x);
will print 6 and
int x=5;
System.out.println(x++);
will print 5.
In Java there is a difference between x++ and ++x
++x is a prefix form:
It increments the variables expression then uses the new value in the expression.
For example if used in code:
int x = 3;
int y = ++x;
//Using ++x in the above is a two step operation.
//The first operation is to increment x, so x = 1 + 3 = 4
//The second operation is y = x so y = 4
System.out.println(y); //It will print out '4'
System.out.println(x); //It will print out '4'
x++ is a postfix form:
The variables value is first used in the expression and then it is incremented after the operation.
For example if used in code:
int x = 3;
int y = x++;
//Using x++ in the above is a two step operation.
//The first operation is y = x so y = 3
//The second operation is to increment x, so x = 1 + 3 = 4
System.out.println(y); //It will print out '3'
System.out.println(x); //It will print out '4'
Hope this is clear. Running and playing with the above code should help your understanding.
I landed here from one of its recent dup's, and though this question is more than answered, I couldn't help decompiling the code and adding "yet another answer" :-)
To be accurate (and probably, a bit pedantic),
int y = 2;
y = y++;
is compiled into:
int y = 2;
int tmp = y;
y = y+1;
y = tmp;
If you javac this Y.java class:
public class Y {
public static void main(String []args) {
int y = 2;
y = y++;
}
}
and javap -c Y, you get the following jvm code (I have allowed me to comment the main method with the help of the Java Virtual Machine Specification):
public class Y extends java.lang.Object{
public Y();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_2 // Push int constant `2` onto the operand stack.
1: istore_1 // Pop the value on top of the operand stack (`2`) and set the
// value of the local variable at index `1` (`y`) to this value.
2: iload_1 // Push the value (`2`) of the local variable at index `1` (`y`)
// onto the operand stack
3: iinc 1, 1 // Sign-extend the constant value `1` to an int, and increment
// by this amount the local variable at index `1` (`y`)
6: istore_1 // Pop the value on top of the operand stack (`2`) and set the
// value of the local variable at index `1` (`y`) to this value.
7: return
}
Thus, we finally have:
0,1: y=2
2: tmp=y
3: y=y+1
6: y=tmp
When considering what the computer actually does...
++x: load x from memory, increment, use, store back to memory.
x++: load x from memory, use, increment, store back to memory.
Consider:
a = 0
x = f(a++)
y = f(++a)
where function f(p) returns p + 1
x will be 1 (or 2)
y will be 2 (or 1)
And therein lies the problem. Did the author of the compiler pass the parameter after retrieval, after use, or after storage.
Generally, just use x = x + 1. It's way simpler.
Yes.
public class IncrementTest extends TestCase {
public void testPreIncrement() throws Exception {
int i = 0;
int j = i++;
assertEquals(0, j);
assertEquals(1, i);
}
public void testPostIncrement() throws Exception {
int i = 0;
int j = ++i;
assertEquals(1, j);
assertEquals(1, i);
}
}
Yes, using ++X, X+1 will be used in the expression. Using X++, X will be used in the expression and X will only be increased after the expression has been evaluated.
So if X = 9, using ++X, the value 10 will be used, else, the value 9.
If it's like many other languages you may want to have a simple try:
i = 0;
if (0 == i++) // if true, increment happened after equality check
if (2 == ++i) // if true, increment happened before equality check
If the above doesn't happen like that, they may be equivalent
Yes, the value returned is the value after and before the incrementation, respectively.
class Foo {
public static void main(String args[]) {
int x = 1;
int a = x++;
System.out.println("a is now " + a);
x = 1;
a = ++x;
System.out.println("a is now " + a);
}
}
$ java Foo
a is now 1
a is now 2
OK, I landed here because I recently came across the same issue when checking the classic stack implementation. Just a reminder that this is used in the array based implementation of Stack, which is a bit faster than the linked-list one.
Code below, check the push and pop func.
public class FixedCapacityStackOfStrings
{
private String[] s;
private int N=0;
public FixedCapacityStackOfStrings(int capacity)
{ s = new String[capacity];}
public boolean isEmpty()
{ return N == 0;}
public void push(String item)
{ s[N++] = item; }
public String pop()
{
String item = s[--N];
s[N] = null;
return item;
}
}
Yes, there is a difference, incase of x++(postincrement), value of x will be used in the expression and x will be incremented by 1 after the expression has been evaluated, on the other hand ++x(preincrement), x+1 will be used in the expression.
Take an example:
public static void main(String args[])
{
int i , j , k = 0;
j = k++; // Value of j is 0
i = ++j; // Value of i becomes 1
k = i++; // Value of k is 1
System.out.println(k);
}
The Question is already answered, but allow me to add from my side too.
First of all ++ means increment by one and -- means decrement by one.
Now x++ means Increment x after this line and ++x means Increment x before this line.
Check this Example
class Example {
public static void main (String args[]) {
int x=17,a,b;
a=x++;
b=++x;
System.out.println(“x=” + x +“a=” +a);
System.out.println(“x=” + x + “b=” +b);
a = x--;
b = --x;
System.out.println(“x=” + x + “a=” +a);
System.out.println(“x=” + x + “b=” +b);
}
}
It will give the following output:
x=19 a=17
x=19 b=19
x=18 a=19
x=17 b=17
public static void main(String[] args) {
int a = 1;
int b = a++; // this means b = whatever value a has but, I want to
increment a by 1
System.out.println("a is --> " + a); //2
System.out.println("b is --> " + b); //1
a = 1;
b = ++a; // this means b = a+1
System.out.println("now a is still --> " + a); //2
System.out.println("but b is --> " + b); //2
}
With i++, it's called postincrement, and the value is used in whatever context then incremented; ++i is preincrement increments the value first and then uses it in context.
If you're not using it in any context, it doesn't matter what you use, but postincrement is used by convention.
There is a huge difference.
As most of the answers have already pointed out the theory, I would like to point out an easy example:
int x = 1;
//would print 1 as first statement will x = x and then x will increase
int x = x++;
System.out.println(x);
Now let's see ++x:
int x = 1;
//would print 2 as first statement will increment x and then x will be stored
int x = ++x;
System.out.println(x);
Try to look at it this way:
from left to right do what you encounter first. If you see the x first, then that value is going to be used in evaluating the currently processing expression, if you see the increment (++) first, then add one to the current value of the variable and continue with the evaluation of the expression. Simple

Categories