Solving algorithm basic problems in Java language
Problem: When a single real number is entered, the integer part in the first line,
Outputs the real number of digits in the second line as it is
Example input:
1.414213
Output example:
1
414213
Below is the code I wrote.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String[] result = input.split(".");
System.out.println(Integer.parseInt(result[0]));
System.out.println(Integer.parseInt(result[1]));
}
}
I wrote it according to the code above and made it run.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Main.main(Main.java:7)
Exceptions popped up
What should I do? No matter how much I think about it, I can't think of anything other than split.
java
I'm not sure because I didn't tell you the conditions of the problem, but in light of the fact that mistakes include integers, I think it's possible to get enough input without decimal points.
This error appears out of range when accessing an array with an index, but there is no other way out of range except when the resulting array size of split
is 1.
Additionally, parseInt
is not required and should not be required.
The integer part doesn't matter, but a few can be 1.000123
, and if 000123
is parseInt
, 123
will come out, so it won't output properly.
.(dot) is a regular expression reserved word. Because it means all characters except \n (initiated characters) All characters are erased one by one, so the result does not contain a value. Therefore, the error ArrayIndexOutOfBoundsException occurred because the index information called result[0] could not be found.
The solution is import java.util.Arrays;
class CodeRunner{ public static void main(String[] args){
double input = 15.45454;
String str = String.valueOf(input);
System.out.println(str);
String[] result = String.valueOf(str).split("\\.");
System.out.println(Arrays.toString(result));
}
}
You can refer to it and modify the code.
© 2024 OneMinuteCode. All rights reserved.