Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cannot loop back before error trapping begins

Status
Not open for further replies.

Tamrak

MIS
Jan 18, 2001
213
0
0
US
Good morning,

I am very new to Java and I tried to create a program that might run a OK.

I created the codes and it worked fine. Only problem I have -> is the error trapping session. When I entered invalid characters, aside from numbers, it popped up with the warning. Then, I could not loop back to the beginning of the program.

I might forget something simple.

There should not be any additional class. One class should be enough for this one..

Here are the codes:


import java.text.*;
import javax.swing.*;

public class ScoreTest {

public static void main(String[] args) {
double AverageScore = 0.000, SumScore = 0.0, sd, BestScore = 0.0;
String str1 = "";
String str2 = "";
String str3 = "";
int number_of_time = 1;

try{
while(!(str1.equalsIgnoreCase("x")))
{
str1 = JOptionPane.showInputDialog("Enter test score:");
sd = Double.parseDouble(str1);
if(number_of_time == 1){
BestScore = sd;
SumScore = sd;}
else{
SumScore=SumScore+sd;
if (sd > BestScore){
BestScore = sd;
}
}
AverageScore = SumScore/number_of_time;
DecimalFormat formatter = new DecimalFormat ("00.000");
str2 = JOptionPane.showInputDialog(null,"Please Enter to continue, \n or 'x' to view test data results.");

if((str2.equalsIgnoreCase("x"))){
str3 = JOptionPane.showInputDialog(null, "Number of scores: " + number_of_time + "\n" + "Average Score: " + formatter.format(AverageScore)+ "\n" + "Best score: " + BestScore + "\n" + "Press Enter to continue entering test scores, \n or 'x' to exit.");
if((str3.equalsIgnoreCase("x"))){
System.exit(0);
}//end str3
}//end of Str2
number_of_time +=1;
}//end of while loop
}//end of try

catch(NumberFormatException e){
str1 = JOptionPane.showInputDialog(null, "Invalid Entry" + "\n"
+ "Press OK to Continue to Enter a Valid Test Score. ", "Invalid Input", JOptionPane.ERROR_MESSAGE);
sd = Double.parseDouble(str1);
}
}
}


************************************************************************
What I would like to do:

1. When the error information screen popped up, I would like to press OK. Then, the program should loop back to where the error starts. If I have the count of three times before the error occurs, those three times should still be there, including the best score and average. The system should not count the time that the error occurs.

2. I think the problem lies on the last part because I do not know what to do, in order to loop back. It starts after " catch(NumberFormatException e){" section.

I am unsure whether I should create any new variables.

Please do not recommend creating a new class. I believe that it can work here with one class, unless we do not have any other options.

Thank you again for your help. I am new to this and try my best to make it to work.
 
Hi again,

I changed the program to the following and it still could not catch the error trapping. I am getting headache and I feel that I miss a simple thing or put some minor things in the wrong place. I do appreciate your help.

** If a user inputs negative number, it will reject as well as inputting the alpha characters.

Can you correct and copy these codes toward your solutions? So, I could see what's wrong. Thank you.

********************************************
The codes are:

import java.text.DecimalFormat;
import javax.swing.JOptionPane;

public class Scoretest {

public static void main(String[] args)//begin main method
{

double counter = 0;
String choice = "";
double total = 0.0;
double bestScore = 0.0;

try
{
while (!(choice.equalsIgnoreCase("x"))) //begin while loop
{

while (!(choice.equalsIgnoreCase("x")))
{
String inputString = JOptionPane.showInputDialog("Enter test score: ");
double grade = Double.parseDouble(inputString);
counter++;
total += grade;
if (grade > bestScore)
bestScore = grade;
String message = "Press Enter to continue, \n or 'x' to view test data results";
choice = JOptionPane.showInputDialog(message);
} //end 2nd while loop

double average = total / counter;
DecimalFormat formatter = new DecimalFormat ("00.000");
DecimalFormat sng = new DecimalFormat ("0");

String secondMessage = "Number of scores: " + sng.format(counter) + "\n"
+ "Average score: " + formatter.format(average) + "\n"
+ "Best score: " + sng.format(bestScore) + "\n"
+ "Press Enter to continue entering test scores,"
+ "\n or 'x' to exit.";

choice = JOptionPane.showInputDialog(secondMessage);
}//end first while loop
}//end of try
catch(NullPointerException e){
System.exit(0);
} //end this catch
System.exit (0);
}

public static double parseDouble(String inputString){
double grade = 0.0;
boolean tryAgain = true;
while (tryAgain){
try{
grade=Double.parseDouble(inputString);
while(grade<=0){
inputString=JOptionPane.showInputDialog(null, "Invalid input. \nPlease enter a positive number","Test Scores",JOptionPane.ERROR_MESSAGE);
grade=Double.parseDouble(inputString);
} //end 2nd while
tryAgain = false;} //end try

catch(NumberFormatException nfe){
inputString=JOptionPane.showInputDialog(null,"Invalid input. \n Please enter a number:", "Test Scores", JOptionPane.ERROR_MESSAGE);
}//end catch
}//end first while
return grade;
} //end public static double parseDouble(String inputString)

}// end class
 
