Home > database >  using a java while loop to make a line of numbers negative
using a java while loop to make a line of numbers negative

Time:10-27

I have a school assignment that goes like this: Read the int variable number. Assume that number ≥ 0. Output the numbers from number to 1 in one line (or an empty line if no positive number to print). In the next line, output the numbers -number to number on one line. Use space in both lines to separate the numbers.

I am not allowed to use any for loops and I am encouraged to use while loops. The output should be like this: Output

I have been really struggling with this for hours. Please help. Here is the code I have so far. The main thing I am struggling with is the 2nd line and it not reaching back up to the higher numbers.

import java.util.Scanner;
public class Exercise 
{
    public static void main(String[] args) 
    {
        Scanner myScanner=new Scanner(System.in);
        int number=myScanner.nextInt();
        
        if(number<=0)
        {
            System.out.println();
        }
        else
        {
            do
            {
                System.out.print(number   " ");
                number--;
            }
            while(number>=1);
            System.out.println();
            
        }
        do
        {
            System.out.print(-number   " ");
            number  ;
        }
        while(-number>=0);
        
    }
}

Thanks

CodePudding user response:

In your first do-while loop (where you print values 0 to number, you are decrementing the value of number until it hits 0

So, your second do-while loop assumes the number in question is 0

Personally, I would recommend keeping number untouched and using a second variable for your loops.

Right after int number = Scanner.nextInt(); just put a int index = number;

In your loops, use index instead of number. Right before the second loop, you should set index = -number

The while of that second loop should be while(index <= number) and instead of printing -number just print index

    Scanner myScanner=new Scanner(System.in);
    int number=myScanner.nextInt();
    int index = number;

    if(index <=0)
    {
        System.out.println();
    }
    else
    {
        do
        {
            System.out.print(index   " ");
            index--;
        }
        while(index >=1);
        System.out.println();
        
    }

    index = -number;

    do
    {
        System.out.print(index   " ");
        index  ;
    }
    while(index <= number);

CodePudding user response:

Problem is on the last line of your code.

while(-number>=0)

If number is positive, -number is negative, so it will only run your loop once.

Try this:

int aux = number;
do
   {
            System.out.print(-aux   " ");
            aux  ;
        }
        while(aux<number);
  • Related