mercredi 26 février 2020

How can I ask a user for 4 numbers and print them out sorted (ascending / descending)? [duplicate]

When I use this code it asks the user for 4 numbers.

When you write in the 4 numbers it prints them as wanted.

Then I want to ask the user for ascending or descending order, but the code just ends.

import java.util.Collections;
import java.util.Scanner;  //import scanner class
import java.util.ArrayList;

public class task2 {
public static void main(String[] args){

    Scanner scanner = new Scanner (System.in);  //create a scanner object
    System.out.println("Enter 4 numbers");

    //numerical input
    int a = scanner.nextInt();
    int b = scanner.nextInt();
    int c = scanner.nextInt();
    int d = scanner.nextInt();

    System.out.println(a + "." + b + "." + c + "." + d);

    System.out.println("you want the numbers by order? (descending / ascending)");
    String order = scanner.nextLine();

    ArrayList<Integer>
            list = new ArrayList<Integer>();

    list.add (a);
    list.add (b);
    list.add (c);
    list.add (d);

    if (order == "ascending"){
        Collections.sort(list);
        System.out.println(list);
    } if (order == "descending"){
        Collections.sort(list, Collections.reverseOrder());
        System.out.println(list);
    }
}

}

Aucun commentaire:

Enregistrer un commentaire