[英]Breaking out of while-loop on user input
I have this code: 我有以下代码:
import java.util.*;
class Uke44{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
boolean lokke=true;
System.out.println("Vennligst oppgi navn: ");
String navn=input.nextLine();
while(lokke){
for(int i=0; i<100; i++){
System.out.println(navn);
}
System.out.println("Gi et nytt navn? j/n: ");
char valg = input.next().charAt(0);
if(valg.contains("j")){
lokke=true;
System.out.println("Skriv et nytt navn: ");
navn=input.nextLine();
}else{
lokke=false;
}
}
}
}
And what I want it to do is that when the user inputs: j at prompt, it should just reenact the lokke-variable to true, the loop runs again and the user is prompted to put in j or n for whether or not he/she wants to continue the program. 我想做的是,当用户输入:在提示符下输入j时,它应该只将lokke变量重新设置为true,循环再次运行,并提示用户输入j或n来确定他/她想继续该程序。 But the valg.contains("j")) doesn't work.
但是valg.contains(“ j”))不起作用。 Before I have always needed to save the possible choices in their own variables, and then use the "=="-operator to make the program check for equality.
在我始终需要将可能的选择保存在自己的变量中之前,然后使用“ ==-运算符”使程序检查是否相等。 But is there an easier way?
但是,有没有更简单的方法? Like, equalto or something?
喜欢,等于还是什么?
char是原始数字类型,因此您需要将代码更改为if(valg == 'j')
,它将起作用
valg
is not a String
, it's a char
. valg
不是String
,而是一个char
。 A char
isn't an Object, it's a primitive, therefore it has no functionality. char
不是对象,而是原始对象,因此没有功能。
A char
is also only a single character, ever, therefore it makes no sense to even provide contains
, either it is or it's not... char
也是一个字符,因此即使提供contains
也不是没有道理...
Try using something like... 尝试使用类似...
if(valg == 'j')){
...instead ...代替
import java.util.*;
class Uke44{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
boolean lokke=true;
System.out.println("Vennligst oppgi navn: ");
String navn=input.nextLine();
while(lokke)
{
for(int i=0; i<2; i++)
System.out.println(navn);
System.out.println("Gi et nytt navn? j/n: ");
char valg = input.next().charAt(0);
System.out.println(valg);
if(valg=='j')
{
lokke=true;
System.out.println("Skriv et nytt navn: ");
Scanner input1=new Scanner(System.in);
navn=input1.nextLine();
}
else
lokke=false;
}
}
}
this is the correct code . 这是正确的代码。
and basically the changed part : 基本上是更改的部分:
if(valg=='j')
{
lokke=true;
System.out.println("Skriv et nytt navn: ");
Scanner input1=new Scanner(System.in);
navn=input1.nextLine();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.