英文:
New to programming having problems
问题
我知道 "\n" 在使用时会产生一个新的换行。在文本之前加上 "\n" 会在文本之前创建一个新行,在文本之后加上会在文本之后创建一个新行。然而,我已经编写了我的代码,如下所示,除非我还在我创建的类的方法中也放入 "\n",否则不会创建新的换行。请有人帮助我理解为什么?
在我的方法的 system.out.println 行中没有 "\n",这种情况就不会发生。它会显示如下:
休斯顿店:
总收入为 $...
西雅图店:
总收入为 $
我希望它看起来像这样:
休斯顿店:
总收入为 $...
西雅图店:
总收入为 $....
代码:
System.out.println("休斯顿店:");
houstonStore.grossRevenue();
System.out.println("\n西雅图店:");
seattleStore.grossRevenue();
System.out.println("\n奥兰多店:");
orlandoStore.grossRevenue();
}
}
class groceryStore {
int applesSoldYearly;
double priceOfApples;
int orangesSoldYearly;
double priceOfOranges;
// 计算总收入并在调用时打印到屏幕上的方法
void grossRevenue() {
double revenue;
revenue = (applesSoldYearly * priceOfApples)
+ (orangesSoldYearly * priceOfOranges);
System.out.print("总收入为 $" + revenue);
}
英文:
I know that the \n should provide me with a new line when utilized. With \n before text being it will put a new line before the text and with it after will create a new line after the text. However, I have written my code, see below, and the new line isn't created unless I also put the \n in the method of my created class as well. Would someone please help me understand why?
Without the \n in my system.out.println line of my method, this doesn't happen. It will come out like this:
Houston Store:
Gross Revenue is $...
Seattle Store:
Gross Revenue is $
I want it to look like this:
Houston Store:
Gross Revenue is $...
Seattle Store:
Gross Revenue is $....
code:
System.out.println("Houston Store:");
houstonStore.grossRevenue();
System.out.println("\nSeattle Store: ");
seattleStore.grossRevenue();
System.out.println("\nOrlando Store: ");
orlandoStore.grossRevenue();
}
}
class groceryStore {
int applesSoldYearly;
double priceOfApples;
int orangesSoldYearly;
double priceOfOranges;
//methods to calculate gross revenue & then print to the screen when called
void grossRevenue() {
double revenue;
revenue = (applesSoldYearly * priceOfApples)
+ (orangesSoldYearly * priceOfOranges);
System.out.print ("Gross Revenue is $" + revenue);
}
答案1
得分: 0
我认为你的困惑来自于你对System.out.println和System.out.print(没有'ln')的混合使用。由于你在grossRevenue中使用了System.out.print,它没有在结尾添加换行符。将该语句更改为使用System.out.println应该会得到你想要的输出。
英文:
I think your confusion is coming from your mixed use of System.out.println and System.out.print (without the 'ln'). Since you are using System.out.print in grossRevenue, it isn't adding the newline at the end. Changing that statement to use System.out.println should give you the intended output.
专注分享java语言的经验与见解,让所有开发者获益!
评论