基本上我需要做的是将名称(第1行)的间距与价格(第2行)相匹配,但它没有按计划进行,我不确定原因。无论出于何种原因,我从来没有使用一组测试代替价格的问题,但现在我已将它切换为双倍,间距非常小。
输出:
Chips Cookies Applesauce Cracker-n-Cheese
0.75 1.0 0.5 1.0
Apple Snickers BabyRuth MilkyWay
0.5 1.0 1.0 1.0
M&M's Kit-Kat TrailMix CrunchyCheetos
1.0 1.0 1.5 0.75
What would you like to buy?
代码:
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 4; j++)
{
/*System.out.println("What is the name of the snack item you'd like to add to row " + i +", column " + j + "?");
name = in.next();
System.out.println("What is the price of " + name +"?");
price = in.nextDouble();
product = new Product(name, price);
products[i-1][j-1] = product;*/
//Change back to what's above when done testing
name = fin.next();
price =fin.nextDouble();
product = new Product(name, price);
products[i-1][j-1] = product;
if(i == 1 && j == 1)
max = name.length();
else if(name.length() > max)
max = name.length();
}
}
System.out.println("\n\n ");
while (!in.equals("-999"))
{
for (int i = 0; i < 3; i++)
{
System.out.println();
for (int j = 0; j < 4; j++)
{
numSpaces = max + 4 - products[i][j].getName().length();
System.out.print(products[i][j].getName());
for (int k = 0; k < numSpaces; k++)
System.out.print(" ");
}
System.out.println();
for (int j = 0; j < 4; j++)
{
len = "" + products[i][j].getPrice(); //Can't cast from double to string :(
numSpaces2 = numSpaces + products[i][j].getName().length() - len.length();//Doesnt work
System.out.print(products[i][j].getPrice());
for (int k = 0; k < numSpaces2; k++)
System.out.print(" ");
}
System.out.println();
}
System.out.println("What would you like to buy?");
itemRequested = in.next();
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
if (itemRequested.equalsIgnoreCase(products[i][j].getName()))
boughtItem = products[i][j];
}
}
if(boughtItem != null)
{
System.out.println("Thank you for selecting " + boughtItem.getName() + "!\nThat will cost $" + boughtItem.getPrice());
System.out.println();
//Add delay for 7 seconds later
}
else
{
System.out.println("We dont carry that!\n");
//Add delay for 7 seconds later
}
}
in.close();
}
答案 0 :(得分:1)
如果您打印制表符(\t
),则会将其后的输出与下一个制表符对齐。那你就不用数字了。
答案 1 :(得分:0)
那里有两个问题