我的程序应该从4个房间计算瓶子。当用户输入退出时,程序将吐出每个房间收集的瓶子数量。
程序提示用户时出现问题,它会提示两次,但会将最后输入的数字作为选定的roomNumber
。我也不知道如何设置我的if语句,这样我就可以不断将用户输入的瓶子加到每个特定的房间。
我可以使用临时变量来存储输入的瓶数,然后将其添加到保存当前瓶数的room1
,room2
吗?
namespace BottleDrive1 {
class Program {
static void Main(string[] args)
{
//Initialize 4 rooms.
int room1 = 0;
int room2 = 0;
int room3 = 0;
int room4 = 0;
int roomNumber;
while (true)
{
Console.WriteLine("Enter the the room number you are in.");
string quit = Console.ReadLine();
if (quit == "quit")
{
//Break statement allows quit to jump out of loop
break;
}
//int roomT = int.Parse(quit);//a temp variable I want to use to add bottles to the count.
roomNumber = int.Parse(Console.ReadLine());
if (roomNumber == 1)
{
Console.WriteLine("How many bottles did room 1 collect?");
room1 = int.Parse(Console.ReadLine());
}
if (roomNumber == 2)
{
Console.WriteLine("How many bottles did room 2 collect?");
room2 = int.Parse(Console.ReadLine());
}
if (roomNumber == 3)
{
Console.WriteLine("How many bottles did room 3 collect?");
room3 = int.Parse(Console.ReadLine());
}
if (roomNumber == 4)
{
Console.WriteLine("How many bottles did room 4 collect?");
room4 = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("Bottles each room has collected:");
Console.WriteLine("Room one:" + room1);
Console.WriteLine("Room two:" + room2);
Console.WriteLine("Room three:" + room3);
Console.WriteLine("Room four:" + room4);
int maxRoom = room1;
if (room2 > maxRoom)
{
maxRoom = 2;
}
if (room3 > maxRoom)
{
maxRoom = 3;
}
if (room4 > maxRoom)
{
maxRoom = 4;
}
else
{
maxRoom = 1;
}
Console.WriteLine("The winner is room " + maxRoom + "!");
}
}
}
答案 0 :(得分:4)
你非常接近!在while循环中,您从控制台读取退出的值,并通过再次从控制台读取来“提示”用户再次输入房间号。您可以通过简单地获取退出值并解析房间号来避免第二个“提示”。请注意,一切都会正常工作,因为如果用户输入quit,那么无论如何都会退出循环:
while (true)
{
Console.WriteLine("Enter the the room number you are in.");
string quit = Console.ReadLine();
// another quick thing to fix is to ignore the case (don't trust the user)
if(quit .Equals("quit", StringComparison.InvariantCultureIgnoreCase))
{
//Break statement allows quit to jump out of loop
break;
}
roomNumber = int.Parse(quit); // you've already asked the user for input, so just reuse the variable holding the input
// TODO: consider what happens if you can't parse an integer, i.e. use TryParse etc
// do whatever you need to do after that
}
获得房间号码后,不要忘记使用'+ =运营商'添加瓶数,例如:
room4 += int.Parse(Console.ReadLine());
答案 1 :(得分:0)
您需要将从Console.ReadLine()收到的值添加到类似房间的现有瓶数:
room1 = room1 + int.Parse(Console.ReadLine());
或者您可以使用速记版本:
room1 += int.Parse(Console.ReadLine());
您目前遇到的问题是,当你为一个房间输入5瓶时,room1
会在变量中保存5个。下次为房间输入10瓶时,room1
会在变量中保存10个。您需要将这两个数字加在一起,以便保留一个房间的瓶子总数。