I have the following code, with code to catch various errors from user input.
import java.util.Collections; import java.util.ArrayList; import java.util.Scanner; import java.util.ListIterator; public class Track { public static int getNumber(String prompt, Scanner sc, int lo, int hi) { while (true) { System.out.print(prompt); System.out.flush(); String in= null; try { in = sc.nextLine(); int input= Integer.parseInt(in); if (input >= lo && input <= hi) return input; System.out.println(input+" is not in the range ["+lo+","+hi+"]."); } catch (NumberFormatException nfe) { System.out.println("'"+in+"' is not a number."); } catch (Exception e) { System.out.println("sorry, something went wrong."); } } } public static void main (String[] args) { Scanner scan = new Scanner (System.in); ArrayList<Portfolio> tracks = new ArrayList<Portfolio>(); //Defines the elements in the array String songTitle; String songDate; int songParts; int total = 0; //Defines the user input necessary to run the program. Action is in the do-while loop. String keepWriting = "y"; //Do-while loop do { //Asks for the name of the composition and goes to next line. System.out.print ("Enter the name of the song or composition: "); songTitle = scan.nextLine(); //Asks for the date at which the composition was created and goes to next line. System.out.print ("Enter the date: "); songDate = scan.nextLine(); //Asks for the number of instrumental or miscellaneous parts in the song. System.out.print ("Enter the number of parts in the song: "); songParts = scan.nextInt(); scan.nextLine(); // Creates a new song and adds it to the tracklist Portfolio portfolio = new Portfolio(songTitle, songDate, songParts); tracks.add (portfolio); // Prints the contents of the tracks object using println total += (portfolio.getParts());//+portfolio.getParts()); ListIterator iterator = tracks.listIterator(); while (iterator.hasNext()) System.out.println(iterator.next()); //Asks if the user wishes to continue programming. System.out.print ("Continue composing (y/n)? "); keepWriting = scan.nextLine(); } //End of the do while loop. Continues the programming if "y" was inputed. Otherwise, prints out //all contents of the array. while (keepWriting.equals("y")); Collections.sort(tracks); System.out.println("\n \nThere are " + tracks.size() + " songs in your tracklist." + "\nThe total number of instrumental parts are " + total + "." + "\n\nHere they are in order." + "\n" + tracks); System.out.println("Keep the tunes a'comin!"); } }
How would I, for example, call the getNumber method at the part where the program asks the user for in put for songParts?
like this???
System.out.print ("Enter the number of parts in the song: ");
songParts = scan.nextInt();
songParts.scan.getNumber(scan);???
scan.nextLine();
Thanks so much!