而循环问题.. Java初学者 [英] While loop problem.. Java beginner

查看:63
本文介绍了而循环问题.. Java初学者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序,该程序需要一个名字和金额,并发送一个简短的谢谢字母和循环,直到nextLine退出



循环很好,但由于某种原因在第二个循环中程序跳过String输入并直接进入Int ..



boolean keepgoing = true;



while(keepgoing = true)

{







out.println(人名是什么?);



String personname = keyboard.nextLine();



out.println(他们捐了多少钱?);



int donation = keyboard.nextInt ();



out.println(亲爱的+人名+);

out.println(谢谢你的捐款+捐赠+\ n );





out.println(问候,詹姆斯);



if(personname.equals(quit))



{

keepgoing = false;

}



我尝试了什么:



不知道是什么可能是问题,这似乎是一个奇怪的怪癖。

I'm trying to write a program that takes a name and amount of money and sends a short thankyou letter and loops until nextLine is "quit"

Its looping just fine, but for some reason on the second loop the program skips the String enter and goes straight to Int..

boolean keepgoing = true;

while (keepgoing = true)
{



out.println("What is the persons name?");

String personname = keyboard.nextLine();

out.println("How much did they donate?");

int donation = keyboard.nextInt();

out.println(" Dear " + personname + "");
out.println("Thankyou for your donation of " + donation + "\n");


out.println("Regards, James");

if(personname.equals("quit"))

{
keepgoing = false;
}

What I have tried:

No idea what could be the problem, this seems like a strange quirk.

推荐答案

首先,为什么要处理这个名字,如果它还是退出呢?这不是一个真正的名称,它是你的程序的命令 - 所以在你输入名字后立即将你的条件测试移动到那里。然后检查那里。

如果它是一个真正的名字,继续得到捐赠。但如果不是,请退出循环。



其次,为什么不起作用?嗯...这是导致它的nextInt调用 - 它留下了终止输入流上的数字的换行符,因此您对nextLine的下一次调用将检索空行而不是用户输入。在nextInt之后添加nextLine调用以将其删除,并且您已修复。
Firstly, why are you processing the name, if it's "quit" anyway? That isn't a "real" name, it's a command to your program - so move your conditional test to immediately after you input the name, and check there.
If it is a "genuine" name, continue to get the donation. But if it isn't, exit the loop.

Secondly, why doesn't that work? Well ... it's the nextInt call that causes it - it leaves the newline that terminates the number on the input stream, so your next call to nextLine retrieves a blank line instead of the user input. Add a nextLine call after the nextInt to remove it, and you are fixed.


这篇关于而循环问题.. Java初学者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