Why are the variable q2,q3 not being initialized, yet q1 is?
This is how the outcome should be similar to:
WELCOME TO MITCHELL'S TINY ADVENTURE!
You are in a creepy house! Would you like to go "upstairs" or into
the "kitchen"?
kitchen
There is a long countertop with dirty dishes everywhere. Off to one
side there is, as you'd expect, a refrigerator. You may open the
"refrigerator" or look in a "cabinet".
refrigerator
Inside the refrigerator you see food and stuff. It looks pretty
nasty. Would you like to eat some of the food? ("yes" or "no")
no
import java.util.Scanner;
public class App1 {
public static void main(String[] Args) {
Scanner keyboard = new Scanner(System.in);
String q1;
String q2;
String q3;
String a = "upstairs";
String b = "kitchen";
String c = "refrigerator";
String d = "cabinet";
String e = "yes";
String f = "no";
String g = "hallway";
String h = "bedroom";
String i = "bathroom";
System.out.println("Welcome To Mitchell's Tiny Adventure!");
System.out.println();
System.out.println("You are in a creepy house, would you like to go upstairs or into the kitchen?");
System.out.print(">");
q1 = keyboard.nextLine();
System.out.println();
if (q1.equals(a)) {
System.out.println("Upstairs you see a hallway. At the end of the hallway is the master");
System.out.println("\"bedroom\". There is also a \"bathroom\" off the hallway. Where would you like");
System.out.println("to go?");
System.out.print(">");
q2 = keyboard.nextLine();
System.out.println();
} else if (q1.equals(b)) {
System.out.println("There is a long countertop with dirty dishes everywhere. Off to one");
System.out.println("side there is, as you'd expect, a refrigerator. You may open the \"refrigerator\"");
System.out.println("or look in a \"cabinet\".");
System.out.print(">");
q2 = keyboard.nextLine();
System.out.println();
}
if (q2.equals(c)) {
System.out.println("Inside the refrigerator you see food and stuff. It looks pretty nasty.");
System.out.println("Would you like to eat some of the food? (\"yes\" or \"no\")");
System.out.print(">");
q3 = keyboard.nextLine();
System.out.println();
} else if (q2.equals(d)) {
System.out.println("Inside the cabinet is the boogie man, Are you scare? \"yes or no\"");
q3 = keyboard.nextLine();
System.out.println();
}if (q2.equals(g)){
System.out.println("You fall in the hallway can you make it? \"yes or no\"");
q3 = keyboard.nextLine();
System.out.println();
}else if (q2.equals(h)){
System.out.println("You run into the bedroom were there are monsters live are you afraid \"yes or no\"");
q3 = keyboard.nextLine();
System.out.println();
}else if(q2.equals(i)){
System.out.println("You run into the bathroom do you have to use it \"yes or no\"");
q3 = keyboard.nextLine();
System.out.println();
}
}
}
Every variable needs to be initialized, before it is accessed the very first time. This can happen automatically for constants and fields, but it needs to be done manually for local variables. So the developers has to decide which value should be the first value for a variable. Mostly it is either null (for object types) or 0/false (for primitive types).
So, now about your question:
Why are the variable q2,q3 not being initialized, yet q1 is?
About q1: the first time you try to read the reference "in" that variable is here:
if (q1.equals(a)) {
but before that, you're having this assignment:
q1 = keyboard.nextLine();
Here you initialize the variable q1 with the returned reference of the keyboard.nextLine() method call.
Now about q2:
(The problem with q2 and q3 are the same, so I just focus on q2).
You have this assignment in both the if and the else if block:
q2 = keyboard.nextLine();
So you try to assign it to another user input if q1 equals "upstairs" or "kitchen". But what will q2 be, if q1 is neither of them? Maybe it is "garden" or "downstairs", then q2 will remain uninitialized and the compiler can detect that, hence the error.
You must think about what to do if q1 is neither of them. You could ask the user again, until you get a valid answer. Or you can exit the program, if such situation is not allowed. It is up to you.
You could also initialize q2 and q3 with a certain default value to avoid that error and to avoid unexpected exceptions like a NullPointerException. It can be done like this:
String q2 = "";
String q3 = "";
In the first section, if all your tests for q1 were false, q2 would remain uninitialized, but you reference q2 in the 2nd section; similarly for q3.
If a code path exists that allows a local variable to be referenced without first being initialized, this compile error will occur.
Note that the compiler does not examine the logic aspects of the code, so for example this will fail to compile:
String a = "foo";
String s;
if (a.equals("foo")) {
s = "bar";
} else if (!a.equals("foo")) {
s = "baz";
}
System.out.println(s); // error
Even though we can see that logically s must be initialized, the compiler sees only boolean methods, which may result in s not being assigned.
You must initialize local variables before you use them. Try
String q1 = "";
String q2 = "";
String q3 = "";
well in line 42 :
if (q2.equals(c)) {
and in line 53 :
} else if (q2.equals(d)) {
you attempt to call the equals() method in an uninitialized variable (String q2) , try to initialize them first or check them for null values , it depends on how you want to handle each case
Related
I'm essentially making a small, simply "twenty questions" style program, using nested if-statements to try to guess what object the user is thinking based on clarifying questions.
I'm using the if statements to eventually give the user a "result" at the end, using a String variable called "result".
My ultimate confusion lies in which the compiler is stating that "variable response may have not been initialized". To which, based on the code, I would think it is after the if statements.
import java.util.Scanner;
public class TwoQuestions {
public static void main (String args[] ) {
Scanner kb = new Scanner(System.in);
String answer1, answer2, response;
System.out.println("\n[Two Questions]\nThink of an object, and I'll try to guess it.");
System.out.println("Is it an \"animal\", a \"vegetable\", or a \"mineral\"? (Type an answer exactly as quoted)");
answer1 = kb.nextLine();
System.out.println("Is it bigger than a breadbox? (yes/no)");
answer2 = kb.nextLine();
// example "response" based on user decisions
if (answer1 == "animal" || answer1 == "Animal") {
response = "yes";
if (answer2 == "yes" || answer2 == "Yes") {
response = "squirrel";
}
}
// more if statements...
// final machine "response" to user"
// TODO: Figure out why *this* "response" requires initialization before if statements.
System.out.println("My guess is that you are thinking of a " + response + ".\nI would ask you if I'm right, but I don't actually care.");
}
}
Like mad programmer said use String equals function to compare string.
Yes it will need to be initialize before compilation can take place. If Im not wrong you can initialize with Null, or " ", empty string.
I have a java program below:
package assignment;
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) {
System.out.println("Enter your age and I wil let you know if you are eligible to vote");
Scanner input = new Scanner(System.in);
int age;
age = input.nextInt();
String nationality;
nationality = "ghana";
nationality = "Ghana";
if (age>=18) {
System.out.println("Enter your nationality");
String nation = input.next();
if (nation.equals(nationality)){
System.out.println("You are eligible to vote");
}
else{
System.out.println("You are not eligible to vote");
}
}
}
Now I would like to assign the two String values, "Ghana" or "ghana" to the "nationality" variable so that when the user enters either "Ghana" or "ghana" the condition becomes true when the program gets to check the "nation" value to the "nationality" value and then executes the statement in the "if" block.
But with my above code, the program executes the "if" statement only when the user enters "Ghana". The program executes the "else" statement when the user enters "ghana".
Please kindly help me out.
Thank you.
Use equalsIgnoreCase()
if (nation.equalsIgnoreCase(nationality))
You can do this in several ways
solution 1:
if (nation.equalsIgnoreCase(nationality))
solution 2:
if (nation.toLowerCase("ghana")) // you can use enum instead of hard coded value
solution 3:
if (nation.toUpperCase("GHANA"))
That is happening because you assing the value ghana and the Ghana. This means that when the programm reaches the if statement the value of your variable is "Ghana". I would use the .toLowerCase method
if (nation.equals(nationality) || nation.equals(nationality.toLowerCase())
{
System.out.println("You are eligible to vote");
}
You can check the documentation here https://www.tutorialspoint.com/java/java_string_tolowercase.htm
let the user get 3 attempts only, after it he get his account suspenedI tried to ask the user to give a final password 3 times if he didn't it will give him that his account suspended and if it right gives him a grating message.
package EE;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
final String password= "Test";
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the password: ");
String pass = sc.next();
for (int i=0; i<2;) {
if (!pass.equals (password))
i++;
System.out.println("Try again! ");
String pass1 = sc.next();
if(pass.equals( password))
System.out.println("Welcome");
String pass2 = sc.next();
if (i == 2)
System.out.println("Sorry, your account is suspened");
}
}}
As Alea commented, you need to use braces { ... } around the blocks in your if statements:
for (int i=0; i<2;) {
if (!pass.equals (password))
i++;
System.out.println("Try again! ");
String pass1 = sc.next();
if(pass.equals( password))
System.out.println("Welcome");
String pass2 = sc.next();
if (i == 2)
System.out.println("Sorry, your account is suspened");
}
actually means this:
for (int i = 0; i < 2; ) {
if (!pass.equals(password)) {
i++;
}
System.out.println("Try again! ");
String pass1 = sc.next();
if (pass.equals(password)) {
System.out.println("Welcome");
}
String pass2 = sc.next();
if (i == 2) {
System.out.println("Sorry, your account is suspened");
}
}
Once we have indented the code correctly and added the braces at the places where the compiler expects them, we can start to see some of the problems.
For example:
When the password is correct, nothing will increment i. That means that i < 2 won't be true, and the loop will keep going around, and around.
You are calling next() twice for each loop iteration.
And so on.
Now I could just rewrite your code for you1. But you won't learn much from that. (You will learn best by writing the code for yourself, making mistakes and finding and correcting them ... yourself!)
Instead I am going to recommend to you to read about the Rubber Duck debugging technique. This may sound like a joke, but it is not. It is an important technique explained in a humorous way. And it is what I was taught as a way debug programs, back when I was 18 years old learning to program2.
The idea behind Rubber Duck debugging is to help you understand how a computer "thinks". Once you can do that, programming gets a lot easier. And this is why I strongly recommend that you do this yourself!
Anyway, once you can visualize what the code is doing wrong, then next step is to work out what it should be doing.
1 - It would be quicker for, for a start!
2 - Though we didn't call it by that name back then. We called it hand execution, and we did it with a pencil and paper. Generally on the back of old computer printouts. Yea, a long time ago. And in those days, we didn't have debuggers or IDEs. It was card punches and a 20 minute wait to get the printout back!
I'm currently doing a project in my computer science class and we are suppose to validate each character of a variable to see if it is legal or not. If it starts with a number it's illegal. If it starts with a special character it's legal but bad style. If it has a space it is again illegal. I'll post my current code now:
import java.util.Scanner;
public class classOfValidation {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String theVariable = null;
System.out.println("This program checks the validity of variables");
System.out.println("Please enter a variable (or press 'q' to quit");
theVariable = scan.nextLine();
do {
System.out.println("The variable is illegal");
theVariable = scan.nextLine();
} while (theVariable.startsWith("[0123456789]"));
do {
System.out.println("The variable is illegal");
theVariable = scan.nextLine();
} while (theVariable.contains("[ ]"));
do {
System.out.println("The variable is legal, but has bad style");
theVariable = scan.nextLine();
} while (theVariable.startsWith("[!##$%^&*]"));
}
}
If you couldn't already tell i'm new to programming and as confused as i possibly could be. If you have any advice or anything else you need me to explain then please leave a comment. Thanks everyone
You can use the single regex to validate your input via String#matches() method. But as for the example you've provided, you should use while loop, but not do-while, because in do while case, you are always running it's body once befor condition checked. So, you better do it like:
theVariable = scan.nextLine();
while (theVariable.startsWith("[0123456789]")) {
System.out.println("The variable is illegal");
theVariable = scan.nextLine();
}
while (theVariable.contains("[ ]")) {
System.out.println("The variable is illegal");
theVariable = scan.nextLine();
}
while (theVariable.startsWith("[!##$%^&*]")) {
System.out.println("The variable is legal, but has bad style");
theVariable = scan.nextLine();
}
The second, in your solution, you are using String.startsWith() method and passing into it some regex. Take a look at javadoc for this method. It's said there:
Tests if this string starts with the specified prefix.
That means, that this method doesn't support regexes, but simply checks whether the string starts with the passed string. So, your conditions seems, never to become true. I don't think, someone will input the [0123456789] or [!##$%^&*].
One more, any conditions are checked once, but after that user can modify the input and the previewsly passed condition will not be checked again. Seems, it's better to run into infinite loop with continue and break in some conditions, like:
//infinit loop, until user enter the `q` or the input is correct
while (true) {
//read the input
theVariable = scan.nextLine();
//chtck, whether is `quit` command entered
if ("q".equals(theVariable)) {
break;
}
//if string starts with digit or contains some whitespaces
//then print alert and let the user to
//modify the input in a new iteration
if (theVariable.matches("^\d+.*|.*\s+.*")) {
System.out.println("The variable is illegal");
continue;
}
//if string contains some special characters print alert
//and let the user to modify the input in a new iteration
if (theVariable.matches("^[!##$%^&*].*")) {
System.out.println("The variable is legal, but has bad style");
continue;
}
//if all the conditions checked, then break the loop
break;
}
I think the best way if you are use regex.
Here is an answer how to do that.
I am creating a simple lift programme in java. I want to to have four users that are allowed to use the lift i have already got it working for 1 but i cant figure out how to check multiple strings using the one if statement.
import java.util.Scanner;
public class Username
{
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
String name;
System.out.println("Enter your name");
name = kb.nextLine();
if (name.equals("barry "))
System.out.println("you are verified you may use the lift");
Scanner f = new Scanner(System.in);
int floor;
System.out.println("What floor do you want to go to ");
floor = f.nextInt();
if (floor >7)
System.out.println("Invalid entry");
else if (floor <= 7)
System.out.println("Entry valid");
}
}
Check out this related question:
Test if a string contains any of the strings from an array
Basically, put the names into an Array of strings, and compare the name entered with each name in the Array.
Use the OR symbol "||" or "|".
Such as if (name.equals("barry ") || name.equals("sara"))
For future reference the difference between the two is "||" short circuits. In this situtation, if barry is the name then the second statement for checking against sara will never be executed.
basically, you need an "Or" gate, this would work:
if(name.equals("name1")||name.equals("name2")||name.equals("name3"))
etc...