Java skips System.out.println(x)

Java skips System.out.println(x)

Page 1 of 1

3 Replies - 1723 Views - Last Post: 30 November 2010 - 10:32 AM Rate Topic: -----

#1 IAmMax  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-November 10

Java skips System.out.println(x)

Posted 29 November 2010 - 02:07 PM

I am trying to write a program where the user is supposed to enter 2 digits. Then the program must print out all the numbers from the first digit to the last and all in between. First, I needed to do it with a for-loop which seemed to work okay (don't know why I had to declare a variable at the start of the loop, but okay), BUT SUDDENLY :o, when I was trying to do the same thing with a while-loop in the same class, the program refused to print out the numbers.

Why is that?

btw, here is the code, any help is very appreciated!

import java.util.Scanner;

class StartoSlut {
	public static void main(String[] args) {
	 Scanner sc = new Scanner(System.in);
		
		System.out.print("Ange start: ");
		int x = sc.nextInt();
		
		System.out.print("Ange slut: ");
		int y = sc.nextInt();

		System.out.println("Med for-loop: ");
		 for(int z=x; x<=y; x++){
		  System.out.println(x);
		 }
		
		System.out.println("Med while-loop: ");
		 while(x<=y){
		  x++;
		  System.out.println(x);
		 }
		  
 }


Is This A Good Question/Topic? 0
  • +

Replies To: Java skips System.out.println(x)

#2 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 1504
  • View blog
  • Posts: 3,215
  • Joined: 11-December 07

Re: Java skips System.out.println(x)

Posted 29 November 2010 - 02:14 PM

It's because your for loop changed the value of x. At the end of each iteration it increments x so at the end of the for loop, x will be 1 greater then y. You can change this by using a different variable in your for loop:

		 for(int i=x; i<=y; i++){
		  System.out.println(i);
		 }


I noticed that you declared z but never used it. What I've done above is a more standard way of solving your problem.
Was This Post Helpful? 1
  • +
  • -

#3 IAmMax  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-November 10

Re: Java skips System.out.println(x)

Posted 30 November 2010 - 10:27 AM

Thanks!

This post has been edited by IAmMax: 30 November 2010 - 10:27 AM

Was This Post Helpful? 0
  • +
  • -

#4 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 1504
  • View blog
  • Posts: 3,215
  • Joined: 11-December 07

Re: Java skips System.out.println(x)

Posted 30 November 2010 - 10:32 AM

No problem. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1