英文:
Java Word-counting Program w/ User-Defined String Variable
问题
// 代码部分不翻译,只翻译注释和文本内容
To preface, I'm quite new to Java.
我是一个相对新手,对于Java还不太熟悉。
I have been trying to figure out what's going on with the following code -- I'm trying to find the number of spaces in the input (String s), but whenever the input is used as a variable it doesn't transfer over. However a set string value does work, i.e:
我一直在努力弄清楚下面的代码是怎么回事 - 我试图找出输入(字符串 s)中空格的数量,但无论何时使用输入作为变量,它都无法传递过来。然而,设置字符串值确实有效,例如:
String s = ("Happy days for all."); // Outputs "Spaces = 3"
字符串 s = ("Happy days for all."); // 输出 "Spaces = 3"
I've read up a bit about why this could be but I cannot find a definitive answer on how to solve it. Any suggestions?
我稍微阅读了一些关于可能原因的内容,但我无法找到明确的解决方法。有什么建议吗?
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Type a sentence > ");
String s = input.next();
long spaces = s.replaceAll("[^ ]", "").length();
System.out.print("Spaces = " + spaces);
}
}
Input
Happy days for all.
Output:
Spaces = 0
英文:
To preface, I'm quite new to Java.
I have been trying to figure out what's going on with the following code -- I'm trying to find the number of spaces in the input (String s), but whenever the input is used as a variable it doesn't transfer over. However a set string value does work, i.e:
String s = ("Happy days for all."); // Outputs "Spaces = 3"
I've read up a bit about why this could be but I cannot find a definitive answer on how to solve it. Any suggestions?
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Type a sentence > ");
String s = input.next();
long spaces = s.replaceAll("[^ ]", "").length();
System.out.print("Spaces = " + spaces);
}
}
Input
Happy days for all.
Output:
Spaces = 0
答案1
得分: 1
next()
会从扫描器中返回下一个完整的标记。如果您的输入是Happy days for all.
,第一次调用将返回Happy
,第二次调用将返回days
,第三次调用将返回for
,最后一次调用将返回all.
。
如果您希望一次性获取完整的句子,需要使用nextLine()
。
英文:
next()
will return the next complete token from this scanner.
If your input is Happy days for all.
it will return Happy
with the first call, days
with the second one, for
with the third and all.
with the last.
If you want to get the complete sentence at once you need to use nextLine()
.
答案2
得分: 0
问题出在这行代码:
String s = input.next();
input.next()
会返回输入直到分隔符的部分,在这种情况下是一个空格。
所以,s == "Happy"
将 input.next()
替换为 input.nextLine()
。
英文:
The problem is with the line:
String s = input.next();
input.next() will return the input up to a delimiter, and in this case, a space.
And so s == "Happy"
Replace input.next() with input.nextLine();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论