In descending order, remove a value from the inserted number to 0

Asked

Viewed 928 times

1

I need the program to remove a value from the user’s number until it reaches 0. I don’t know if the loop used should be the for, but my program was like this.

package numerodescrecente;

import java.util.Scanner;

public class NumeroDescrecente {

    public static void main(String[] args) {
        Scanner leitor = new Scanner(System.in);
        System.out.println("DIGITE UM NUMERO");
        int n1 = leitor.nextInt();
        for (n1=n1;n1>0;n1--)
        {
            System.out.println("Numero: "+n1);
        }
    }

}
  • If you wish to include the 0, you must change the condition n1>0 for n1>=0

1 answer

0


Your program works. See it working on ideone. With input 12, it produces this output:

DIGITE UM NUMERO
Numero: 12
Numero: 11
Numero: 10
Numero: 9
Numero: 8
Numero: 7
Numero: 6
Numero: 5
Numero: 4
Numero: 3
Numero: 2
Numero: 1

Despite that, there are some things to look at in your code:

  • n1=n1 does absolutely nothing. It is better to put the int n1 = leitor.nextInt() as the boot instruction of for.

  • If the idea is to go to 0, use n1 >= 0.

Your code should look like this:

package numerodescrecente;

import java.util.Scanner;

public class NumeroDescrecente {
    public static void main(String[] args) {
        Scanner leitor = new Scanner(System.in);
        System.out.println("DIGITE UM NÚMERO");
        for (int n1 = leitor.nextInt(); n1 >= 0; n1--) {
            System.out.println("Número: " + n1);
        }
    }
}
  • Thank you so much for the explanation. Hugs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.