![](/img/trans.png)
[英]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.