Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

Using if to compare strings c#

I am trying to compare strings then have it write hi if the strings are equal. But whenever I enter AS I get nothing AS being the string i want to compare my input against.

Here is my code.

using System;

namespace testing121
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            long vrt;
            bool run;
            string pass = ("AS");
            run = true;
            string vrt2;
            while (run)
            {
                if (long.TryParse (Console.ReadLine (), out vrt)) {
                    vrt2 = Convert.ToString (vrt);
                    if (String.Equals (pass, vrt2) ) {
                        Console.WriteLine ("Hi");
                    }
                }
            }}}}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This code just doesn't make sense. You're entering AS but then checking if it can be converted to a long as part of your condition for equality. Just do this;

public static void Main (string[] args)
{
   string pass = "AS";

   if (Console.ReadLine() == pass)
       Console.WriteLine("hi");
}

Then, if you want to put that in a loop or whatever go for it. But I recommend starting with the simplest most basic thing. When you run this program and enter AS it will print hi


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...