This is my raw code
int n1=nextInt();
String ch=next().split("");
int n2=nextInt().split("");
if i want to get input line 5A11
(in same line).What should i do to get input like this.IS it possible to get input like this in java
This is my raw code
int n1=nextInt();
String ch=next().split("");
int n2=nextInt().split("");
if i want to get input line 5A11
(in same line).What should i do to get input like this.IS it possible to get input like this in java
Read the input as a String. Then use below code to remove the characters from the String followed by summing the integers.
String str = "123ABC4";
int sum = str.replaceAll("[\\D]", "")
.chars()
.map(Character::getNumericValue)
.sum();
System.out.println(sum);
You can use String#split
.
int[] parseInput(String input) {
final String[] tokens = input.split("A"); // split the string on letter A
final int[] numbers = new int[tokens.length]; // create a new array to store the numbers
for (int i = 0; i < tokens.length; i++) { // iterate over the index of the tokens
numbers[i] = Integer.parseInt(tokens[i]); // set each element to the parsed integer
}
return numbers;
}
Now you can use it as
int[] numbers;
numbers = parseInput("5A11");
System.out.println(Arrays.toString(numbers)); // output: [5, 11]
numbers = parseInput("123A456");
System.out.println(Arrays.toString(numbers)); // output: [123, 456]
String input = "123C567";
String[] tokens = input.split("[A-Z]");
int first = Integer.parseInt(tokens[0]);
int second = Integer.parseInt(tokens[1]);