Java/Java Program

Advertisement


Question
Hi Good day to you!.
Can I ask some help because I really don't know how to do it

My Professor in Java Programming ask me to create a program that will allow the user to enter a random number and then sort it into ascending order, and subtract the random number to the ascending order. I dont have idea how will I subtract the random to the ascending order here's my unfinished program :

package JavaApplication1;

import java.io.*;
import java.util.Arrays;

/**
*
* @author students
*/
public class JavaApplication1 {

   public static BufferedReader peers = new BufferedReader(new InputStreamReader(System.in));

   /**
    * @param args the command line arguments
    */
   public static void main(String[] args) throws IOException {

         
       
       System.out.print("Enter How Many Inputs: ");
       int numero = Integer.parseInt(peers.readLine());
       int arr[] = new int[numero];

       for (int i = 0; i <numero; i++) {
         System.out.print("Enter Value #" + (i + 1) + ":");
         arr[i] = Integer.parseInt(peers.readLine());
       }

       System.out.print("Numbers in Ascending Order:");

       for (int i = 0; i < arr.length; i++) {
         Arrays.sort(arr);
         System.out.print(" " + arr[i]);
       }
       // TODO code application logic here
   }
}


Hope you can help me. Thank you

Answer
What you need to do is copy the array before you sort it. This is as simple as:
int[] arr2 = arr.clone();

Since you only sort arr, you can compare the unsorted arr2 to arr each element at a time and print the difference.

Some other notes:
You should put Array.sort(arr) outside the for look, as you only need to sort the array once.
To declare an array you should use:
int[] arr
not
int arr[]

Although both can be used, using the [] is the preferred form as the [] is part of the type of the variable.

Also, make sure that your professor is fine with you using the sort method in Arrays instead of implementing your own.

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.