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!");
}
Related
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);
}
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
I know this has been asked before, but not in a way I understood, because I am dumb.
So.
I need to take some variables into a class, compare them against something, and then return the higher of the two. In the long run, I need to compare against a running total, but for my problem, I think the issue is considerably more fundamental. I'm not understanding how to pass a variable BACK to my main class.
import java.io.*;
public class testing123 {
public static void main(String[] args) {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
Integer a;
Integer b;
Integer numbersCombined;
try {
System.out.println("Please enter a number");
a = Integer.parseInt(reader.readLine());
System.out.println("Please enter a number");
b = Integer.parseInt(reader.readLine());
numbersCombined = (a + b);
testClass Check = new testClass();
System.out.println("Your numbers combined is " +numbersCombined);
System.out.println(Check);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
class testClass {
public static Integer testClass (Integer numbersCombined) {
if (numbersCombined > 100) {
numbersCombined = numbersCombined;
}
else {
numbersCombined = 100;
}
System.out.println(numbersCombined);
return numbersCombined;
}
}
If I remove the return, this will print the numbersCombined, but that's all it does. With the return in place, it doesn't execute the print line above the return, and first prints the original numbersCombined (which it shouldn't if you use, say, 10 and 20, since that's less than 100), and then prints testClass#76046e53 rather than the actual value. I know there's a way to override it, but the answers I've found don't work for me.
I know this answer: http://www.google.com/url?q=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F29140402%2Fhow-do-i-print-my-java-object-without-getting-sometype2f92e0f4&sa=D&sntz=1&usg=AFQjCNGIzxlBSH8xIS7hurKe6_Euc7B8RQ
is the basic problem I'm encountering, but the overrides listed aren't really working for me, and I want integer anyway, rather than string.
In the end, what I'm "really" doing is taking a series of 4 numbers from a user, then using this function to compare whether THIS series of numbers is higher than the previous maximum, and if it is, that's the new maximum moving forward, with a loop until the user is done entering serieses of 4 numbers, and then finally printing the maximum.
I was able to write this without ANY functions, all inline, easy as pie. But once I send the comparison to a function, I don't understand how to send it back, and I've spent all day trying to understand the concept. ALL DAY. So, while I know it's going to be a stupid answer, that's because I'm stupid, but not because I didn't try (sorry, kind of defensive. Frustrated).
Fundamentally, I want to send two (this example is just one) variables to a class, compare them, change ONE of them, and return it to the main class. In this example, I'm just trying to send ONE variable, compare it, and the send it back.
You need to call the method within TestClass. Your code is already returning an integer from that method.
Once you instantiate the class run testClass.testClass(numbers)
The way you're throwing around pseudo-global variables between classes is probably the problem. Pass them through the calls like above, rather than implicitly.
Try to do something like this:
import java.io.*;
public class HelloWorld{
public static void main(String []args){
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
Integer a;
Integer b;
Integer numbersCombined;
try {
System.out.println("Please enter a number");
a = Integer.parseInt(reader.readLine());
System.out.println("Please enter a number");
b = Integer.parseInt(reader.readLine());
numbersCombined = (a + b);
testClass Check = new testClass(numbersCombined); // constructor should be like this
System.out.println("Your numbers combined is " + numbersCombined);
System.out.println(Check);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
class testClass {
Integer numbersCombined;
// This is a constructor
public testClass (Integer numbersCombined) {
if (numbersCombined > 100) {
this.numbersCombined = numbersCombined; // use this to represent the object
} else {
this.numbersCombined = 100;
}
System.out.println(numbersCombined);
}
// Add method toString()
public String toString() {
return this.numbersCombined.toString();
}
}
I'm trying to put a try-catch into a procedure type method but I'm 95% sure it has to be a function type. What I'm trying to accomplish is to make my code shorter in the main. One of the biggest things I thought of was to put a try-catch into a method and call the method.
The thing is, it will validate the input if it is a integer or not- it even catches the exceptions the problem is that it doesn't "remember" the validated input once it continues on with the program/calculates. Here's the part of the code I'm having trouble with.
public static void tryCatchNum(double value)
{
while(true)
{
try
{
Scanner iConsole = new Scanner(System.in);
value = Double.parseDouble(iConsole.nextLine());
System.out.println(" ");
break;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException error has oocured. Please try again.");
}
}
}
And here is the entire program:
import java.util.Scanner;
public class ch7exercise1
{
public static double compound(double oA, double cI)
{
return roundCent((oA*(Math.pow((1+(percent(cI))),10))));
}
public static double percent(double interest)
{
return interest/100.0;
}
public static double roundCent(double amount)
{
return ((Math.round(amount*100))/100.0); //100.0 is mandatory.
}
public static void tryCatchNum(double value)
{
while(true)
{
try
{
Scanner iConsole = new Scanner(System.in);
value = Double.parseDouble(iConsole.nextLine());
System.out.println(" ");
break;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException error has oocured. Please try again.");
}
}
}
#SuppressWarnings("unused")
public static void main(String[] args)
{
boolean f = true;
boolean f2 = true;
double origAmount = 0;
double compInterest = 0;
double total = 0;
Scanner iConsole = new Scanner(System.in);
System.out.println("10 year Compound Interest Claculator\n");
System.out.println("Input amount of money deposited in the bank");
tryCatchNum(origAmount);
System.out.println("Input compouded interest rate. (If the compound interest is 3% input 3)");
tryCatchNum(compInterest);
total = compound(origAmount,compInterest);
System.out.println("$"+total);
}
}
Java arguments are passed by value. You're passing 0 to the tryCatchNum method. A copy of the value is passed to the method. This method assigns a new value to its own copy, and then returns. So the original value is still 0.
You must not pass anything to the method. Instead, the method must return the value it has validated. Also, consider using a more appropriate method name:
public double readDoubleValue() {
...
return value;
}
And in the main method:
double origAmount = readDoubleValue();
Since double is a primitive in Java it is passed by value to the method, therefore when you alter the value of the primitive the changes to the method parameter are not reflected in the original variable passed into the method call.
Read the cup story on Java ranch which explains pass by value and pass by reference.
http://www.javaranch.com/campfire/StoryCups.jsp
The next story to read is the Pass By Value story on Java Ranch.
http://www.javaranch.com/campfire/StoryPassBy.jsp
You should alter your method so that it returns a double which is assigned to value in the main method of your program.
I am also very curious as to why you are using a while loop that checks true. I think it is highly likely your program will encounter an infinite loop if the value entered cannot be converted to a double.
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.