java - I have been asked to make an Create a new integer array with 16 elements -
java code (not java script). asked create new integer array 16 elements.
only integers between 1 , 7 entered in array user (scanner)input.
only valid user input should permitted, , integers entered outside bounds (i.e. < 1 or > 7 should excluded , warning message displayed. design program sort array.
the program should display contents of sorted array. program should display numbers of occurrences of each number chosen user input have been trying complete code step step , used knowledge me need current code under appreciate if 1 able edit code above wants.i know needs enter array user input store , reuse code sort numbers sort array.
the result should print out like “the numbers entered array are:” 1, 2,4,5,7 “the number chose search is” 7 “this occurs” 3 “times in array”
import java.util.scanner; public class test20 { public static void main (string[] args){ scanner userinput = new scanner (system.in); int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6}; int count = 0; int input = 0; boolean isnumber = false; { system.out.println ("enter number check in array"); if (userinput.hasnextint()){ input = userinput.nextint(); system.out.println ("the number chose search " + input); isnumber = true; }else { system.out.println ("not proper number"); } (int = 0; i< nums.length; i++){ if (nums [i]==input){ count ++; } } system.out.println("this occurs " + count + " times in array"); } while (!(isnumber)); } private static string count(string string) { return null; } }
import java.util.scanner; import java.util.arrays; public class test20 { private static int readnumber(scanner userinput) { int nbr; while (true) { while(!userinput.hasnextint()) { system.out.println("enter valid integer!"); userinput.next(); } nbr = userinput.nextint(); if (nbr >= 1 && nbr <= 7) { return nbr; } else { system.out.println("enter number in range 1 7!"); } } } private static int count(int input, int[] nums) { int count = 0; (int = 0; < nums.length; i++){ if (nums[i] == input){ count++; } else if (nums[i] > input) { break; } } return count; } public static void main(string[] args) { scanner userinput = new scanner(system.in); int[] nums = new int[16]; (int = 0; < nums.length; i++) { nums[i] = readnumber(userinput); } arrays.sort(nums); system.out.println ("sorted numbers: " + arrays.tostring(nums)); int input = 0; while(true) { system.out.println("search number in array"); input = readnumber(userinput); system.out.println("the number chose search " + input); system.out.println("this occurs " + count(input, nums) + " times in array"); } } } because array sorted, break loop if element larger 1 we're looking found; if encounter larger 1 no other matches can found in rest of array.
Comments
Post a Comment