我想有兩個子程序createArray()
和print()
。 Print()
將需要multArray
變量createArray()
我寫了程序,以便該數組不是在本地創建的主要。我意識到我可以將createArray
設置爲createArray(int a, int b)
但是我決定反對它。這會回來咬我現在還是還有我的方式來完成這個沒有做出建議的變化?有沒有辦法從createArray()在子程序print()中打印multArray?
import java.util.*;
import java.io.*;
public class Array {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String newLine = System.lineSeparator();
String choiceInput;
boolean stop = false;
boolean firstTime = true;
while (stop == false){
if (firstTime == true) {
System.out.println("Welcome To The Multiplications Table Creator!" + newLine + newLine + "Would you like to:" + newLine + newLine + "Create Print Exit" + newLine + newLine + "Please enter one of the above in the space below: ");
}
else {
System.out.println("Welcome Back!" + newLine + newLine + "Would you like to:" + newLine + newLine + "Create Print Exit" + newLine + newLine + "Please enter one of the above in the space below: ");
}
choiceInput = scan.nextLine().toUpperCase();
if (choiceInput.equals("CREATE")) {
createArray();
firstTime = false;
for (int count = 0; count < 10; count++) {
System.out.println(newLine);
}
}
else if (choiceInput.equals("PRINT")) {
print();
firstTime = false;
}
else if (choiceInput.equals("EXIT")) {
for (int count = 0; count < 10; count++) {
System.out.println(newLine);
}
System.out.print("Thank you for using the program!");
for (int count = 0; count < 2; count++) {
System.out.println(newLine);
}
stop = true;
}
else System.out.println("You did not enter one of the above!");
}
}
public static int[][] createArray() {
Scanner s = new Scanner(System.in);
String newLine = System.lineSeparator();
int a;
int b;
System.out.print("How big would you like your multiplication table to be? (A x B)" + newLine + "A: ");
a = s.nextInt();
System.out.println(a + " x ");
b = s.nextInt();
int[][] multArray = new int[a][b];
for (int countA = 1; countA <= a; countA++) {
for (int countB = 1; countB <= b; countB++) {
multArray[countA - 1][countB - 1] = countA * countB;
}
}
System.out.print("Creating .");
delay(1000);
System.out.print(" .");
delay(1000);
System.out.print(" .");
delay(1000);
System.out.println(newLine + "Done.");
return multArray;
}
public static void print() {
**//This is where I need to print multArray created above is it possible?**
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
}
catch (InterruptedException exp) {
}
}
}
notenote 1:定義一個全局掃描程序並重用它,不需要定義每個掃描程序的倍數。旁註2:「if(!stop)」和「if(firstTime)」比我眼中的bool值更好。 – SomeJavaGuy
您沒有存儲函數'createArray()'的結果,因此您無法正確使用'print()'。 您需要將它作爲私有成員存儲,然後在'print()'中訪問它,或者將它作爲參數傳遞給'print()'。 – Ghost93
在這種情況下,'return multArray'是不夠的嗎?在代碼方面,這需要我做什麼? –