【问题标题】:How do I print both Strings and Ints from a single text file?如何从单个文本文件中同时打印字符串和整数?
【发布时间】:2022-01-06 00:38:09
【问题描述】:

我有一个文件,如下所示,但还有几个名称(每个单词和数字都在单独的行上): 詹姆士 123 343 355 凯尔 136 689 680

我一直在尝试将所有这些作为字符串读取,并使用 parseInt 将它们转换为整数,因为我需要找到名称后面数字的平均值。但它没有用,我很好奇如何在 Java 中打印这个文件。谢谢

【问题讨论】:

    标签: java file io parseint


    【解决方案1】:

    让我们假设在每个名称下它们可以是可变数量的数值。我们想要做的是,虽然每一行都是数字,但继续将它们加在一起并跟踪我们读过的行数,当该行变为String 时可能会将其打印出来并设置下一个序列。

    老实说,我认为人们认为Scanner 仅对读取用户输入或文件有用,而忘记了他们可以使用多个Scanners 来解析相同的内容(或提供帮助)

    例如。我设置Scanner 来读取文件的每一行(作为String)。然后我设置第二个Scanner(对于每一行)并测试它是否是int,并采取适当的措施,例如......

    import java.util.Scanner;
    
    public class Test {
    
        public static void main(String[] arg) {
            // Just beware, I'm reading from an embedded resource here
            Scanner input = new Scanner(Test.class.getResourceAsStream("/resources/Test.txt"));
            String name = null;
            int tally = 0;
            int count = 0;
            while (input.hasNextLine()) {
                String line = input.nextLine();
                Scanner parser = new Scanner(line);
                if (parser.hasNextInt()) {
                    tally += parser.nextInt();
                    count++;
                } else {
                    if (name != null) {
                        System.out.println(name + "; tally = " + tally + "; average = " + (tally / (double) count));
                    }
    
                    name = parser.nextLine();
                    tally = 0;
                    count = 0;
                }
            }
            if (name != null) {
                System.out.println(name + "; tally = " + tally + "; average = " + (tally / (double) count));
            }
        }
    }
    

    根据您的示例数据,打印类似...

    James; tally = 821; average = 273.6666666666667
    Kyle; tally = 1505; average = 501.6666666666667
    

    【讨论】:

      【解决方案2】:

      这是您要找的吗?

          import java.util.*;
      
          public class Main
          {
              public static void main(String[] args) {
                  //System.in is a standard input stream
                  Scanner sc= new Scanner(System.in);    
                  String name=sc.next();
                  int a= sc.nextInt();
                  int b= sc.nextInt();
                  int c= sc.nextInt();
                  int d=(a+b+c)/3;
                  System.out.println("Average= " +d);
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-16
        • 2012-11-05
        • 2021-07-25
        • 1970-01-01
        • 1970-01-01
        • 2015-04-28
        相关资源
        最近更新 更多