www.webdeveloper.com
Results 1 to 2 of 2

Thread: Problem with java code that determines if an array is sorted or not.

  1. #1
    Join Date
    Nov 2012
    Posts
    5

    Problem with java code that determines if an array is sorted or not.

    Here is my code:

    import java.util.*;

    public class Problem6_19 {

    public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    // prompt the user for the length of the list
    System.out.println("Enter a number for the length of the list: ");
    int listLength = input.nextInt();
    // list array and input
    int[] number = new int[listLength];
    for (int i = 0; i < number.length; i++) {
    System.out.println("Enter a value: ");
    number[i] = input.nextInt();
    }
    // show the output
    if (isSorted(number)) {
    System.out.println("The list is sorted");

    } else
    System.out.println("The list is NOT sorted");

    }

    public static boolean isSorted(int[] list) {
    // sort list from min to max
    for (int i = 0; i < list.length; i++) {
    if (list[i] > list[i + 1])

    return false;
    i++;// plus i/isSorted = true will be out of bounds
    }

    return true;
    }

    }

    For some reason if I input a list that is only 3 numbers long, the program will not run and has an error. However, if I input a longer list the program works.

  2. #2
    Join Date
    Sep 2013
    Posts
    1

    My solution

    Hello,

    Been trying to work with your solution for some time now. After some time I got up with this solution:
    import java.util.Scanner;

    public class Problem6_19 {
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.println("Enter a number for the length of the list: ");
    int listLength = input.nextInt();
    int[] number = new int[listLength];

    for(int i = 0; i < number.length; i++) {
    System.out.println("Enter a value: ");
    number[i] = input.nextInt();
    }

    if (isSorted(number)) {
    System.out.println("The list is sorted!");
    } else {
    System.out.println("The list is NOT sorted!");
    }

    }

    public static boolean isSorted(int[] list) {

    for(int i = 0; i < list.length; i++) {
    if (list[i] > list[i + 1]) {
    return false;
    } else {
    return true;
    }
    }
    return false;
    }

    }

    (Only did a few changes in the boolean method).

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles