【问题标题】:How to read a String followed by an int in Java?如何在Java中读取一个字符串后跟一个int?
【发布时间】:2016-07-10 00:41:24
【问题描述】:

我一直在努力完成这项工作。我需要的是读取这样的输入:DEPOSITO 123 1000.00,但字符串“DEPOSITO”需要保存在一个变量中,int“123”保存到另一个变量,双“1000.00”保存到另一个变量。问题是我找不到像scanner.nextString() 这样的东西,如果我可以只将字符串扫描到一个变量中,我可能可以用scanner.nextInt()scanner.nextDouble() 扫描输入流的其余部分。如果我在尝试仅读取字符串时执行scanner.next(),它会读取整行,那么我的问题的答案是什么?我真是一头雾水。

【问题讨论】:

  • 考虑将字符串按空格分成 3 部分。
  • 您能否发布您遇到问题的代码部分?这会让我们更容易为您提供帮助
  • @user3814613 已回答,但谢谢。

标签: java java.util.scanner inputstream


【解决方案1】:

由于输入总是以字符串开头,所以可以先获取字符串,然后根据它判断后面有多少个变量:

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

【讨论】:

  • 输入并不总是由 3 个部分组成,有时它有 4 个部分。什么决定了输入开头的字符串,如果它是“SAQUE”或“DEPOSITO”,它将有更多的 2 个部分(int 和 double)。但是,如果字符串是“TRANSFERENCIA”,则它有更多的 3 个部分(int、int 和 double)
  • 我可以看到它背后的逻辑,问题是..我正在逐步调试我的程序,它会将整行读取为字符串输入,但是当我执行String[] tokens = input.split("\\s+") 时它没有'不要拆分字符串,我可以访问变量面板,tokens[0] 是整个输入。
【解决方案2】:
String[] s = scanner.nextLine().split(" ");

那么你将有 3 个字符串:

  1. s[0] 这将返回 "DEPOSITO"
  2. s[1] 返回“123”
  3. s[2] 会返回“1000.00”

现在:

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

【讨论】:

    【解决方案3】:

    你可以像这样解析值

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-19
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      相关资源
      最近更新 更多