如何将案例 1 的结果用于另一个案例



我有输入货物数量的程序,我有开关 - 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 datan2. 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 中打印最终结果 [][] 的值。

如何保存案例 1 语句的 finalResult[][],这样当我想调用结果时,程序不会再填满了。

在您的代码中,finalResult 是局部变量,即此变量的范围在该开关 case 块(案例 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 datan2. 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;
}
}

最新更新