我正在为我的妈妈制作一个以赛马为主题的程序,该程序将她的员工拿来的钱与马匹联系起来。我创建了两个完全相互依赖的方法,并且不知道如何将它们调用到我的main方法中。当然,我有时也需要为此添加图形元素,并且弄清楚如何使程序使用十进制整数也将是理想的。现在,我的主要问题是我需要知道如何在我的main方法中调用print3largest和input,或者通常如何使它不成为垃圾箱之火,并可能将其减少到少于3个这样不纠结的方法。 >
我已经在存储库网站上搜索了几个小时,现在正在寻找解决方案,但是由于我没有任何编程经验,因此我严重缺乏寻找答案的术语,前提是其他人都愚蠢到可以碰到这个问题。我有同样的问题。我的编程知识非常有限,由于高中课程的缘故,Java是我所困扰过的唯一事物。令人遗憾的是,这几乎没有作用,因为它几乎完全是通过本质上只是一个临时界面的。
import java.util.Scanner;
class HorseComparison
{
public static void main(String[] args)
{
//no clue how to call print3largest or inputs here without ruining everything
}
static void print3largest(int arr[], int arr_size, String firsthorse, String secondhorse, String thirdhorse)
{
int i, first, second, third;
if (arr_size < 3)
{
System.out.print(" Invalid Input ");
return;
}
third = first = second = Integer.MIN_VALUE;
for (i = 0; i < arr_size ; i ++)
{
if (arr[i] > first)
{
third = second;
second = first;
first = arr[i];
}
else if (arr[i] > second)
{
third = second;
second = arr[i];
}
else if (arr[i] > third)
third = arr[i];
}
inputs(first, second, third);
System.out.println("The horse in the lead is " + firsthorse + " with " +
first + " dollars.");
System.out.println("The runner up is " + secondhorse + " with " +
second + " dollars.");
System.out.println("Third place is " + thirdhorse + " with " +
third + " dollars.");
}
static void inputs(int first, int second, int third)
{
Scanner sc = new Scanner(System.in);
int size;
System.out.println("How many horses are competing?");
size = sc.nextInt();
int[] arr = new int[size];
System.out.println("Enter the amount of money taken in by each horse (rounded to the nearest dollar and separated by spaces)");
//For reading the element
for(int i=0;i<size;i++) {
arr[i] = sc.nextInt();
int n = arr.length;
String firsthorse;
String secondhorse;
String thirdhorse;
System.out.println("Which horse has taken in "+ first +"?");
firsthorse = sc.toString();
System.out.println("Which horse has taken in "+ second +"?");
secondhorse = sc.toString();
System.out.println("Which horse has taken in "+ third +"?");
thirdhorse = sc.toString();
print3largest(arr, n, firsthorse, secondhorse, thirdhorse);
}
}
}
我希望它显示3个最高数量以及与这些数量相关的马的输入名称。
答案 0 :(得分:0)
您可以直接通过方法名称调用静态方法
print3largest()
或者您可以在方法名称示例之前使用类名
HorseComparision.print3largest() ```
答案 1 :(得分:0)
由于这两种方法都是静态的,因此是Main方法。静态方法可以称为
print3largest(.. args), inputs(.. args)
HorseComparison.print3largest(.. args), HorseComparison.inputs(.. args)
答案 2 :(得分:0)
我觉得确实没有足够的有关程序打算做什么的信息,以便提供清晰,直接的答案,但是我会尽力而为。
首先,我的建议是,您仔细看一下该程序并确定如何区分每个职责。例如,您是否真的需要从inputs
调用print3largest
,还是可以直接从您的主站调用此电话?
一旦确定了每个函数的意图,请考虑使每个函数返回结果。一般来说,您希望参数为不可变。现在学习函数式编程习惯将可以帮助您。
这就是我要做的:
print3largest
中。 将结果返回给呼叫者。这可能会导致更多功能,但这并不是一件坏事。我还建议您考虑创建一个单独的类来容纳某些逻辑。这将使您有机会了解对象和关注点分离。