gpt4 book ai didi

java - 如何用空格分隔单词?

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

我在这段代码中试图做的是将五个单词输入中的每个单词分成它组成的五个单词。我设法使用 indexOf 和 substring 将第一个单词与输入的其余部分分开,但在分离其余单词时遇到问题。我只是想知道我能做些什么来解决这个问题。

import java.util.Scanner;

public class CryptographyLab {
public static void main (String [] args) {
fiveWords();
}

public static void fiveWords () {
Scanner input = new Scanner(System.in);

for (int i = 1; i <= 3; i++) {
if (i > 1) {
String clear = input.nextLine();
// I was having some problems with the input buffer not clearing, and I know this is a funky way to clear it but my skills are pretty limited wher I am right now
}

System.out.print("Enter five words: ");
String fW = input.nextLine();
System.out.println();
// What I'm trying to do here is separate a Scanner input into each word, by finding the index of the space.

int sF = fW.indexOf(" ");
String fS = fW.substring(0, sF);

System.out.println(fS);

int dF = fW.indexOf(" ");
String fD = fW.substring(sF, dF);

System.out.println(fD);

int gF = fW.indexOf(" ");
String fG = fW.substring(dF, gF);

//I stopped putting println commands here because it wasn't working.
int hF = fW.indexOf(" ");
String fH = fW.substring(gF, hF);

int jF = fW.indexOf(" ");
String fJ = fW.substring(hF, jF);

System.out.print("Enter five integers: ");
int fI = input.nextInt();
int f2 = input.nextInt();
int f3 = input.nextInt();
int f4 = input.nextInt();
int f5 = input.nextInt();
//this part is unimportant because I haven't worked out the rest yet

System.out.println();
}
}
}

最佳答案

Scanner class has a next() method从输入返回下一个“ token ”。在这种情况下,我认为连续调用 next() 五次应该返回 5 个单词。

正如 Alex Yan 在他的回答中指出的那样,您还可以在字符串上使用 split 方法来按某些分隔符(在本例中为空格)进行拆分。

关于java - 如何用空格分隔单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33897340/

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