0 Replies - 183 Views - Last Post: 19 October 2013 - 07:00 PM Rate Topic: -----

#1 NetBeansNoob  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 19-October 13

Need help adding validation to a Java program.

Posted 19 October 2013 - 07:00 PM

Please see me code below. I am attempting to add validations for error handling purposes. Example invalid input - invalid integer or a "y" followed by another value at them prompt when the user is asked if they want to input another score. I'm attempting to use getInt to created a valid score range 1 to 100. Also I need to add code to discard any extra entries that ask is you want to enter another score.

Thanks!

import java.util.Scanner;
import java.text.NumberFormat;

public class TestScoreApp
{
    public static void main(String[] args)
    {
        int scoreTotal = 0;
        int scoreCount = 0;
        int testScore = 0;
        double averageScore = 0;

        Scanner sc = new Scanner(System.in);
        String choice = "y";
        while (!choice.equalsIgnoreCase("n"))
        {
            // get the input from the user
            System.out.print("Enter score: ");
            testScore = sc.nextInt();
            
            

            scoreCount += 1;
            scoreTotal += testScore;

            averageScore = (double) scoreTotal / (double) scoreCount;

            // see if the user wants to enter more test scores
            System.out.print("Enter another test score? (y/n): ");
            choice = sc.next();
        }

        NumberFormat number = NumberFormat.getNumberInstance();
        number.setMaximumFractionDigits(1);
        String message = "\n" +
                         "Score count:   " + scoreCount + "\n"
                       + "Score total:   " + scoreTotal + "\n"
                       + "Average score: " + number.format(averageScore) + "\n";
        System.out.println(message);
        
        
    }
    ////////***************************
public static String getContinueWithinRange(Scanner sc, String prompt, String yContinue, String nContinue)
{ 
String i = ""; 
boolean isValid = false;
while (isValid == false)
{
       i = getContinue(sc, prompt);
       if (!yContinue.equalsIgnoreCase("") && !nContinue.equalsIgnoreCase("")){
           System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
       }        
       else{
           isValid = true;
       }
}
return i;
 }
public static String getContinue(Scanner sc, String prompt)
 {
 String i = "";
 boolean isValid = false;
 while(isValid == false)
 {
        System.out.print(prompt);
        if (i.length() > 0)
        {

            i = sc.nextLine(); 
            isValid = true;
        }
        else
        {
            System.out.println("Error! Entry is required. Try again.");
        }       
        sc.nextLine();
 }
 return i;
}
}




Is This A Good Question/Topic? 0
  • +

Page 1 of 1