【问题标题】:Java reading integers and strings from text file and then using the integers and stringsJava 从文本文件中读取整数和字符串,然后使用整数和字符串
【发布时间】:2014-12-02 18:28:25
【问题描述】:

我正在尝试从文本文件中读取一些数据,格式如下:

String (Monday)
String (M141)
Integer (16)
Integer (6)
Double (10.5)
Double (10.5)
Integer (20)
Integer (20)
Integer (20)
Integer (30)

我已经设法读取文件并尝试使用 nextLine 来显示这些,这很有效,但是在使用下一行打印出这些值之后,我需要操作我需要加起来的数据(30、20、20、20 , 10.5, 10.5) 并将其乘以 (16) 以获得最终值,但我想不出办法做到这一点,我尝试使用数组来存储它们然后操作它们但没有运气。有不止一组具有相同格式但不同整数的数据。请帮助我了解如何解决这个问题,我已经尝试了一天多。到目前为止,这是我的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class Main {

    static Scanner console = new Scanner(System.in);


    public static void main(String[] args) throws FileNotFoundException {

        Scanner reader = new Scanner(new File("C:\\data.txt"));

        System.out.println(reader.nextLine());
        System.out.println(reader.nextLine());
        System.out.println(reader.nextInt());
        System.out.println(reader.nextInt());
        System.out.println(reader.nextDouble());
        System.out.println(reader.nextDouble());
        System.out.println(reader.nextInt());
        System.out.println(reader.nextInt());
        System.out.println(reader.nextInt());
        System.out.println(reader.nextInt());

    }
}

编辑: 我需要将 (10.5) (10.5) (20) (20) (20) (30) 相加并乘以 16。

【问题讨论】:

  • 所以 java 有一个奇怪的东西, reader.nexInt() 不会在字符串末尾拾取换行符。如果您在那之后再进行扫描,请注意。只需将所有整数作为双打并将它们全部加起来应该可以正常工作。如果以后需要使用数据,可以使用数组或数组列表。如果我们获得了您的数据样本,那也会有很大帮助。
  • 不确定您到底想完成什么。您希望提取的数据采用什么格式?这些值是某个对象的属性吗?在我看来,您必须先解析类型信息,然后切换可能的类型以正确解析带括号的值。这是您遇到的问题吗?
  • 我正在尝试从我已经完成的文件中读取数据并打印出来。我需要将文件中的值相加并忽略文件的某些部分。这是我的数据: Monday M141 16 6 10.5 10.5 20 20 20 30 正在读取此数据,16 是此人工作的小时数。 30、20、20、20、10.5、10.5需要加起来乘以16
  • 那是文件的一行还是 10 行?
  • 您必须根据哪些规则来决定忽略什么、添加什么以及相乘什么?

标签: java string integer


【解决方案1】:

如果您在获取数字本身时遇到问题,请查找 Java Substring。这很有帮助。并搜索 Java IndexOf。这两种方法对你有很大帮助。 例如 字符串 a = "鲍勃 (10)"; 字符串 x = a.substring(a.indexof("("),a.indexOf(")"));

【讨论】:

    【解决方案2】:

    听起来好像文件是用try行写的

    Scanner reader = new Scanner(new File("C:\\data.txt"));
    
    String monday = reader.nextLine();
    // splits up the string into pieces, seperated at the space
    String[] parts = monday.split(" ");
    String day = parts[0];
    
    // you may have to use Integer.parseInt() here I don't remember
    int hourMutiplier = parts[2];
    int people = parts[3];
    double wages = 0;
    for( int i = 4; i < people + 3; i++){
      wages += parts[i];  
    }
    double finalWages = wages * hourmutiplier;
    ...
    

    或类似的东西,语法可能有点不对。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2019-05-12
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      相关资源
      最近更新 更多