Reputation: 341
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. But the valg.contains("j")) doesn't work. 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?
Upvotes: 1
Views: 755
Reputation: 181
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();
Upvotes: 0
Reputation: 347194
valg
is not a String
, it's a char
. A char
isn't an Object, it's a primitive, therefore it has no functionality.
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...
Try using something like...
if(valg == 'j')){
...instead
Upvotes: 1
Reputation: 24146
char is primitive numeric type, so you need to change you code to if(valg == 'j')
and it will work
Upvotes: 1