java - Sorting Arrays. The first element is length of array -
question : sorted?) write following method returns true if list sorted in increasing order. public static boolean issorted(int[] list) write test program prompts user enter list , displays whether list sorted or not. here sample run. note first number in input indicates number of elements in list.
my try:
import java.util.scanner; public class problem6_19 { public static void main(string[] args) { scanner input = new scanner(system.in); system.out.println("enter number. length of list: "); int listlength = input.nextint(); int[] number = new int[listlength]; for(int = 0; < number.length; i++) { system.out.println("enter value: "); number[i] = input.nextint(); } if (issorted(number)) { system.out.println("the list sorted!"); } else { system.out.println("the list not sorted!"); } } public static boolean issorted(int[] list) { for(int = 0; < list.length; i++) { if (list[i] > list[i + 1]) { return false; } else { return true; } } return false; } } but there's 1 problem. in question prompts user enter list , first element length of list. means need prompt user 1 time. please explain how possible first element becomes size of array??
the scanner class uses whitespace, white space, delimiter between tokens default. means if user pressed return between entering numbers need handle case , ask user number, or end user on new line , not know do. if user doesn't press return between entering numbers separates them space, example:
1 2 3 4 5
then scanner separate in 5 separate tokens returned 1 @ once when call nextint().
if run program , enter like:
4 2 1 3 4
it should out put 4 questions asking enter inout (that have given it) perform function want anyway , print "the list not sorted!".
ps. program doesn't quite work imagine want because checks if first 2 values in ascending order , returns. instead should check see if first 2 correct, set flag keep track of them if , carry on loop without exiting. or return in case list isn't sorted , if end of checking array , haven't exited must sorted , therefore should return true (as in code example below). return statements force method issorted exit hits line, without going through whole loop. should check going off end of array before trying access i+1. like
import java.util.scanner; public class scannerclass { public static void main(string[] args) { scanner input = new scanner(system.in); system.out.println("enter number. length of list: "); int listlength = input.nextint(); int[] number = new int[listlength]; for(int = 0; < number.length; i++) { system.out.println("enter value: "); number[i] = input.nextint(); } if (issorted(number)) { system.out.println("the list sorted!"); } else { system.out.println("the list not sorted!"); } } public static boolean issorted(int[] list) { for(int = 0; < list.length - 1; i++) { if (list[i] > list[i + 1]) { return false } } return true; } }
Comments
Post a Comment