我有输入 cargo 数量的程序,并且有 switch - case 语句。
案例1:输入新的商品数据
案例2:打印所有数据的报告
在情况1中,程序输入新数据。代码是这样的
import java.util.Scanner;
public class inputData {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int add = 0;
System.out.println("1. Create a new goods data\n2. Print the data");
System.out.print("Type the option by typing sc: ");
int menu = sc.nextInt();
switch (menu) {
case 1:
String finalResult[][] = inputAgainConfirmation(createFirstRow(add), add);
break;
case 2: //the code is not written yet
break;
}
}
static String[] information() {
String info[] = {"Code", "Name", "Purchase Price", "Selling Price", "Incoming Goods", "Outgoing Goods", "Damaged Goods", "Total Goods"};
return info;
}
static String[][] createFirstRow(int add) {
String info[] = information();
String create[][] = new String[1][8];
sc.nextLine();
for (String[] create1 : create) {
for (int j = 0; j < create[0].length; j++) {
System.out.print("Input the " + info[j] + ": ");
String input = sc.nextLine();
create1[j] = input;
}
}
return create;
}
static String[][] InputNewDataAgain(String[][] result, int add) {
sc.nextLine();
String info[] = information();
String backup[][] = result;
result = new String[result.length + 1][result[0].length];
System.arraycopy(backup, 0, result, 0, backup.length);
for (int i = backup.length; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
System.out.print("Input the " + info[j] + ": ");
String input = sc.nextLine();
result[i][j] = input;
}
}
return result;
}
static String[][] inputAgainConfirmation(String[][] result, int add) {
System.out.print("Create again? 1 = yes, 0 = no: ");
int in = sc.nextInt();
if (in == 1) {
String createAgain[][] = InputNewDataAgain(result, ++add);
return inputAgainConfirmation(createAgain, add);
} else {
return result;
}
}
}
我想打印情况 2 中 FinalResult[][] 的值。
如何保存case 1语句的finalResult[][],这样当我想调用结果时,程序就不会再填满了。
最佳答案
在您的代码中,finalResult 是本地变量,即该变量的范围在该 switch case block (案例 1)内,用于在案例 2 中打印该变量结果,将该变量设置为全局,请参阅下面的代码:
public static void main(String[] args) {
int add = 0;
String finalResult[][] = new String[10][10]; // declare finalResult variable
System.out.println("1. Create a new goods data\n2. Print the data");
System.out.print("Type the option by typing sc: ");
int menu = sc.nextInt();
switch (menu) {
case 1:
finalResult[][] = inputAgainConfirmation(createFirstRow(add), add); // Assign value
break;
case 2: //the code is not written yet
// Print finalResult value
break;
}
}
关于java - 如何将案例 1 的结果应用到另一个案例中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59285567/