I am creating a program written in Java using Eclipse, and JDK 8. I have created a Scanner
using this code: Scanner input = new Scanner(System.in);
I then created a String
using the code String command = "no";
I planned on using this string to control a while
loop in my code, and a switch
within the while
loop. The loop starts with: while(command = "no")
and within the while
loop, I use the Scanner
I created earlier to get the user to define values for a String
and an int
, which when the code is executed, works. After that (but still within the while
loop, I put command = input.nextLine();
, followed by input.close();
on the line below, to set the value of the command
string, and close the Scanner
. But when I execute the code, it seems to skip that, and the switch
which I put directly after that (which should also be controlled by the command
string), and go on to code after the while
loop, even though command
is still set to "no", which should make the while
loop start again.
How do I make the code pause and wait for something to be entered at command = input.nextLine();
, and how do i make the switch
work like it should?
Here is the entire code:
`import java.util.Scanner;
class Human {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
String name = this.name;
return name;
}
public int getAge() {
int age = this.age;
return age;
}
}
public class Asdfghjkl {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String command = "no";
int age;
String name;
while(command == "no") {
System.out.println("Welcome to HUMAN CREATOR");
System.out.println("What is the human's name?");
name = input.nextLine();
System.out.println("Okay, its name is " + name + ".");
System.out.println("What about its age?");
age = input.nextInt();
System.out.println(name + " is " + age + " years old.");
System.out.println("Is this correct?");
command = input.nextLine();
switch (command) {
case ("yes"):
System.out.println("Great! Lets make the human!");
Human h1 = new Human();
h1.setAge(age);
h1.setName(name);
case ("no"):
System.out.println("Okay, lets start again.");
}
}
System.out.println("qwerty");
input.close();
}
}