AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



corejava-collection: Sorting Numbers in both order

Write a program which will take a list of positive numbers specified by the user till it encounters -1 and prints the list both in Ascending and Descending order. The range of the numbers in the list is 1 <= n <= 10^30.

Input Format:
A single line containing a list of numbers separated by whitespace and terminated by -1.

Output Format:
The output will contain 2 lines with the numbers listed in ascending and then the descending order.

corejava x 352
collection x 52
Posted On : 2017-01-17 14:34:33.0
profile Glad - anyforum.in Glad
1500
up-rate
4
down-rate

Answers


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;


public class Sorting {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String numberList=input.nextLine();
if(numberList.endsWith("-1")){
try{
String[] numArray=numberList.split(" ");
List<Integer> list=new ArrayList<Integer>();
Integer temp=null;
double max=Math.pow(10, 30);
for(int i=0;i<numArray.length-1;i++){
temp=Integer.parseInt(numArray[i]);
if(temp>=1 && temp<=max){
list.add(temp);
}else{
System.out.println("Invalid input");
break;
}
}

Collections.sort(list);
System.out.println(list.toString().replace("[", "").replace("]", "").replaceAll(",", ""));
Collections.sort(list,Collections.reverseOrder());
System.out.println(list.toString().replace("[", "").replace("]", "").replaceAll(",", ""));
}catch(Exception e){
System.out.println("Invalid input");
}
}else{
System.out.println("Invalid input");
}
}
}

Posted On : 2017-01-19 18:13:39
Satisfied : 1 Yes  0 No
profile Rishi Kumar - anyforum.in Rishi Kumar
523188222437
Reply This Thread
up-rate
5
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in