【问题标题】:A program that reads a text file and determines the most expensive purchase读取文本文件并确定最昂贵购买的程序
【发布时间】:2015-09-11 23:55:12
【问题描述】:

我需要帮助的程序涉及读取一个 .txt 文件,该文件包含 信用卡交易,例如:杂货 50.36 美元,汽油 41.20 美元等,我需要找到最贵的商品并打印商品的名称和价格。我无法找到获取和判断哪个商品的方法最昂贵的。我如何读取和抓取整数并将它们与其他整数进行比较以查看哪个更大?

import java.io.*;
import java.util.*;

public class Transcation {

    public static void main(String[] args)throws IOException {
        Scanner console = new Scanner(System.in);
           System.out.println("Enter the directory of file: "); //ask for file
           String filename = console.nextLine();       //input directory of file

           File inputFile = new File(filename);        

           if(!inputFile.exists()){     //if it does not exist print error,end
               System.out.println("Transaction.txt not found");
               System.exit(0);
           }

           Scanner input = new Scanner(inputFile);  //reads and access the file
           String line;


                while(input.hasNext()){   //while its still has more lines loop
                    line = input.nextLine();    

                        //System.out.println(line); //prints the next line

                }         
          input.close();    //closes file

    }
}

【问题讨论】:

  • 欢迎来到 StackOverflow。提供一些代码来显示您尝试过的内容总是一个好主意。从您粘贴的内容来看,我没有看到任何试图对数字做任何事情的东西?另请注意,您说当价格不是整数时阅读integers,因为它们有美分。
  • 整数?您的价格似乎是浮动/双倍。

标签: credit-card


【解决方案1】:

您可以通过' ' 将字符串拆分为名称和值。将值解析为double

像这样:

String[] parts = yourStringFromFileLine.split( " " );

// access the parts
String name = parts[ 0 ]; // name if item
double price = Double.parseDouble( parts[ 1 ] ); // price of item

将每一行保存在Map 中,名称为key,价格为value

像这样:

Map<String, Integer> map = new HashMap<String, Integer>();
// add content to map
map.put( name , price );

读完文件后,遍历Map 并为key 找到最高的value

像这样:

double tempPrice = 0.0;

for ( Map.Entry<String, Integer> entry : map ) {
    if ( entry.getValue() > tempPrice ) {
        tempPrice = entry.getValue();
    }
}

最后tempPrice是所有参赛作品中的最高价。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 1970-01-01
    • 2017-10-12
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2012-03-23
    • 2023-03-15
    相关资源
    最近更新 更多