0

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

Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
Develper
  • 57
  • 3
  • 11
  • Just read the whole string ("5A11"), [take the first 2 characters](https://stackoverflow.com/a/3878230/9997212) ("5A"), [take the last 2 characters](https://stackoverflow.com/a/8768577/9997212) ("11") and [parse the latter as an int](https://stackoverflow.com/a/5585800/9997212). – enzo May 07 '21 at 17:07
  • @Enzo by the way the 5 and 11 are integers.I want to add those number by avoiding the character in middle.If it is 123A456 i want to add those integers avoiding the middle char – Develper May 07 '21 at 17:10

3 Answers3

2

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);
1

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]
enzo
  • 9,861
  • 3
  • 15
  • 38
0
String input = "123C567";
String[] tokens = input.split("[A-Z]");
int first = Integer.parseInt(tokens[0]);
int second = Integer.parseInt(tokens[1]);
Piotr
  • 504
  • 4
  • 6