我的问题是如何显示我存储的2D数组。
System.out.println("Total amount spent for the month of January is....."
)感谢所有帮助!
import java.util.*;
import java.text.*;
public class test {
static Scanner input = new Scanner(System.in).useDelimiter("\r\n");
static DecimalFormat fmt = new DecimalFormat("0.00");
static String months[] = { null, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; // to store month data
static String monthItems[][] = new String[13][13];
static double amount[][] = new double[13][13];
static int m = 1;
public static void main(String[] args) {
try {
System.out.print("Enter month <1 for Jan - 12 for Dec>: ");
m = input.nextInt();
if (m == 0) {
System.out.println("----------------------------------------");
System.out.println("Invalid month!");
System.out.println();
return;
} else {
}
System.out.println("----------------------------------------");
System.out.println(months[m] + " Expenditure <max 10 items>");
// to store data if January is selected
MonthData();
} catch (Exception e) {
// error message to inform user of wrong input
System.out.println("Invalid month!");
}
try {
System.out.print("Enter month <1 for Jan - 12 for Dec> : ");
m = input.nextInt();
EntryMonth();
System.out.println("----------------------------------------");
System.out.println("Expenditure for " + months[m] + ":");
// to display monthly data
DisplayMonthData();
} catch (Exception e) {
// when user enter's wrong input
System.out.println("Invalid month!");
}
}
static void EntryMonth()// to allow user to enter month data
{
try {
if (m < 1 || m > 12) {
return;
} else {
}
} catch (Exception e) {
System.out.println();
}
}
static void MonthData() {
try {
for (int i = 0; i < 10; i++) {
System.out.print("Enter item " + (i + 1)
+ " <Press ENTER to exit> : ");
monthItems[m][i] = input.next();
if (monthItems[m][i].length() == 0) {
return;
} else {
System.out.print("Enter amount : $");
amount[m][i] = input.nextDouble();
System.out.println("");
}
}
} catch (Exception e) {
System.out.println("");
}
}
static void DisplayMonthData() {
for (int row = 0; row < amount.length; row++) {
for (int column = 0; column < amount[row].length; column++) {
System.out.println(monthItems[row][column]);
}
}
}
}
答案 0 :(得分:0)
有很多方法,但这里应该有一些帮助你。
static void DisplayMonthData()
{
for(int row=0;row<amount.length;row++){
for(int column=0;column<amount[row].length;column++){
String monthItem = monthItems[row][column];
if (monthItem==null)
System.out.print("\t")
else
System.out.print(monthItems[row][column]+"\t");
}
System.out.print("\n");
}
}
如果您想要每行旁边的总计,请重构打印一行的部分,并将其与该行中的值相加。然后添加结尾,添加print(total)
。
编辑跳过空值。
答案 1 :(得分:0)
我不允许对Joeri Hendrickx的回答发表评论,但他是对的。我刚刚尝试了您的代码,输入了10 (enter) foo (enter) 5 (enter) bar (enter) 7 (enter) (enter) 10 (enter)
,它显示的一切都很好。当然除了两个项目之外的所有项目都是空的,除了两个数量之外的所有项目都是0.0,但这正如预期的那样。