Question

Java 1 Some help Please...... 1. Before You Begin Anticipate where things can go wrong Consider...

Java 1

Some help Please......

1. Before You Begin

Anticipate where things can go wrong
Consider how to gracefully shut down the program and save the users data and close files properly.
Typically there are two scenarios to make a distinction between:

The first is one that which you have absolutely no control over; such as if all the files are where they should be, and that the user has not deleted one or accidentally moved it rather than copied it. In this case the program should not continue because the results cannot be trusted or even processed.

The second scenario is when, for instance, a user enters a double, when the input should be an int. In this situation you can, by good programming, maintain control of the program. In a poorly written program, the program will crash with an input mismatch. However, you can catch this type of error and ask the user to reenter a number of the proper type.
In both of these scenarios you want things to go smoothly without upsetting the user, and have the program either shut down smoothly and save all data, or continue with a reentering of a number, with little disruption to the user.

2. The Assignment

2.1. Specifications

2.2. General

Follow this with the name of the program: TryCatch.

Use good comments in the body of the program.

Think about the problem and decide what type each of the input numbers should be. Also, think about the calculations and decide what type the variables should be that will hold the results of the calculations.

Use camel casing for variable names, and use descriptive variable names. Do not use general variable names like "tax" or "total."

Take a look at the method below.
This method will cause the program to crash.

Example 1: A method that tries to perform an impossible task

public static void watchThis()
{
    int theFirstNumber = 5;
    int theSecondNumber = 0;
    int theAnswer = theFirstNumber / theSecondNumber;  // 
    return;
}
This is where the program crashes. I hope that at this point that you understand why.

Here is another example of a method that asks for an int and displays the number entered.
A good way to handle a situation like this is to have a method (think one task) that will return an int from the user, but will continue to ask for input until an int is received. This would prevent a type mismatch and cause the program to end.
You could use this method any time you needed an int from the user. You might also create a method for doubles as well.
You would not put the prompting in the method because the prompting would be different in each program.

Example 2: A method that will return an int.

public static int getInt()
{
    while(true)    //  
    {
        try
        {
            return keyboard.nextInt();   // 
        }
        catch(InputMismatchException e)
        {
            keyboard.next();             // 
            System.out.print("That is not and integer. Please try again: ");
        }
    }
}
Using while(true) will create an infinite loop. The return statement will take it out of the loop.
This is a normal int input statement. You could set this to a variable as well, and then return it. As it is, you need to have a variable set to store it in when it is returned.
The next() statement discards the previous input. That is its only purpose.

2.3. The Problem

You will have a good bit of leeway in completing this problem.
You may create any problem you like, as long as it meets the specifics below. It can be written to display the results in the terminal, or it can be written in GUI style.

The program must use OOP style and have more than one class containing methods.

The program must at some point ask the user for the input of numbers.

There must be methods to handle the input of the numbers to insure that type mismatches should not crash the program.

The program must do at least one calculation. If it is possible to have a division by zero, there should be a try-catch to catch it and prevent the program from crashing.

There must be at least one try-catch statement in your program.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

example one without try catch:
import java.util.*;
public class Cheggexample {
public static void main(String[] args) {
// TODO Auto-generated method stub
watchThis();
}
public static void watchThis()
{
int theFirstNumber = 5;
int theSecondNumber = 0;
int theAnswer = theFirstNumber / theSecondNumber;
return;
}
}
output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Cheggexample.watchThis(Cheggexample.java:11)
at Cheggexample.main(Cheggexample.java:5)



code with try catch:
import java.util.*;
public class Cheggexample {
public static void main(String[] args) {
// TODO Auto-generated method stub
watchThis();
}
public static void watchThis()
{
try{
int theFirstNumber = 5;
int theSecondNumber = 0;
int theAnswer = theFirstNumber / theSecondNumber;
return;
}catch(Exception e){
System.out.println("Divisible by zero causes error:");
System.out.println("try catch can help u out from sudden shut down of program:");
}
}
}
output:
Divisible by zero causes error:
try catch can help u out from sudden shut down of program:


example 2:
import java.util.*;
public class Cheggexample2{
static Scanner keyboard=new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
getInt();
}
public static int getInt()
{
while(true) //
{
try
{
return keyboard.nextInt();
}
catch(InputMismatchException e)
{
keyboard.next();   
System.out.print("That is not and integer. Please try again: ");
}
}
}
output:
when integer given:12
normal stop of excecuton:
output when non int given:
12.44
That is not and integer. Please try again: 22.3
That is not and integer. Please try again: 33.4
That is not and integer. Please try again: 22

import java.util.*;
public class Cheggexample {
static Scanner keyboard=new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
getInt();
}
public static int getInt()
{
int intgr;
while(true) //
{
try
{
System.out.println("enter integer:");
intgr=keyboard.nextInt();
System.out.println("it is integer:");
return intgr;

}
catch(InputMismatchException e)
{
System.out.println("input you have entered is not integer:\t plese enter again");
String other=keyboard.next();
System.out.print("That is not and integer. Please try again: ");
}
}
}
}

