[英]Java: Using the Do-while loop with Scanner Input as a String type: Making a program that calculates simple math and have it repeat if you type yes
This is the image of the code这是代码的图像
I am a little confused how to implement nextLine() in my code.我有点困惑如何在我的代码中实现 nextLine() 。 I am looking at my teachers code and I wanted to use a string instead of a char?
我正在查看我的教师代码,我想使用字符串而不是字符? Is there a way I can do that?
有没有办法我可以做到这一点?
Some of the lines in the code you linked to do not compile.您链接到的代码中的某些行无法编译。
For example, myObj.nextLine();
例如,
myObj.nextLine();
returns a String, and in java, String and char is not interchangible;返回一个字符串,并且在 java 中,字符串和字符不可互换; the line
isRepeat = someStringExpr;
行
isRepeat = someStringExpr;
does not compile.不编译。
Separately, don't mix nextLine
and nextAnythingElse
, it doesn't work the way you intend.另外,不要混合
nextLine
和nextAnythingElse
,它不会按照您想要的方式工作。 If you want to read entire lines, use .useDelimiter("\r?\n");
如果要阅读整行,请使用
.useDelimiter("\r?\n");
to change the scanner from 'read things separated by spaces' to 'read things separated by newlines'.将扫描仪从“读取由空格分隔的内容”更改为“读取由换行符分隔的内容”。 Then, you can just use
next()
to get an entire line, as a string.然后,您可以使用
next()
将整行作为字符串。
Once you've 'fixed' isRepeat
to be a String
, note that in java, strings are delimited by double quotes, so it's "Yes"
, not 'Yes', and finally, you use .equals()
to compare strings, not ==
which won't work: while (isRepeat.equals("Yes"));
一旦你'固定'
isRepeat
是一个String
,请注意在 java 中,字符串由双引号分隔,所以它是"Yes"
,而不是 'Yes',最后,你使用.equals()
来比较字符串,而不是==
这不起作用: while (isRepeat.equals("Yes"));
is what you're looking for.就是你要找的。
Note that in the original code, .next()
is used (not nextLine - you don't want nextLine).请注意,在原始代码中,使用了
.next()
(不是 nextLine - 您不需要 nextLine)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.