Home > Enterprise >  Trying to use a for loop to try and match user input to a premade array. Getting a warning for unrea
Trying to use a for loop to try and match user input to a premade array. Getting a warning for unrea

Time:02-13

I must get the user to enter a zip code and then the program searches a premade array to either confirm or deny their zip code.

It works fine when the zip codes don't match but it doesn't recognize it when it does.

Also, the line where I am getting the 'unreachable code' warning is in my loop controls:

for (int i = 0; i < zips.Length; i  )

The rest of the code looks like this:

    string[] zips = { "I won't bother you with all the zip codes manually entered here" };  
    System.Console.WriteLine("Enter your zip code > ";  
    string userZip = System.Console.ReadLine();  

    for (int i = 0; i < zips.Length; i  )  
     {  
        if (userZip == zips[i])  
           System.Console.WriteLine("Delivery to "   userZip   " ok.");  
        else  
           System.Console.WriteLine("Sorry - no delivery to "   userZip);  
        break;  
    }  

CodePudding user response:

Here's one working solution (includes some sample made up ZIP codes).

using System;
using System.Linq; 
                    
public class Program
{
    public static void Main()
    {
        var zips = new [] {"12345", "23456", "34567"};
        
        System.Console.WriteLine("Enter your zip code > ");  
        string userZip = System.Console.ReadLine(); 
        
        var match = zips.FirstOrDefault(z => z == userZip);

        if(match!=null)  System.Console.WriteLine("Delivery to "   userZip   " ok.");  
        else  System.Console.WriteLine("Sorry - no delivery to "   userZip);  
    }
}

Explanation: instead of manually writing a for loop, I used a System.Linq function FirstOrDefault() to look through the list of zip codes instead. Internally it uses a loop but its just a simpler way of writing the logic required (IMO). It will either return the first match or null if none.

And you can run and try it right here: https://dotnetfiddle.net/yHDfEk

Sample input/output (no match):

Enter your zip code > 
12344
Sorry - no delivery to 12344

Sample input/output (match):

Enter your zip code > 
23456
Delivery to 23456 ok.

An example of where this is easier is that it deals with loop termination for you. (As noted in a comment by @Flydog57) you have the break statement in the wrong place which causes your program to misbehave. That extra logic is handled implicitly in the example I gave. Instead, you would want something like this:

var found = false;

for (int i = 0; i < zips.Length; i  )  
 {  
    if (userZip == zips[i])  
    {
       found = true;
       System.Console.WriteLine("Delivery to "   userZip   " ok.");  
       break;  
    }
}  

if(!found) System.Console.WriteLine("Sorry - no delivery to "   userZip);  

Note that if you wanted to use a manual loop, I would recommend foreach instead of for in most situations where you have a simple array, list, or similar data structure to loop through. foreach is just easier to get right.

var found = false;

foreach(var zip in zips) 
{
    if (userZip == zip)  
    {
       found = true;
       System.Console.WriteLine("Delivery to "   userZip   " ok.");  
       break;  
    }
}  

if(!found) System.Console.WriteLine("Sorry - no delivery to "   userZip);  

CodePudding user response:

The question is not very much clear and also not formatted well. I guss this would be the solution:

public class Run {
    public static void main(String[] args) {
        String[] zips = {"11", "13", "30", "50"};
        Scanner scanner = new Scanner(System.in);
        String input = scanner.next();

        Stream<String> stream = Stream.of(zips);
        if(stream.anyMatch(x -> input.equals(x))){
            System.out.println("Delivery to "   input   " ok.");
        }else {
            System.out.println("Sorry - no delivery to "   input);
        }
    }
}

CodePudding user response:

It seems like this code might actually be written in C#, is this the language that you're targeting? For instance, Java does not have a System.Console.WriteLine method available, however C# does:

https://docs.microsoft.com/en-us/dotnet/api/system.console.writeline?view=net-6.0#system-console-writeline(system-char())

A question like this might be best suited for the Code Review StackExchange:

https://codereview.stackexchange.com/


EDIT

  1. It looks like you may simply be missing a closing ) in your call to WriteLine.
  2. the break isn't necessary as it will leave the for loop after the first iteration, not allowing you to search the rest of the string[] It looks like you should put the break in the body of the first if, which will require you to add {} to it

https://replit.com/@mynameishank/PrudentForthrightCodec#main.cs

class Program {
    static void Main(string[] args) {
      string[] zips = { "1", "2" };  
      System.Console.WriteLine("Enter your zip code > ");  
      string userZip = System.Console.ReadLine();  
      
      for (int i = 0; i < zips.Length; i  ) {  
          if (userZip == zips[i]) {
             System.Console.WriteLine("Delivery to "   userZip   " ok.");  
             break;
          }
          else  
             System.Console.WriteLine("Sorry - no delivery to "   userZip); 
      }
    }
}
  • Related