希望有人帮助我还为时不晚。我正在尝试创建一个程序,它有一个类(TestCode),要求用户输入 4 个整数。然后,我将该类中的变量发送到另一个类(MySmartDataType)。然后,我使用这些整数来执行某些计算。问题是,我不确定如何让第二个程序正确地接受这些整数。这里是第一堂课。
import java.util.*;
class TestCode{
public static void main(String args[]){
int n1 = 0;
int n2 = 0;
int n3 = 0;
int n4 = 0;
String repeat = "Y";
int evenTotal = 0;
int oddTotal = 0;
MySmartDataType msdt;
Scanner sc;
sc = new Scanner(System.in);
while (repeat == "Y"){
System.out.println("Enter number 1 ");
n1 = sc.nextInt();
System.out.println("Enter number 2 ");
n2 = sc.nextInt();
System.out.println("Enter number 3 ");
n3 = sc.nextInt();
System.out.println("Enter number 4 ");
n4 = sc.nextInt();
System.out.println("Would you like to continue? N for no and Y for Yes.");
repeat = sc.nextLine();
msdt = new MySmartDataType(n1,n2,n3,n4);
}
evenTotal = msdt.getEvenTotal();
System.out.println("Even total is: " + evenTotal);
oddTotal= msdt.getOddTotal();
System.out.println("Odd total is: " + oddTotal);
System.out.println("Grand Total is: " + msdt.getTotal() );
}
}
这是第二个:
import java.util.*;
class MySmartDataType {
private int myArray[] = new int [4];
myArray[4] = {n1, n2, n3, n4};
int getEvenTotal(){
int sumEven = 0;
for (int i = 0; i <= myArray.length; i++){
if (myArray[i] % 2 == 0){
sumEven += myArray[i];
}
}
System.out.println("The even total is: " + sumEven);
return sumEven;
}
int getOddTotal(){
int sumOdd = 0;
for (int i = 0; i <= myArray.length; i++){
if (myArray[i] % 3 == 0){
sumOdd += myArray[i];
}
}
System.out.println("The odd total is: " + sumOdd);
return sumOdd;
}
int getTotal(){
int sumTotal;
for (int i = 0; i <= 3; i++){
sumTotal += myArray[i];
}
System.out.println("The total is: " +sumTotal);
return sumTotal;
}
}