I am developing in Java and am currently studying Java Study Java using Introduction to Java for a refreshing second edition.
I tried to arrange the application of Chapter 2 2-3.
Run Java in browser using dokojava
Main.java
import java.util.Scanner;
import java.util.Random;
public class Main{
public static void main(String[] args) {
System.out.println("Welcome to the fortune-telling hall\n Please enter your name");
String name = new Scanner(System.in).nextLine();
System.out.println("Please enter your age.");
String ageString = new Scanner(System.in).nextLine();
if (isNumber(ageString)){
int age = Integer.parseInt(ageString);
int fortune = new Random().nextInt(4) + 1;
System.out.println("The result of fortune-telling came out.");
System.out.println( age + "of age" + name + "San, your fortune" + fortune + "is");
System.out.println("1:Daikichi 2: Nakakichi 3: Kichi 4: Bad");
} else {
System.out.println("Age is not a number");
}
}
static boolean isNumber(String num) {
try {
Integer.parseInt(num);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome\n Please enter a number");
String s = new Scanner(System.in).nextLine();
try {
//Processing that may cause an exception
int i = Integer.parseInt(s);
System.out.println(i);
} catch (NumberFormatException e) {
//What to do if an exception occurs(Processing that is not performed unless an exception occurs)
System.out.println("Please enter the numbers properly!");
}
}
}
During program execution, something unexpected happens to the program.
Roughly speaking, exception handling is a mechanism for notifying the occurrence of an abnormal situation (for example, different from the assumed data type) as described above.
The method that detects the occurrence of the anomaly (eg parseInt) "throws" an exception.
This informs you that an abnormal situation has occurred.
In Java terminology, "throwing" is called "throwing."
The method that called the method in which the anomaly occurred can "catch" the thrown exception. If you catch it, you can take appropriate action (also called catching is called "catch").
-Introduction to Programming (Exception Handling) -[Java] Let's implement exception handling with try-catch! How to use the Exception class
Recommended Posts