gpt4 book ai didi

java - 调用类文件及其方法

转载 作者:行者123 更新时间:2023-12-01 23:12:21 26 4
gpt4 key购买 nike

这是我当前的代码在 SalesManager 客户端应用程序中我想提示用户输入文件名。然后实例化一个SalesAnalyzer对象并调用上面的所有方法,输出每个方法的结果。

如何调用 SalesAnaylzer 及其所有方法?

销售经理:

import java.io.File;
import java.text.DecimalFormat;
import java.util.Scanner;
import java.io.IOException;;

public class SalesManager
{
public static void main( String []args) throws IOException
{
System.out.println(" What is the name of the file");
Scanner scan= new Scanner(System.in);
String fileName= scan.next();
}
}

这是类文件:

import java.io.File;
import java.text.DecimalFormat;
import java.util.Scanner;
import java.io.IOException;
import java.util.*;
import javax.swing.*;
import java.awt.*;

public class SalesAnaylzer {

DecimalFormat pricePattern = new DecimalFormat("$#0.00");
int[][] sales = new int[3][4];

public SalesAnaylzer(String fileName) throws IOException {

File inputFile = new File(fileName);
Scanner scan = new Scanner(inputFile);
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 6; col++) {
sales[row][col] = scan.nextInt();
}
}
}

public String toString() {
String data = "";
for (int row = 0; row < 4; row++) {
data = data + "\nStore " + (row + 1) + ": ";
for (int col = 0; col < 6; col++) {
data = data + "QTR " + (col + 1) + ": " + pricePattern.format(sales[row][col]) + " ";
}
}
return data;
}

public double totalSales() {
double total = 0.0;
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 6; col++) {
total = total + sales[row][col];
}
}
return total;
}

public double highStoreSales(int store) {
double highest = 0.0;
for (int row = 0; row < 4; row++) {
if (sales[row][store] > highest)
highest = sales[row][store];
}
return highest;
}

public double averageStoreSales(int quarter) {
double total = 0.0;
double avg = 0.0;
for (int col = 0; col < 6; col++) {
total = total + sales[quarter][col];
}
avg = (total / 4);
return avg;
}
}

最佳答案

确保它们位于同一个包中,以便您可以直接调用 SalesAnaylzer 类的构造函数和方法。然后像创建其他对象一样创建一个 SalesAnalyzer 对象:

SalesAnaylzer sA = new SalesAnaylzer(filename);
System.out.println(sA);
etc...

关于java - 调用类文件及其方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21686970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com