Java从文本文件中读取整数和字符串,然后使用整数和字符串

时间:2014-12-02 18:28:25

标签: java string integer

我试图从文本文件中读取一些数据,其格式为:

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。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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;
...

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