[英]How can I convert a String in 2 differents values for 2 differents int
我是新来的,我知道这个页面是如何工作的,我认为我的问题很简单,我正在自己学习 Java,但我没有答案,我认为这里有人可以帮助我。 问题是我想把字符串 z 的 12 的值和 4 的值放到 int A 中。我能做什么? 谢谢你的时间
String z = "12 4"
int A;
int B;
尝试首先按空格字符拆分字符串并将它们解析为整数:
String[] parts = z.split(" "); // Return an array of string
int A = Integer.parseInt(parts[0]); // 12
int B = Integer.parseInt(parts[1]); // 4
或者您可以使用空格正则表达式来拆分以下字符串:
String[] parts = z.split("\\s+");
注意:你应该在try catch
块中处理你的解析函数,以避免错误字符串不是数字格式:
try {
String[] parts = z.split(" "); // Return an array of string
int A = Integer.parseInt(parts[0]); // 12
int B = Integer.parseInt(parts[1]); // 4
} catch (e) {
e.printStackTrace()
}
class brainchild{
public static void main(String[] args) {
String z = "12 4";
String [] str = z.split(" ");
int A = Integer.parseInt(str[0]);
int B = Integer.parseInt(str[1]);
System.out.println(A);
System.out.println(B);
}
}
这里的想法是拆分找到空格的字符串String [] str = z.split(" ");
并将其保存到字符串数组中。 然后访问第一个元素并将其转换为整数类型并赋值给整数 A int A = Integer.parseInt(str[0]);
. 与 B 类似。
将此代码保存为 Main.java 并运行它。
public class Main {
public static void main(String[] args) throws Exception {
String z = "12 4" ;
int A;
int B;
String[] arr = z.split(" ") ; //splits the String wherever it finds spaces
A = Integer.parseInt(arr[0]);
B = Integer.parseInt(arr[1]);
System.out.println(A);
System.out.println(B);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.