[英]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新 10 32
I want to store these values into two seperate variables.我想将这些值存储到两个单独的变量中。 But I struggle with the conversion from String to Integer.但是我在从 String 到 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).有谁知道如何实现这个,所以在进行评估之后,我可以有两个看起来像这样的变量:int width = 10(第一个参数)int height = 32(第二个参数)。 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);
}
} }
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.希望这能让您了解如何处理该任务。
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这应该工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.