gpt4 book ai didi

java - 在这段代码中,我将如何以及在哪里为我的 Needle 和 haystacks 变量获取用户输入

转载 作者:行者123 更新时间:2023-12-01 13:12:21 25 4
gpt4 key购买 nike

我正在为项目执行此操作,方向如下:编写一个程序 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;
}
}

最佳答案

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

错误信息
用法:正确用法

所以代码看起来像这样

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();

关于java - 在这段代码中,我将如何以及在哪里为我的 Needle 和 haystacks 变量获取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22750056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com