[英]How to read numbers after followed by particular Character of a string using Java Android?
[英]How to read a String followed by an int in Java?
我一直在努力做到这一点。 我需要读取这样的输入: DEPOSITO 123 1000.00
,但是字符串“ DEPOSITO”需要保存在一个变量中,将int“ 123”保存到另一个变量中,将双精度“ 1000.00”保存到另一个变量中。 问题是我找不到像scanner.nextString()
这样的东西,如果我可以将字符串仅扫描到一个变量中,则可能可以使用scanner.nextInt()
和scanner.nextDouble()
扫描其余的输入流。 。 如果我尝试只读取字符串来执行scanner.next()
,那么它将读取整行,那么对我的问题的解答是什么? 我真的很笨
由于输入始终以字符串开头,因此您可以先获取字符串,然后根据该字符串确定后面有多少个变量:
String input = scanner.nextLine();
// use regex to split string
String tokens = input.split("\\s+");
String firstPart = tokens[0];
int intPart = 0;
double doublePart = 0;
int transferenciaInt = 0;
if(firstPart.equals("SAQUE") || firstPart.equals("DEPOSITO"))
{
intPart = Integer.parseInt(tokens[1]);
doublePart = Double.parseDouble(tokens[2]);
}
else
{
intPart = Integer.parseInt(tokens[1]);
transferenciaInt = Integer.parseInt(tokens[2]);
doublePart = Double.parseDouble(tokens[3]);
}
有关正则表达式(regex)的更多信息,请参见: 学习正则表达式
String[] s = scanner.nextLine().split(" ");
然后,您将获得3个字符串:
s[0]
将返回“ DEPOSITO” s[1]
返回“ 123” s[2]
,它将返回“ 1000.00” 现在:
Integer i = Integer.parseInt(s[1]);
Double d = Double.parseDouble(s[2]);
你可以这样解析值
Scanner scanner = new Scanner(System.in);
String array[] = scanner.nextLine().split("\\s");
String strValue = array[0];
int intValue = Integer.valueOf(array[array.length - 2]);
int intValue1 = 0;
double doubleValue = Double.valueOf(array[array.length - 1]);
if ("TRANSFERENCIA".equalsIgnoreCase(strValue)) {
intValue1 = Integer.valueOf(array[array.length - 3]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.