gpt4 book ai didi

java - 输出间距逻辑错误

转载 作者:行者123 更新时间:2023-12-01 11:38:38 26 4
gpt4 key购买 nike

本质上,我需要做的是将名称(第 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();

}

最佳答案

如果打印制表符 (\t),则会将其后的输出与下一个制表位对齐。那么你就不必计算字符了。

关于java - 输出间距逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29737555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com