a) You didn't move the try/catch inside the while-loop; why?
b) Please use code-tags [ code] like this [ /code] without the blanks.
c) Don't comment blocks - use an indentation level of 8 instead.
d) What is the second method 'parseDouble' for? You don't use it - why do you post it?
e) Why did you change to NullpointerException, instead of sticking to NumberFormatException?

When you don't follow advices - why should I send a new one?

Write down what you want to achieve in short plain text.
Translate it into a program.
Break responsibilities.

This might be improved:
Code:
 import java.text.DecimalFormat;
import javax.swing.JOptionPane;

/* The response is very different - they don't have much in common. 
Perhaps 'react' would be a better name instead of execute.*/
interface Response 
{
	public void execute ();
}

class ExitResponse implements Response 
{
	public void execute ()
	{
		System.exit (0);
	}	
}

class InvalidResponse implements Response 
{
	private String reason;
		
	public InvalidResponse (String reason)
	{
		this.reason = reason;
	}
	public void execute ()
	{
		System.err.println (reason + " - try again. x to exit.  s to show.");
	}	
}

class ShowResponse implements Response 
{
	private Score score;

	public ShowResponse (Score score)
	{
		this.score = score;
	}
	
	public void execute ()
	{
		score.show ();
	}	
}

class ValidResponse implements Response 
{
	private double value;
	private Score score;

	public ValidResponse (double d, Score score)
	{
		value = d;
		this.score = score;
	}
	
	public void execute ()
	{
		score.add (value);
	}	
}

/** here the real work is done.
If you modify 'show' to return a String, the code-user might decide late to show it in a dialog, show it on System.out, write it to a file ... */
class Score
{
	private double total = 0.0;
	private double bestScore = 0.0;
	private int counter = 0;
		
	public void add (double d)
	{
		++counter;
		total += d;
		if (d > bestScore) 
			bestScore = d;
	}
	
	public void show ()
	{
		double average = total / counter;
		DecimalFormat formatter = new DecimalFormat ("00.000");
		DecimalFormat sng = new DecimalFormat ("0");
		String secondMessage = "Number of scores: " + sng.format (counter) + "\n"
			+ "Average score: " + formatter.format (average) + "\n"
			+ "Best score: " + sng.format (bestScore);
		System.out.println (secondMessage);
	}
}

public class Scoretest 
{
	private Response response;
	private Score score;
	
	public Scoretest ()
	{
		score = new Score ();
		Response response = null;
		do
		{
			response = getResponse ();
			response.execute ();
		} while (true);
	}
	
	private Response getResponse ()
	{
		String inputString = JOptionPane.showInputDialog ("Enter test score, x to exit, s to show: ");
		if (inputString == null || inputString.length () == 0) 
			return new InvalidResponse ("Empty Input");
		if (inputString.equals ("x"))
			return new ExitResponse ();
		if (inputString.equals ("s"))
			return new ShowResponse (score);
		double grade;
		try
		{
			grade = Double.parseDouble (inputString);
			if (grade < 0.0) 
				return new InvalidResponse ("Negative value");
			return new ValidResponse (grade, score);
		}
		catch (NumberFormatException e)
		{
			return new InvalidResponse ("Not a double");
		}
	}

	public static void main (String [] args)
	{
		new Scoretest ();
	}
}

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top