So here's the problem

Write a program that asks the user to input a set of floating-point values. When the user enters a value that is not a number, give the user a second chance to enter the value. After two chances, quit reading input. Add all correctly specified values and print the sum when the user is done entering data. Use a sentinel value to signal the end of input. Use exception handling to detect improper inputs. Here is a sample program run:


Value: 1
Value: 2
Value: three
Input error. Try again.
Value: 3
Value: four
Input error. Try again.
Value: 4
Value: five
Input error. Try again.
Value: cinq
Input error. Try again.
Sum: 10.0

Here's what I'm trying to do.

while (flagA)
		{
			try {
				while (flagB)
				{
					try {
						System.out.print("Value: ");
						num = input.nextFloat();
						sum += num;
					}
					catch (InputMismatchException e) {
						System.out.println("Input error. Try again.");
						flagB = false;
					}
				}
				System.out.print("Value: ");
				num = input.nextFloat();
				sum += num;
				flagB = true;
			}
			catch (InputMismatchException f) {
				System.out.println("Input error. Try again");
				flagA = false;
			}
		}
		System.out.println(sum);

Basically, I execute my inner loop first to read a floating-point value from the user-input. Then, if an invalid entry is detected, an exception is thrown, leading to the outer try block. This try block also checks for valid user input. If the user enters a wrong number the second time, the loop breaks and the sum of all valid inputs is printed. Otherwise, it will continue to take a valid input until 2 consecutive invalid entries are read.

Am I supposed to use nested try blocks like this?

I think my solution is really close but I can't seem to bridge the gap here.

A counter of the incorrect entries would be easier. What if you decided to allow for three incorrect entries instead of two? Another try block with identical code would be needed. In most all cases, duplicate code blocks should suggest to you that something could be arranged more efficiently.

A counter of the incorrect entries would be easier. What if you decided to allow for three incorrect entries instead of two? Another try block with identical code would be needed. In most all cases, duplicate code blocks should suggest to you that something could be arranged more efficiently.

thx for the reply.

The goal of this problem was for us to practice handling exceptions. I actually managed to solve the problem, though my solution was rather messy. I ended up using 2 scanner objects T_T

Something simple like this would have done the job:

public class Test
{
    public static void main(String[] args)
    {
        int tries = 0;
        boolean isNormalTermination = true;
        final int LIMIT = 3; 
        final float SENTINEL = -1.0f, TOLERANCE = 1e-6f;
        float val = TOLERANCE, total = 0f;
        Scanner in = new Scanner(System.in);
        do
        {
            try
            {
                System.out.print("Enter a float value: ");
                val = in.nextFloat();
                total += val;
                tries = 0;
            }
            catch(InputMismatchException e)
            {
                in.skip("\\w+"); //gobble up the junk characters
                ++tries;
                if(tries == LIMIT)
                {
                    isNormalTermination = false;
                    break;
                }
                System.out.println("Error! Please try again.");
            }
        }while(TOLERANCE < (Math.abs(val - SENTINEL)));
        in.close();
        if(!isNormalTermination)
        {
            System.out.println("You have exceeded " + LIMIT + " tries. Sorry");
        }
        System.out.print("Total: " + (total - SENTINEL));        
    }
}

This is a not as messy solution, one loop, one trial, coupla Scanners created, but thats ok ( while it's not really good practice ), its ok because java gets rid of any variables that aren't referenced anymore!

import java.util.*;
import java.io.*;

public class TypeTest
{
	public static void main ( String [] args )
	{
		Scanner in = null; //Null as reading fresh value each trial.
		float sum = 0; // Total entered.
		int errCount = 1; //Count our errors.
		float num = 0; //For read value.
		System.out.println( "Press 0 at any time to exit." );
		while ( true )
		{
			System.out.print( "Value: " ); //The value.
			try
			{
				in = new Scanner( System.in ); //Read fresh variable.
				num = in.nextFloat( ); //Add to total.
				if ( num == 0 )
					break;
				sum += num;
			}
			catch ( InputMismatchException e ) //Catch bad data.
			{
				System.out.println( "Bad type error, try again" ); //Alert user.
				errCount++; //Increase error count. 
				if ( errCount == 3 ) //Change this no, depending on how many errors you are allowing.
					break; //If amount of errors exceeded, exit loop.
			}
		}
		System.out.println( "Total: " + sum ); //Print out total.
	}
}

Yes, something like what S.O.S. posted was what I had in mind, and you'll notice that it does still show exception handling as your assignment required.

It may make no difference to your current assignment, but keep such things in mind for future consideration when your initial plan yields duplicate code blocks.

> This is a not as messy solution
Your solution doesn't address the two things asked in your assignment. For one "Use a sentinel value to signal the end of input." and "After two chances, quit reading input".

You need to reset the tries counter after the user recovers from his mistake so he can get three consecutive attempts to enter a bad value. And what happens if he wants to just *stop*? You leave him no choice but to enter some junk characters three times in a row. This is one of the reasons why you were asked to keep a sentinel controlled loop.

Fixed :/

Solved. ;-)

I did something along the lines of what mickinator posted up. Thx for the replies.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.