Home > Mobile >  How to split integers from a String in seperate variables in Java?
How to split integers from a String in seperate variables in Java?

Time:12-21

I am trying to get the following to work:

Imagine the input via the scanner class is this:

new 10 32

I want to store these values into two seperate variables. But I struggle with the conversion from String to Integer. Does anyone know how to implement this, so after the evaluation has been made, I can have two variables that look like this: int width = 10 (first argument) int height = 32 (second argument). Thanks for any help in advance.

Here is what I implemented so far:

I know the code is rather ugly, but I couldn't wrap my head around how I would get this to work

import java.util.Scanner;
public class Main {
public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    String input = scanner.nextLine();
    String word = "";
    String number1 = "";
    String number2 = "";
    boolean check = false;

    for (int i = 0; i < 5; i  ) {
        word  = input.charAt(i);
    }
    word.trim();
    
    if (word.equals("new")) {

        for (int i = 4; i < input.length(); i  ) {
            if (Character.isDigit(input.charAt(i)) && !check) {
                number1  = input.charAt(i);
            }
            else if (check) {
                number2  = input.charAt(i);
            }
            if (input.charAt(i) == ' ') {
                check = true;
            }
        }
    }
    System.out.println(number1   " "   number2);

}

}

CodePudding user response:

This is how I would solve the described problem:

String input = scnanner.nextLine();
Integer firstNumber;
Integer secondNumber;
if(input.contains("new")){
  String[] split = input.split(" ");
  // if you can be sure that there are only two numbers then you don't need a loop.
  // In case you want to be able to handle an unknown amount of numbers you need to
  // use a loop.
  firstNumber = split.length >= 2 ? Integer.valueOf(split[1]) : null;
  secondNumber = split.length >= 3 ? Integer.valueOf(split[2]) : null;
}

Notice: I did not test the code, just typing out of my head. Hope this gives you an idea how to approach the task.

CodePudding user response:

To convert the strings number1 and number2 to integers, you can use the Integer.parseInt() method. This method takes a string as input and returns the integer value represented by the string.

Here's how you can use it to convert number1 and number2 to integers and store them in width and height respectively:

int width = Integer.parseInt(number1);
int height = Integer.parseInt(number2);

You should also consider handling the case where the input string is not in the expected format. For example, if the input string does not have the word "new" at the beginning, or if it does not contain two integers separated by a space, the program may produce unexpected results. You can add additional checks and error handling to handle these cases.

You might also want to consider using the Scanner.nextInt() method to read integers directly from the input stream, instead of reading the entire line as a string and parsing it manually. This can make the code simpler and more efficient.

Finally, you might want to refactor the code to make it more readable and maintainable. For example, you can extract the logic for parsing the input into a separate method, which can make the main() method easier to understand.

CodePudding user response:

String str = "new 10 32";

// Split the string by space character
String[] parts = str.split(" ");

// Convert the second and third elements of the array to integers
int width = Integer.parseInt(parts[1]);
int height = Integer.parseInt(parts[2]);

This should work

  • Related