output:
enter integer:
12
it is integer:

output when non int
enter integer:
12.9
input you have entered is not integer: plese enter again
That is not and integer. Please try again: enter integer:
99.8
input you have entered is not integer: plese enter again
That is not and integer. Please try again: enter integer:
12
it is integer:

/*comments
while loop terminates when it return only integer
so try catch block is writen inside the while loop
if user enters integer then it loop ends
but when user enters non integer it contunusly iterates till integer..
without try catch the program causes or deviates or abnormal termination*/

Add a comment
Know the answer?
Add Answer to:
Java 1 Some help Please...... 1. Before You Begin Anticipate where things can go wrong Consider...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • CIT 149 Java 1 programming question Use DrJava to compile the following try-catch program ? The...

    CIT 149 Java 1 programming question Use DrJava to compile the following try-catch program ? The Assignment ? Specifications General Structure your file name and class name on the following pattern: The first three letters of your last name (begin with upper case.). Then the first two letters of your first name (begin with upper case.). Follow this with the name of the program: TryCatch. For a student called ’John Doe,’ the class name and file name would be: DoeJoTryCatch...

  • This assignment will continue our hardware store system. You will turn in a java file named...

    This assignment will continue our hardware store system. You will turn in a java file named "MyMethods.java". It will contain one class named "MyMethods". That class will contain three methods. These methods must be exactly as specified (including method names): getAnInt will return a value of type int, and take as an argument a string to prompt the user. The actual prompt presented to the user should include not only the string argument, but also the information that the user...

  • use java program, create a class with conditions below. 1. asking user to type int number...

    use java program, create a class with conditions below. 1. asking user to type int number 2.you have to receive it use next String (not next int) 3.use try catch , if user input is not int, ask them to retype int number. (have to print out message that said only type int number)

  • You will turn in a java file named "MyMethods.java". It will contain one class named "MyMethods". That class will contain three methods. These methods must be in JOptionPane and must c...

    You will turn in a java file named "MyMethods.java". It will contain one class named "MyMethods". That class will contain three methods. These methods must be in JOptionPane and must contain: getAnInt will return a value of type int, and take as an argument a string to prompt the user. The actual prompt presented to the user should include not only the string argument, but also the information that the user may press Cancel or enter an empty string to...

  • Use Java program Material Covered : Loops & Methods Question 1: Write a program to calculate...

    Use Java program Material Covered : Loops & Methods Question 1: Write a program to calculate rectangle area. Some requirements: 1. User Scanner to collect user input for length & width 2. The formula is area = length * width 3. You must implement methods getLength, getWidth, getArea and displayData ▪ getLength – This method should ask the user to enter the rectangle’s length and then return that value as a double ▪ getWidth – This method should ask the...

  • Instructions Write a program in Java that implements the A* algorithm to find a path from...

    Instructions Write a program in Java that implements the A* algorithm to find a path from any two given nodes. Problem Overview & Algorithm Description In a fully-observable environment where there are both pathable and blocked nodes, an agent must find a good path from their starting node to the goal node. The agent must use the A* algorithm to determine its path. For this program, you must use the Manhattan method for calculating the heuristic. Remember: your heuristic function...

  • Create two java programs. The first will ask the user to enter three integers. Once the...

    Create two java programs. The first will ask the user to enter three integers. Once the three integers are entered, ask the user to enter one of three functions. The “average” if they want the average of the three numbers entered, enter “min” if they want the minimum and “max” if they want the maximum. Display the answer. Ask the user if they want to calculate another function for the three numbers. If so, loop and ask what function they...

  • C# Write a program that takes a list of information and grades of the students of...

    C# Write a program that takes a list of information and grades of the students of a class and perform some processing. Take the following steps to write the program. The program must give the user two options such as a menu. At the beginning of the program must ask the following from the user: Which task you want to do (choose an option between 1-2), 1- Entering new information 2- Searching a student If the user types something rather...

  • IN BASIC JAVA and using JAVA.UTIL.RANDOM write a program will randomly pick a number between one...

    IN BASIC JAVA and using JAVA.UTIL.RANDOM write a program will randomly pick a number between one and 100. Then it will ask the user to make a guess as to what the number is. If the guess is incorrect, but is within the range of 1 to 100, the user will be told if it is higher or lower and then asked to guess again. If the guess was outside the valid range or not readable by Scanner class, a...

  • Hi this is C++, I'm really struggle with it please help me.... ************************ Here is the...

    Hi this is C++, I'm really struggle with it please help me.... ************************ Here is the original high score program,: Write a program that records high-score data for a fictitious game. The program will ask the user to enter five names, and five scores. It will store the data in memory, and print it back out sorted by score. The output from your program should look exactly like this: Enter the name for score #1: Suzy Enter the score for...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT