有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在这段代码中,我将如何以及在何处获取针和干草堆变量的用户输入

我这样做是为了项目,方向如下: 编写一个程序StringSearch,将两个字符串作为程序参数,打印 第一个字符串在第二个字符串中出现的次数,并打印 第一个字符串在第二个字符串中的第一次出现。 我还是一个新手,从教科书中借用了大量的代码,但还不知道如何将其集成到我编写的代码中。我知道我并不是在问一个具体的问题,我只是不明白如何让我的代码完成任务

 package StringSearch;

/**
 *
 * @author devan
 */
import java.util.Scanner;

public class SearchString {

  public static void main(String[] args) {
    int nargs = args.length;
    Scanner scanner = new Scanner(System.in);
 System.out.println("Please enter value for needle:");
      String needle;
      needle = scanner.nextLine();

System.out.println("Please enter value for haystack:");
      String haystack = scanner.nextLine();
    if(nargs < 2) {
System.out.println("Insufficient arguments provided");
System.out.println("Usage is: java SearchString needle haystack");
    } 
    else {
      System.out.println(searchString(args[0].toCharArray(),args[1].toCharArray()));
      System.out.println(getFrequency(args[0].toCharArray(),args[1].toCharArray()));
    }
  }
  public static int searchString(char[] needle, char[] haystack) {
    int nsize = needle.length;
    int hsize = haystack.length;

    for(int i = 0; i < hsize; i++) {
     int j;

     for(j = 0; j < nsize; j++) {
      if(i+j >= hsize) {
        break;
      }
      if(needle[j] != haystack[i+j]) {
        break; 
      }
     }
     if(j == nsize) {
       return i+1;
     }
   }
   return -1;
 }

 public static int getFrequency(char[] needle, char[] haystack) {
   int freq = 0;
   int nsize = needle.length;
   int hsize = haystack.length;
   for(int i = 0; i < hsize; i++) {
     int j;
     for(j = 0; j < nsize; j++) {
       if(i+j >= hsize) {
         break;
       }
       if(needle[j] != haystack[i+j]) {
         break;
       }
     }
     if(j == nsize) {
       freq++;
     }
   }
   if(freq == 0)
     return -1;
   else
     return freq;
 }
   }

共 (1) 个答案

  1. # 1 楼答案

    命令行参数提示的典型格式为

    错误消息
    用法:正确用法

    所以代码看起来像

    if(nargs < 2) {
        System.out.println("Insufficient arguments provided");
        System.out.println("Usage is: java SearchString needle haystack");
    } ...
    

    如果希望用户以交互方式输入数据,请使用扫描仪

    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter value for needle:");
    String needle = scanner.nextLine();
    
    System.out.println("Please enter value for haystack:");
    String haystack = scanner.nextLine();