Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
this is my class Person() method inputPersonInfo():
Scanner sc = new Scanner(System.in);
System.out.println("Input Information of Person");
System.out.println("Please input name");
name = checkInputString();
System.out.println("Please input address");
address = checkInputString();
System.out.println("Please input salary");
salary = checkInputSalary();
return new Person(name,address,salary);
}
this is my check for input method:
public static String checkInputString() {
//loop until user input true value
while (true) {
String s = in.nextLine();
if (s.isEmpty()) {
System.err.println("Not empty.");
} else {
return s;
}
}
}
// check if salary is smaller than 0
public static double checkInputSalary() {
//loop until user input true value
while (true) {
try {
double salary = Double.parseDouble(in.nextLine());
if (salary < 0) {
System.err.println("Salary is greater than zero");
System.out.print("Please input salary: ");
} else {
return salary;
}
} catch (NumberFormatException ex) {
System.err.println("You must input digidt.");
System.out.print("Please input salary: ");
}
}
}
how can i throws Exception in this method without using the above checkinput method() ?
public Person inputPersonInfo (String name, String address, Double salary) throws Exception {}
this is my main class(), do i need to throw any Exception in my main class ?:
System.out.println("=====Management Person programer=====");
//call constructor Person
Person p = new Person();
//enter 3 person
for (int i =0; i< 3 ;i++){
persons[i] = p.inputPersonInfo(p.getName(), p.getAddress(), p.getSalary());
}
throws Exception is used when defining a method to signal that this method may throw an error in case something does not go right. It is simply a signal, it does not handle anything.
In case you add this to a method declaration, wherever you call this method, you will be required (by the IDE, compiler..) to add handling mechanisms, such as a try-catch clause, or add yet another throws Exception to the declaration of the method that is calling your "dangerous" method.
Example:
public void dangerousMethod() throws Exception, RuntimeException // Or whatever other exception
{
throw new Exception("FAKE BUT DANGEROUS");
}
public void anotherMethod()
{
dangerousMethod(); // <------------ Compiler, IDE will complain that this should be handled in some way
// Either add try catch:
try
{
dangerousMethod();
}
catch(Exception e) // Or whatever specific Exception you have
{
// Handle it...
}
// Or add the throws Exception at the head of the anotherMethod()
}
For unchecked exception:
NumberFormatException is a RuntimeException, which is an "unchecked exception", that means even if you don't try...catch it, it will eventually thrown to the outside (the caller).
In the outside (the caller), you can try...catch it if you want so, or you can ignore it. If the exception happens, it will be thrown out. If your program is a console program, it will be thrown and displays in the console window.
That also means your main method don't have to explicitly try..catch or throws it, and the compiler will still compile it successfully.
For checked exception:
On the other side, about the "checked exception", you have to try..catch or else the compiler will show you errors. If you do not want to try...catch the exception in the current method, you can use throws Exception in the method signature. For e.g with IOException:
public Person inputPersonInfo (String name, String address, Double salary) throws IOException {}
In your main method that is calling the above inputPersonInfo(), you have to try..catch or throws it in the main method signature.
For e.g: with IOException (a checked exception)
public static void main(String[] args) throws IOException {
...
inputPersonInfo(...);
...
}
Create the method so that Exceptions won't be thrown to begin with:
public double getSalaryFromUser() {
String salary = "";
while (salary.isEmpty()) {
System.out.print("Please enter a Salary amount: --> ");
salary = in.nextLine();
/* Input Validation:
The RegEx below used as argument for the String#matches()
method checks to see if the supplied string is a unsigned
Integer or floating point numerical value. If anything other
than that is supplied then the error message is displayed.
The second condition checks to see if the value is greater
than 0.9d */
if (!salary.matches("\\d+(\\.\\d+)?") || Double.valueOf(salary) < 1.0d) {
System.out.println("Invalid Entry (" + salary + ")! You must supply a");
System.out.println("numerical value and it must be greater than zero.");
System.out.println("Try again...");
System.out.println();
salary = "";
}
}
return Double.parseDouble(salary);
}
Related
I'm writing a method that is supposed to convert a string to an int if possible, and it throw an exception of not possible with a message. It throws the exception but it doesn't print the message, meaning it acts identically as it would were I to comment out the exception condition:
private static int throwsMethod() throws NumberFormatException{
Scanner s = new Scanner(System.in);
System.out.println("enter a number");
String intNumber = s.next();
Integer wrapperIntNumberConv = Integer.parseInt(intNumber);
if(!(wrapperIntNumberConv instanceof Integer)){
throw new NumberFormatException("can't make an int");
}
int fullConvertedNumber = (int) wrapperIntNumberConv;
System.out.println(fullConvertedNumber);
return fullConvertedNumber;
}
how can I do it without a try/catch block (I'm trying to learn exceptions and in this exercise, without a try/catch block) and get it to show the message?
edit: the reason the suggested answer that azro put in didn't solve my problem is because nothing there addreses a method with a throws someException() in the header
The exception is probably thrown at this line:
Integer wrapperIntNumberConv = Integer.parseInt(intNumber);
Because parseInt itself throws it if the string does not contain a parsable integer. (Documentation)
So the program does not reach your if in that case.
You need to wrap the line with parseInt inside a try-catch block to be able to throw an exception with your message:
String intNumber = s.next();
try {
return Integer.parseInt(intNumber);
catch(NumberFormatException e) { // catch system's exception
// throw new one with your message
throw new NumberFormatException("can't make an int");
}
Or, you can check if the string contains a number (optional sign and digits), before calling parseInt:
String intNumber = s.next();
if (intNumber.matches("-?\\d+")) { // see: regular expressions
return Integer.parseInt(intNumber);
} else {
throw new NumberFormatException("can't make an int");
}
I'm not sure to understand what you want: if the NumberFormatException is thrown, it can't reach the print instructions
int fullConvertedNumber = (int) wrapperIntNumberConv;
System.out.println(fullConvertedNumber);
return fullConvertedNumber;
so no message is printed.
If you want to print the "can't make an int" message you can print it before throwing the Exception or in the caller method via try-catch
Ok so I have a method with a switch statement but I left out the rest of the cases because they're not important. In my main method, the operator method is called and passed the parameter "selection" in a while loop until they choose "Q".
When the user enters a negative number, it should throw an exception, print a message, and ignore their input but then loop back to the beginning. When this exception is thrown it terminates the program. Any help would be very much appreciated. Thanks!
public static void operator(String selection) throws IllegalArgumentException{
Scanner input = new Scanner(System.in);
double price;
switch(selection){
case "A":
System.out.println("Enter the price");
if(input.nextDouble()<0){
throw new IllegalArgumentException("Price cannot be a negative value");
}
else{
price = input.nextDouble();
}
break;
case"Q":
System.exit(0);
}
}
An IllegalArgumentException inherits from RuntimeException, for it not to stop your program you can just use a simple try{} catch {} but i don't recommend doing that with Runtime Exceptions. If that's the case, create your own Exception inheriting from java.lang.Exception.
You can use try catch here.
Something like this should work:
public static void operator(String selection) {
Scanner input = new Scanner(System.in);
double price;
switch(selection){
case "A":
System.out.println("Enter the price");
try {
if(input.nextDouble()<0) {
throw new NegativePriceException();
}
} catch (NegativePriceException e) {
System.out.println("The price can't be negative.");
e.printStackTrace();
}
price = input.nextDouble();
break;
case"Q":
System.exit(0);
}
}
And to make your own Exception class you basically need to inherit from Exception (if you want to use try catch on it) or inherit from RuntimeException (if you want it to stop your program from running), like this:
public class NegativePriceException extends Exception {
public NegativePriceException() {
super();
}
}
Java requires that you handle or declare all exceptions. If you are not handling an Exception using a try/catch block then it must be declared in the method's signature.
In your main method you should handle the Exception
public static void main(String args[]) {
//codes
try{
operator("A");
}
catch(IllegalArgumentException e){
e.printStackTrace();
}
}
You've gotten some good answers already on how to handle the exception.
For your case I don't think an exception is appropriate at all. You should get rid of the exception altogether and just handle the problem input by printing an error message and asking for a new input.
Exceptions are for exceptional situations, they should not be part of the normal execution of your code.
Whenever I catch the exception for the integer it works fine, but when I try with the string value it wants me to initiate the string. The follow is my code so far
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
LocalMath e = new LocalMath();
Machine machine = new Machine(name);
String name;
int age;
Scanner userInput = new Scanner(System.in);
System.out.println("What is your name?");
try{
name = userInput.nextLine();
} catch (Exception IllegalArgumentException) {
System.out.println("Must be a character from the english alphabet!");
}
// System.out.println(e.add(5, 10));
System.out.println(name);
System.out.println("-------");
System.out.println("What is your age?");
try {
age = userInput.nextInt();
System.out.println(age);
} catch (Exception IllegalArgumentException) {
System.out.println("Must be in numeric value only!");
}
}
}
And the rest of my code
public class Machine {
public Machine(){
}
public Machine(String name){
}
public Machine(int age){
}
}
Just initialize your String variable to null
String name = null;
It's possible because of the try/catch block for name to get to the sysytem.out line without any value being assigned to it. For example, if userInput.nextLine() raises an illegal argument exception, name will not be assigned a value, yet the rest of the function will execute because the exception is caught. Anything that happens between the exception and the catch line is skipped. Thus, the String "name" could be used before anything is assigned to it; the compiler is therefore forcing you to explicitly initiliaze it.
If you could use the variable/memory address without guaranteeing it had been set to a value first, you might find "name" holding erroneous data from the last time that memory address was used. The compiler is guaranteeing that can't happen.
First, you could declare String name = null; before you instantiate your Machine object.
However, you should instantiate the Machine object after you assign a value other than null to machine. For example, as you have it now, you're creating a machine object with a name of null passed into the constructor.
I would instantiate your machine like this:
try{
name = userInput.nextLine();
} catch (Exception IllegalArgumentException) {
System.out.println("Must be a character from the english alphabet!");
}
Machine machine = new Machine(name);
One more thing, I don't think IllegalArgumentException will prevent the user from entering a number as part of the name. "Bob1234" is a valid string, so you won't catch the exception in this case.
Instead, you'll have to check each character one at a time.
for (int i = 0; i < name.length(); i++) {
if (isDigit(charAt(i))
throw new IllegalArgumentException("Must be in numeric value only!");
}
The following program is meant to calcuate simple interest given the formula i = p*r*t, given the user input and putting that into its own method (Must) , however, when running it i get the error "Unhandelled exception type IOException..." I tried implementing a try catch block previously but it resulted into more errors
import java.io.*;
public class cInterest {
public static void main(String[] args) throws IOException {
}
public static double balance(double principal, double rate, double years) {
double amount = 0;
String input;
BufferedReader myInput = new BufferedReader(new InputStreamReader(
System.in));
System.out.print("How much would you like to take out? ");
input = myInput.readLine();
principal = Double.parseDouble(input);
System.out.print("Enter the interest rate: ");
input = myInput.readLine();
rate = Double.parseDouble(input);
for (int i = 1; i < years; i++) {
amount = principal * rate * years;
amount += principal;
}
return amount; // - principal;
}
}
myInput.readLine(); can throw `IOException` so you **must** handle it somewhere.
Use:
try {
myInput.readLine();
} catch (IOException e){
e.printStackTrace();
}
And try to solve other problems.
Also remove throws declaration from main method.
The simplest fix is to simply declare that your method throws IOException (and you'll need to do this to the main method too, if you call balance from there):
public static double balance(double principal, double rate, double years) throws IOException {
public static void main(String[] args) throws IOException {
You may want to try using Scanner instead of InputStreamReader - its a bit easier to use for this sort of thing
Scanner sc = new Scanner(System.in);
In order for your code to be executed you'll need to call it from the main method:
public static void main(String[] args) throws IOException {
balance(0, 0, 0);
}
however, when running it i get the error "Unhandelled exception type IOException..."
You do not get the exception when the program is run (actually, your main() method is still empty, so nothing would be executed), but the compiler gives this error when compiling your code.
You either need to catch the exception or have your method let it pass on, like
public static double balance(double principal, double rate, double years) throws IOException { ... }
The background is that your myInput.readLine(); could throw an IOException - this either needs to be passed on to the calling method as shown above, or it needs to be handled by a try{}-catch()-block:
try {
input = myInput.readLine();
} catch(IOException ioex) {
ioex.printStackTrace();
// ... additional code to handle the exception properly
}
You should also avoid having main() throw exceptions - if you choose the first approach from above and let balance throw the IOException, handle it in the main method latest. The following code snippet also shows how to call the balance method:
public static void main(String[] args) {
try {
balance(1, 2, 3);
} catch(IOException ioex) {
ioex.printStackTrace();
// ... additional code to handle the exception properly
}
}
See also Lesson: Exceptions.
I had some difficulty with the title, wasn't sure how to word it more accurately.
I'm having this issue, I have a several methods which ask the user for 3 Double inputs.
For each input it checks if it's valid (for example if its a positive value), if it's not it throws an IllegalArgumentException. Now I made a Tester class to check if the methods are working properly. It's supposed to catch the exception thrown by the methods and re-ask the user for the input which caused that specific exception.
All 3 methods throw and IllegalArgumentException but the error message is different for each one. Is there anyway (when catching the exception) to see which input cause the error? Here's a sample of my code:
public class account
{
double value;
public account(double initialValue)
{
if (initialValue < 0)
{
throw new IllegalArgumentException("Initial value cannot be negative.");
}
value = initialValue;
}
public add(double addValue)
{
if (addValue < 0)
{
throw new IllegalArgumentException("Added value cannot be negative.");
}
value = value + addValue;
}
}
and the tester class would be something like:
public class accountTester
{
public static void main(String[] args)
{
try
{
double initialValue = Double.parseDouble(JOptionPane.showInputDialog("Enter initial value"));
account acc = new account(initialValue);
double addValue = Double.parseDouble(JOptionPane.showInputDialog("Enter value to add"));
acc.add(addValue);
} catch (Exception e) {
System.out.println("Wrong ammount");
initialValue = Double.parseDouble(JOptionPane.showInputDialog("Re-enter ammount"));
}
}
So what would I have to change in the tester class to throw that code only if the IllegalArgumentException is "Initial value cannot be negative."
Sorry if I made this hard to understand.
EDIT: According to my prof, we're supposed to use do
String error = e.toString;
if (error.contains("Added value cannot be negative.")
{
//DO CODE FOR FIRST ERROR
}
I know this isn't the most proper way of doing it though.
Since you can't match over Strings like you would do in a functional language you have to provide three different kind of objects if you want to be able to distinguish them using the try-catch mechanics.
Or with a simplified approach attach a parameter to the exception so that you can use just a catch clause but you could behave differently. Something like
class MyIllegalArgumentException extends IllegalArgumentException {
public int whichParameter;
public MyIllegalArgumentException(String string, int which) {
super(string);
whichParameter = which;
}
}
now you can:
catch (MyIllegalArgumentException e) {
if (e.whichParameter == 0)
..
else if (e.whichParameter == 1)
..
}
You could also check the string for equality but this would be really not a good design choice, you could also have many try-catch blocks but this is not always possible.
After having expanded your code the solution is easy:
public static void main(String[] args) {
try {
double initialValue = ...
account acc = new account(initialValue);
} catch (IllegalArgumentException e) {
...
}
try {
double addValue = ...
acc.add(addValue);
} catch (Exception e) {
System.out.println("Wrong ammount");
initialValue = Double.parseDouble(JOptionPane.showInputDialog("Re-enter ammount"));
}
}
Surround each method call with its own try/catch block?
In your catch block you should only catch IllegalArgumentException. Then what you can do is invoke the getMessage() function which will enable you to do a very simple String.equals call.