Results 1 to 5 of 5
  1. #1
    movsesinator is offline Member
    Join Date
    Apr 2010
    Posts
    6
    Rep Power
    0

    Default Handling Errors IE: Wrong User Input

    I want to add code to the following program so that the user cannot provide anything but a number for when the program prompts for "number of parts in the composition."

    Thanks ahead of time to anyone who goes through my program and finds the solution.

    import java.util.*;

    public class Portfolio implements Comparable
    {
    private String title;
    private String date;
    private int parts;


    // -------------------------------------------------------
    // Creates a new portfolio with the given information.
    // -------------------------------------------------------
    public Portfolio (String songTitle, String songDate, int songParts)
    {
    title = songTitle;
    date = songDate;
    parts = songParts;
    }


    // -------------------------------------------------------
    // Returns a string with the information about the item
    // -------------------------------------------------------
    public String toString ()
    {


    return ("title: " + title + "\t\t" + "Date composed: " + (date) + "\t Instruments: " + parts + "\t");
    // + (date*quantity));
    }

    // -------------------------------------------------
    // Returns the date the song was created
    // -------------------------------------------------
    public String getDate()
    {
    return date;
    }

    // -------------------------------------------------
    // Returns the title of the composition
    // -------------------------------------------------
    public String getTitle()
    {
    return title;
    }

    // ----------------------------------------------------------------------------
    // Returns the number of instrumental/miscellaneous parts in the composition
    // ----------------------------------------------------------------------------
    public int getParts()
    {
    return parts;

    }
    // -------------------------------------------------
    // Sorts the compositions alphabetically by title
    // -------------------------------------------------
    public int compareTo(Object other)
    {
    int result;
    if (title.equals(((Portfolio)other).title))
    result = date.compareTo(((Portfolio)other).date);
    else
    result = title.compareTo(((Portfolio)other).title);
    return result;
    }
    }
    ____________________
    Now the main program:
    ____________________

    import java.util.Collections;
    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.ListIterator;

    public class Track
    {

    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 instrumentla 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());
    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
    //the current contents of the array.

    while (keepWriting.equals("y"));
    System.out.println("There are " + tracks.size() + " songs in your tracklist" + "\n" + tracks);

    System.out.println("Keep the tunes a'comin!");


    }

    }

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,002
    Blog Entries
    7
    Rep Power
    20

    Default

    No comments because this snippet of code is a complete spoiler; store it somewhere in a class so you can reuse it over and over again.

    Java Code:
    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+"' isn't an int");
    		}
    		catch (Exception e) {
    			System.out.println("oops, something went wrong");				
    		}
    	}
    }
    kind regards,

    Jos

  3. #3
    movsesinator is offline Member
    Join Date
    Apr 2010
    Posts
    6
    Rep Power
    0

    Default

    i really really appreciate your quick help

    do you mind explaining your code though? i'm not super adept at coding, if you hadn't noticed.

    also, how/where exactly do i implement your code in my program?

    thanks again
    Last edited by movsesinator; 04-05-2010 at 01:26 PM.

  4. #4
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,002
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by movsesinator View Post
    i really really appreciate your quick help

    do you mind explaining your code though? i'm not super adept at coding, if you hadn't noticed.

    also, how/where exactly do i implement your code in my program?

    thanks again
    If you're really lazy you can put that method in your Track class and call it whenever you need a number (in a certain range) see its parameter list for details. It returns an int in the range [lo, hi]. Your Track class is going to look like this:

    Java Code:
    public class Track {
       public static int getNumber( ... ) { ... }
       public static void main( ... ) { ... }
    }
    kind regards,

    Jos

  5. #5
    movsesinator is offline Member
    Join Date
    Apr 2010
    Posts
    6
    Rep Power
    0

    Default

    I get an error message that the method cannot be found when i try to call it in the program.


    for example, i tried to call it for the getParts prompt, which is what i really needed it for originally.
    could i do it like this?

    System.out.print ("Enter the number of parts in the song: ");
    songParts = scan.nextInt();
    scan.getNumber(scan.nextInt());
    scan.nextLine();

    We're almost there, Jos, I promise :p

Similar Threads

  1. Replies: 0
    Last Post: 12-01-2009, 02:42 PM
  2. Whats Wrong? Errors when compiling
    By software_dude_2009 in forum New To Java
    Replies: 5
    Last Post: 05-12-2009, 12:19 PM
  3. how to avoid input errors?
    By Sinnergy in forum New To Java
    Replies: 5
    Last Post: 02-02-2009, 11:25 PM
  4. Replies: 11
    Last Post: 05-24-2008, 04:26 AM
  5. Handling SQL Errors and Warnings
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-12-2008, 09:37 AM

Posting Permissions

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