简体   繁体   English

如何打破循环并排除 C# 中的最后一个输入?

[英]How can I break the loop and exclude the last input in C#?

I have to write a code that asks the user how many movies will be entered.我必须编写一个代码来询问用户将输入多少部电影。 After entering the number of movies, the user should be asked for the names of the movies.输入电影数量后,应要求用户输入电影的名称。 All names will be added to the array movies .所有名称都将添加到数组movies If the user enters "Exit", the program should stop and display the movies that the user has already entered.如果用户输入“退出”,程序应该停止并显示用户已经输入的电影。

I wrote this code:我写了这段代码:

Console.WriteLine("Enter number of movies:");
int num1 = int.Parse(Console.ReadLine());
string[] movies = new string[num1];

for (i = 0; i < num1; i++)
{
    Console.WriteLine("Enter movie name:");
    movies[i] = Console.ReadLine();
    if(movies[i] == "Exit" || movies[i] == "exit")
    {
        break;
    }
}
for (i = 0; i < num1; i++)
{
    Console.WriteLine("Movie {0} is {1}", i + 1, movies[i]);
}

The problem is: If user writes exit the program shows exit as a movie.问题是:如果用户编写exit ,程序会将exit显示为电影。 For example: User wants to enter 4 movies and enters first as the first movies and exit as the second movies.例如:用户想输入 4 部电影,第 1 部电影作为第 1 部电影进入,作为first 2 部电影exit The output of the program in this case will be as follows:本例中程序的output如下:

movie 1 is first 
movie 2 is exit
movie 3 is
movie 4 is

But the program should only display the first movie that was entered.但是程序应该只显示输入的第一部电影。 What am I doing wrong?我究竟做错了什么?

Set the movie entered to a temp variable.将输入的电影设置为临时变量。 Only add it if it isn't your exit condition.仅当它不是您的退出条件时才添加它。

//Rest of the code left out for simplicity
Console.WriteLine("Enter movie name:");
string movie = Console.ReadLine();
if(movie.Equals("exit", StringComparison.OrdinalIgnoreCase)
    break;
else
    movies[i] = movie;  

There are a couple of extra improvements you can make, such as using a List .您可以进行一些额外的改进,例如使用List That way you don't need to manage size and prompt the user.这样你就不需要管理大小和提示用户。

First, lets see what you have: you add the value before checking whether is exit or not.首先,让我们看看你有什么:在检查是否退出之前添加值。

Also, you can compare by ignoring the letters case (answer suggested by Broots Waymb).此外,您可以通过忽略字母大小写进行比较(Broots Waymb 建议的答案)。

Finally, you print the whole array without checking if there are some values or not.最后,您打印整个数组而不检查是否有一些值。

Console.WriteLine("Enter number of movies:");
int num1 = int.Parse(Console.ReadLine());
string[] movies = new string[num1];

for (i = 0; i < num1; i++)
 {
    Console.WriteLine("Enter movie name:");
    movies[i] = Console.ReadLine(); // you always add the value
    if(movies[i] == "Exit" || movies[i] == "exit") 
    {
      break;
    }
}
for (i = 0; i < num1; i++) // there is no condition to stop the iteration.
  Console.WriteLine("Movie {0} is {1}", i + 1, movies[i]);

To solve the print problem, we can add an index that will be incremented only when movie is entered.为了解决打印问题,我们可以添加一个索引,该索引只有在输入电影时才会增加。 Or you can use a list in place or array and you iterate with foreach loop.或者您可以使用列表或数组,然后使用 foreach 循环进行迭代。 Another solution is the possibility to keep the array but transform it to list for the print task.另一种解决方案是保留数组但将其转换为打印任务列表的可能性。

Console.WriteLine("Enter number of movies:");
int num1 = int.Parse(Console.ReadLine());
string[] movies = new string[num1];
int enteredMovies = 0;

for (i = 0; i < num1; i++)
{
    Console.WriteLine("Enter movie name:");
    string movie = Console.ReadLine(); 

    if(movie.Equals("exit", StringComparison.OrdinalIgnoreCase)
    {
       break;
    }
    else
    {
       movies[i] = movie;
       enteredMovies++;

    }

}

for (i = 0; i < enteredMovies; i++)
{
    Console.WriteLine("Movie {0} is {1}", i + 1, movies[i]);
}

Or you can use lists as I mentioned.或者您可以使用我提到的列表。

It will probably be easier to use a List<T> than an array, unless the assignment specifically requires the use of arrays.使用List<T>可能比使用数组更容易,除非分配特别需要使用 arrays。 This would be used something as follows:这将使用如下:

  1. Read the number of movies阅读电影数量
  2. Create a list of movies创建电影列表
  3. Loop the number of movies循环电影的数量
    1. Read a line from the console and store in a temporary variable从控制台读取一行并存储在一个临时变量中
    2. Check if the temporary variable equals exit检查临时变量是否等于退出
    3. Either add the temporary variable to the list of movies, or break the loop要么将临时变量添加到电影列表中,要么打破循环
  4. Now the list of movies should contain all movies entered, neither more nore less.现在电影列表应该包含所有输入的电影,不多也不少。

You have couple of problems:你有几个问题:

  • You are entering the data first and then checking it.您首先输入数据,然后检查它。
  • You need to convert input to lowercase, so that no matter if user enters exit, Exit, EXIT, ExIt your program will terminate.您需要将输入转换为小写,这样无论用户输入exit, Exit, EXIT, ExIt您的程序都会终止。

Your code can be improved but as you are a beginner and might not know advance stuff, I am going to leave as it is:您的代码可以改进,但由于您是初学者并且可能不知道高级的东西,我将保持原样:

using System;

public class Test
{ 

    public static void Main(String[] args)
    {
        Console.WriteLine("Enter number of movies:");
        int num1 = int.Parse(Console.ReadLine());
        string[] movies = new string[num1];

        for (int i = 0; i < num1; i++)
        {
            Console.WriteLine("Enter movie name:");
            String movie = Console.ReadLine();
            if (movie.ToLower() == "exit")
                break;
            else
                movies[i] = movie;
        }
        for (int i = 0; i < num1; i++)
            Console.WriteLine("Movie {0} is {1}", i + 1, movies[i]);
    }
}

Thank you all of you for the attention.谢谢大家的关注。 its a nice community.这是一个不错的社区。

i took a little bit of each answer and managed to solve this problem.我对每个答案都做了一点,并设法解决了这个问题。 I could learn a lot.我可以学到很多东西。

thank you谢谢你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM