I am trying to use a JOption pane to recieve an input, and use a scanne and next
ID: 3790517 • Letter: I
Question
I am trying to use a JOption pane to recieve an input, and use a scanne and nextInt to read through the string and read exactly 3 integers. Additionally it is supposed to be in a try catch block so that it throws an exception if the integers inputed are not 3 ints seperated by spaces. I will catch these exceptions in another method. Additionally, I need to be able to take these numbers and input them into a constructor as shown. How do I use a scanner and nextInt to make sure the input is exactly 3 integers? and how do I format them into a try catch block. Also, do I need to create an ArrayList or array to handel the numbers so I can use them in my constructor?
Combination comb = new Combination( num1, num2, num3 ); then I use comb to create lock.
Lock lock = new Lock( upper, comb );
public void resetNaive() {
String message = JOptionPane.showInputDialog(null, "Type a new combination");
try{
Scanner scanner = new Scanner(message);
int count = scanner.nextInt();
if(count != 3){
throw new InvalidLockCombinationException();
}
for (int i = 0; i < 3; i++){
arr[i] = scanner.nextInt();
}
}
}
Explanation / Answer
Hi,
I have modified a code as per your requirement. Please find the below code and higlighted the code changes below.
public static void resetNaive() {
String message = JOptionPane.showInputDialog(null, "Type a new combination");
message = message.trim();
try{
int count = message.length();
if(count != 3){
throw new InvalidLockCombinationException();
}
Scanner scanner = new Scanner(message);
int n = scanner.nextInt();
}
catch(InputMismatchException e){
System.out.println("Given input is not an integer");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.