如何在Java中读取String后跟一个int?

时间:2016-07-10 00:41:24

标签: java java.util.scanner inputstream

我一直在努力完成这项工作。我需要的是读取这样的输入:scanner.nextString(),但字符串“DEPOSITO”需要保存在一个变量中,int“123”保存到另一个变量,双“1000.00”保存到另一个变量。问题是我找不到scanner.nextInt()之类的内容,如果我只能将字符串扫描到变量中,我可能会使用scanner.nextDouble()scanner.next()扫描输入流的其余部分。如果我试图只读取字符串class location: NSObject, CLLocationManagerDelegate { var locationManager = CLLocationManager() internal func getLocation() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest if CLLocationManager.authorizationStatus() == .AuthorizedAlways { locationManager.startUpdatingLocation() } else if CLLocationManager.authorizationStatus() == .NotDetermined { locationManager.requestAlwaysAuthorization() } else if CLLocationManager.authorizationStatus() == .Denied { print("User denied location permissions.") } } // MARK : CLLocationManagerDelegate protocol @objc func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location: CLLocationCoordinate2D = (locationManager.location?.coordinate)! print(location.latitude) print(location.longitude) } } ,它会读取整行,那么我的问题的答案是什么?我真的很无能。

3 个答案:

答案 0 :(得分:3)

由于输入始终以字符串开头,因此您可以先获取字符串,然后根据该字符串确定后面有多少变量:

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)的更多信息,请参阅:Learning Regular Expressions

答案 1 :(得分:2)

String[] s = scanner.nextLine().split(" ");

然后你将有3个字符串:

  1. s[0]将返回" DEPOSITO"
  2. s[1]返回" 123"
  3. s[2]并且它将返回" 1000.00"
  4. 现在:

    Integer i = Integer.parseInt(s[1]);
    Double d = Double.parseDouble(s[2]);
    

答案 2 :(得分:1)

你可以像这样解析价值

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