gpt4 book ai didi

java - ''s cannot be resolved' ' 如何解决此错误?

转载 作者:行者123 更新时间:2023-12-01 17:07:31 24 4
gpt4 key购买 nike

我是一个初学者,对Java的理解很薄弱。我使用 Dr.Java 并收到此错误:

     "S cannot be resolved"

使用这个 Java 程序:

import java.util.Scanner;

public class HDtest5

{
public static int countWords(String str) {
String words[] = str.split(" ");
int count = words.length;
return count;
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = in.nextLine();
System.out.print("Your sentence has " + countWords(sentence) + " words.");
}

{
while (true) // have created infinite loop
{

if (s.equals("quit"))
// if enterd value is "quit" than it comes out of loop

{

String[] words = s.split(" "); // get the individual words
System.out.println("#words = " + words.length);
for (int i = 0; i < words.length; i++)
System.out.println(s + "word[" + i + words[i] + " nchars = " + words[i].length());

}
System.out.println(s); // to Print string
System.out.println(s.length()); // to print Entered string's length

}
}
}

什么原因导致此错误消息?我认为所有名为“s”的字符串应该可以毫无问题地一起工作。您能帮我找出问题所在吗?非常感谢您的帮助,非常感谢!

诗。更清楚地说,我的程序的目的是输出在文本窗口(扫描仪)中输入的文本的总字符数、每个单词的字符数和单词数。代码应该可以完美工作,除了这个字符串问题,它使得代码块不能一起工作。

最佳答案

我认为您想使用sentence 变量。并且您不会为 while 循环的每次迭代读取变量。

也许您想要更多类似的东西。

public class HDtest5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) { // have created infinite loop
System.out.print("Enter a sentence: ");
String sentence = in.nextLine();
System.out.print("Your sentence has " + countWords(sentence) + " words.");

if (sentence.equals("quit")) { // if enterd value is "quit" than it comes out of loop
break;
} else {
String[] words = sentence.split(" "); // get the individual words
System.out.println("#words = " + words.length);
for (int i = 0; i < words.length; i++)
System.out.println(sentence + "word[" + i + words[i] + " nchars = " + words[i].length());

}
System.out.println(sentence); // to Print string
System.out.println(sentence.length()); // to print Entered string's length

}
in.close();
}

private static int countWords(String str) {
String words[] = str.split(" ");
int count = words.length;
return count;
}
}

关于java - ''s cannot be resolved' ' 如何解决此错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24804011/

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