简体   繁体   中英

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 . 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. For example: User wants to enter 4 movies and enters first as the first movies and exit as the second movies. The output of the program in this case will be as follows:

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 . 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).

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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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