Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @author Justin Palmer
- * 9/24/2021
- * csc102
- * Computer Science 2
- * Lab 2
- */
- import java.util.Scanner;
- import java.util.ArrayList;
- public class Main {
- public static void main(String[] args) {
- //Creating Scanner and arraylist for later use
- ArrayList<Integer> al = new ArrayList<Integer>();
- Scanner sc = new Scanner(System.in);
- //Getting a first number to populate the arraylist with
- System.out.println("Enter a number to add to the list");
- System.out.printf("> ");
- int r = sc.nextInt();
- al.add(r);
- //Getting a second/last number to populate with before looping to make it easier
- System.out.println("Enter a number to add to the list");
- System.out.printf("> ");
- r = sc.nextInt();
- if (r<al.get(0)) {
- al.add(al.get(0));
- al.set(0, r);
- } else {
- al.add(r);
- }
- //creating a way to end the program on user command by exiting loop when a negative number is entered
- int value = 0;
- while (value==0) {
- //See if the user wants to quit
- System.out.println("Enter a number to add to the list or -1 to exit");
- System.out.printf("> ");
- r = sc.nextInt();
- //create the escape if the user enters a negative number
- if (r<0) {
- value = 1;
- } else {
- //Find where the number belongs in the list
- int i = 0;
- while (i<al.size()) {
- //if the number is smallest than the first one add it as the first
- if (r<al.get(i)) {
- al.add(i, r);
- i=al.size();
- } else { // if it's not smaller than the first
- if (i==(al.size()-1)) { //then if it's not smaller than the last one it appends r
- al.add(r);
- }
- i++; // increase the index to finish the loop
- }
- }
- }
- }
- //Show the user their sorted list
- System.out.println("Your Sorted List Is: ");
- System.out.println(al);
- sc.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement