简体   繁体   English

接受字符串输入到数组中并检查数组中字符串的可用性

[英]Accepting string inputs into an array and checking the availability of the string in the array

So I am completely new to java, and I want to create a code to accept string inputs from a user, and store it into an array.所以我对 java 完全陌生,我想创建一个代码来接受来自用户的字符串输入,并将其存储到一个数组中。 After this in the next statement, I will type a value into the terminal, and I want the code to compare my string input to one of the strings in the array and print available on the terminal when the string is available and vice versa.在下一个语句中,我将在终端中输入一个值,并且我希望代码将我的字符串输入与数组中的一个字符串进行比较,并在字符串可用时在终端上打印可用,反之亦然。 The first part of my code was right (hopefully) but I had a problem in comparing the strings.我的代码的第一部分是正确的(希望如此),但我在比较字符串时遇到了问题。 I feel it doesn't check the strings with my input in the code.我觉得它不会用我在代码中的输入来检查字符串。 Here is my code, Could anyone please help me with this?这是我的代码,有人可以帮我吗? Thank you so much.太感谢了。

import java.util.Scanner;
class Course {
 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  String a[] = new String[20] //assuming max 20 strings
  System.out.println("Enter no. of courses");
  int no_of_courses = sc.nextInt(); // number of strings
  if (no_of_courses <= 0)
   System.out.println("Invalid Range");
  else {
   System.out.println("Enter course names:");
   for (int i = 0; i < no_of_courses; i++) {
    a[i] = sc.next(); //accepting string inputs
   }
   System.out.println("Enter the course to be searched:");
   String search = sc.next() //entering a string to search
   for (int i = 0; i < no_of_courses; i++) {
    if (a[i].equals(search)) //I feel the problem is here
     System.out.println(search + "course is available");
     break;
     else
      System.out.println(search + "course is not available");
    }
   }
  }
 }

I expect the output to be我希望 output 是

<string> course is available

when my string matches a string in the array and当我的字符串与数组中的一个字符串匹配时

<string> course is not available

when my entered string doesn't match a string in the array当我输入的字符串与数组中的字符串不匹配时

But there is no output:(但是没有output:(

I have modified your code and commented on line where it need to be explained.我已经修改了您的代码并在需要解释的地方发表了评论。 check it carefully.仔细检查。

import java.util.Scanner;

class Course {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter no. of courses");
        int no_of_courses = sc.nextInt(); // number of strings
        String a[] = new String[no_of_courses]; // do not assume when you have proper data.
        if (no_of_courses <= 0)
            System.out.println("Invalid Range");
        else {
            System.out.println("Enter course names:");
            for (int i = 0; i < no_of_courses; i++) {
                a[i] = sc.next(); // accepting string inputs
            }
            System.out.println("Enter the course to be searched:");
            String search = sc.next(); // entering a string to search
            boolean flag = false;
            for (int i = 0; i < no_of_courses; i++) {
                if (a[i].equals(search)) // I feel the problem is here
                {
                    flag = true;//do not print here. just decide whether course is available or not
                    break;
                }
            }
            //at the end of for loop check your flag and print accordingly.
            if(flag) {
                System.out.println(search + "course is available");
            }else {
                 System.out.println(search + "course is not available");
            }
        }

    }
}
class Course {
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String a[] = new String[20] ;                //assuming max 20 strings
                System.out.println("Enter no. of courses");
        int no_of_courses = sc.nextInt();           // number of strings
        if(no_of_courses <= 0)
            System.out.println("Invalid Range");
            else
            {
                System.out.println("Enter course names:");
                for(int i=0 ; i < no_of_courses ; i++)
                {
                    a[i] = sc.next();                            //accepting string inputs
                }
                System.out.println("Enter the course to be searched:");
                String search = sc.next()   ;             //entering a string to search
                boolean found = false;
                        for(int i = 0 ; i < no_of_courses ; i++)
                        {
                            if(a[i].equalsIgnoreCase(search))                   //I feel the problem is here
                            {
                                **found = true;**
                                break;
                            }   

                            }
                        if(found) {
                            System.out.println(search+ "course is available"); 
                        }else {
                            System.out.println(search+ "course is not available");
                        }
                        }
            }
    }

I noticed a few things - Does your program run to the end?我注意到一些事情 - 你的程序是否运行到最后? When i copy/pasted into my ide i noticed a few missing semi-colons, and like Yhlas said, your last if/else statement syntax is incorrect.当我复制/粘贴到我的 ide 中时,我注意到缺少一些分号,就像 Yhlas 所说,你最后的 if/else 语句语法不正确。

And this doesn't have anything to do with whether or not your program will give you the right answer, but your last loop will print over and over again because it will check each element in a, and each time it loops and finds a mismatch it will print something out这与您的程序是否会给您正确的答案没有任何关系,但是您的最后一个循环会一遍又一遍地打印,因为它会检查 a 中的每个元素,并且每次循环并发现不匹配时它会打印出一些东西

This is really a good effort and you almost got it.这真的是一个很好的努力,你几乎得到了它。 So just a couple of things所以只有几件事

  1. Since you are inputting the number of courses, just use that value to initialise your array (it's just a good practice to get into to try not initialise things before you actually need them).由于您正在输入课程数量,因此只需使用该值来初始化您的数组(在实际需要之前尝试不初始化它们只是一个很好的做法)。
  2. If you are doing String comparisons and case sensitivity does not matter, rather use .equalsIgnoreCase(String)如果您正在进行String比较并且区分大小写无关紧要,请使用.equalsIgnoreCase(String)
  3. To solve your problem, you just needed a boolean variable to indicate whether or not you had found a match.为了解决您的问题,您只需要一个boolean变量来指示您是否找到了匹配项。 Initially this would be FALSE (no match found) and you would run through your array until a match is found.最初这将是FALSE (未找到匹配项),您将遍历您的数组,直到找到匹配项。 Once found this would be flagged TRUE and you'd break out your loop (which you correctly did).一旦发现这将被标记为TRUE并且你会break你的循环(你正确地做了)。
  4. Only once out your loop, you'd print out whether you found a match.只有在循环结束后,您才会打印出是否找到了匹配项。

Have a look:看一看:

public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter no. of courses");
  int no_of_courses = sc.nextInt();           // number of strings
  if (no_of_courses <= 0) {
    System.out.println("Invalid Range");
  } else {
    String a[] = new String[no_of_courses];
    System.out.println("Enter course names:");
    for (int i = 0; i < a.length; i++) {
      a[i] = sc.next();                            //accepting string inputs
    }
    System.out.println("Enter the course to be searched:");
    String search = sc.next();                //entering a string to search
    boolean courseFound = Boolean.FALSE;
    for(int i = 0; i < a.length; i++) {
      if (a[i].equalsIgnoreCase(search)) {
        courseFound = Boolean.TRUE;
        break;
      }
    }
    if(courseFound) {
      System.out.println(search + "course is available");
    } else {
      System.out.println(search + " course is not available");
    }
  }
}

Oh, just for interest (and when you start working with some more advanced constructs), you could always just use stream , which was introduced in Java 8. It'll trim down 12 lines to 5...哦,只是为了感兴趣(当你开始使用一些更高级的构造时),你总是可以只使用stream ,它是在 Java 8 中引入的。它将减少 12 行到 5...

if(Arrays.stream(a).anyMatch(i -> i.equalsIgnoreCase(search))) {
  System.out.println(search + " course is available");
} else {
  System.out.println(search + " course is not available");
}

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

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