Noname
Noname

Reputation: 89

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

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

Upvotes: 0

Views: 173

Answers (2)

YvesHendseth
YvesHendseth

Reputation: 1181

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.

Upvotes: 1

Pranav
Pranav

Reputation: 63

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

Upvotes: 0

Related Questions