This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am writing a program for a school assignment to create one string array of 3 riddles and another string array of 3 answers to each riddle. However when I input the correct answer to the riddle it keeps on showing the else part of the if-else statement. Here's my code:
import java.util.Scanner;
import java.util.Random;
public class riddleProgram {
public static void main (String[]args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int index;
int chosenRiddles = rand.nextInt(2);
//declares the riddles in the program as well as choosing a random riddle from the three presented
String[]riddle = new String[3];
riddle[0] = "What starts with a T, ends with a T, and has T in it?";
riddle[1] = "The day before two days after the day before tommorrow is Saturday. What day is it today?";
riddle[2] = "What grows up while growing down?";
//declares the answers to the riddles
String[]answer = new String[3];
answer[0] = ("teapot");
answer[1] = ("friday");
answer[2] = ("goose");
//asks user to enter guessed answer for the randomly presented riddle
for (index=0; index<3; index++); {
System.out.println(riddle[chosenRiddles]);
System.out.print("Enter your answer for the presented riddle (lowercase): ");
String inputtedAnswer = input.nextLine();
//if user inputs right answer, congratulates user
//if user inputs incorrect answer, tells user the correct answer
if (inputtedAnswer == answer[chosenRiddles]) {
System.out.println("Congratulations, you have gotten the right answer!"); }
else {
System.out.println("Sorry you had the wrong answer. The right answer is " + answer[chosenRiddles] + ".");}
}
}
}
never compare strings with ==
you should always use .equals( )
if (answer[chosenRiddles].equals(inputtedAnswer)) {
you should also try to have the constant value (the one that will always exist) on the left of these, to prevent possible NullPointerExceptions.
Related
So I'm currently a beginner programmer trying to slove some basic programming tasks. But I dont understand why My code is wrong. In eclipse everyting works. It's a coding problem from codewars.com
Introduction:
You ask a small girl,"How old are you?" She always says, "x years old", where x is a random number between 0 and 9.
Write a program that returns the girl's age (0-9) as an integer.
Assume the test input string is always a valid string. For example, the test input may be "1 year old" or "5 years old". The first character in the string is always a number.
package headfirstjava;
import java.util.Random;
public class do_something5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
{
int min =1;
int max =9;
int age1 = (int)Math.round(Math.random() * (max - min)+ min);
int age2 = (int)Math.round(Math.random() * (max - min + 1)+ min);
System.out.println("I'm "+ age1+ " Old");
}
}
}
I think you didn't understand the problem asked. Here the input of the program is the string "x years old" and you have to return "x" as an integer :
return Integer.parseInt(input.substr(0,1))
I am not sure what the problem is.
Try this if the problem is with generating random number:
// create random object
Random ran = new Random();
// Print next int value
// Returns number between 0-9
int nxt = ran.nextInt(10);
// Printing the random number
// between 0 and 9
System.out.println
("Random number between 0 and 9 is : " + nxt);
Also check out Random class in java! (Sry if this doesn't help)
If you simply want to extract a number from a specific string format (means you know where the number you are looking for is) use the Character.getNumericValue(string.charAt(0)) method.
Scanner scanner = new Scanner(System.in)
System.out.println("How old are you?");
String s= scanner.nextLine();
char c=s.charAt(0);
System.out.println("1st character is: "+ Character.getNumericValue(c) );
This is the simplest form that you can go. I suggest you go through w3schools.com for the basics.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
boolean a = true;
do {
Scanner input = new Scanner(System.in);
System.out.println("Press any on keyboard:");
String keys = input.nextLine();
System.out.println("You pressed:");
System.out.println(keys);
System.out.println("Your hash is:");
String B = "#B";
String hash = B+keys;
System.out.println(hash);
System.out.println("To end loop press f");
//End Loop
Scanner exit = new Scanner(System.in);
String end = exit.nextLine();
if (end=="f") {
a=false;
}
}
while(a);
}
}
I've been using python and I decided to start learning java since android studio requires it. I'm learning how to do loops again. I can't get this to work. I already looked this up I couldn't find it. How would I end this by pressing 'f'? My thought process was that once it was done going though the first lines of the do loop, it would go though the if statement changing the value of a ending the loop.
use break statement under if(){} body. also your == comparison will give false, use str1.equals(str2) for comparison.
Your problem is you are comparing strings with ==.You have to use equals to write correct if statement.
if (end.equals("f")){...}
You could use the below code to check
if (end.equals("f")) { // end == "f" , it check the reference.
a = false;
}
This question already has an answer here:
Simple Palindrome Detector [duplicate]
(1 answer)
Closed 4 years ago.
I've tried different approaches to do this, and when I do this..
import java.util.*;
public class Palindrome {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number");
int number = in .nextInt();
int first = number
int middle = 0;
int last = first;
boolean isPalindrome = last == first;
if (isPalindrome) {
System.out.print("This is a palindrome");
} else
System.out.print("This is not a palindrome");
}
}
it spits out "this is a palindrome". Mind you I can't use loops. Shouldn't this work?
It works when I do this...
import java.util.*;
public class Palindrome {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number");
int first = 1;
int middle = 0;
int last = 5;
boolean isPalindrome = last == first;
if (isPalindrome) {
System.out.print("This is a palindrome");
} else
System.out.print("This is not a palindrome");
}
}
It tells me if it's a palindrome or not...
So, it works on my end, but not the users end.
What am I missing
The problem is, you are assigning the value of the input to your variable first then you assigned the value of first to the variable last. You declared your boolean as isPalindrome = first==last (true) which will always be true in this scenario that's why you get "This is a palindrome". On your second block of code which you said "works" is because you declared first = 1 and last = 5, when you did isPalindrome = first==last (false) the value of the palindrome will always be false hence you get "This is not a palindrome" output.
I think what you need to do is rewrite your logic so you can elaborate the process you want to do. Feel free to ask a follow-up question.
In the first one, the user enters a number which is assigned to first, then you set last to be a reference to first. Since the truth value of isPalindrome depends on whether last == first, it will always be true, since you coded it that way. However, this doesn't actually prove that the number is a palindrome, because for example if the user enters the number 56, the number 56056 is not a palindrome (reverse is 65065).
In the second program, first is always 1 and last is always 5, so since they are never equivalent the condition last == first will always be false.
What are you attempting to achieve with the programs? Neither one tests the user input to be a palindrome. Try writing psuedocode first, in the comments if you like.
This question already has answers here:
How to use .nextInt() and hasNextInt() in a while loop
(3 answers)
Closed 6 years ago.
I have this code that I want to run to solve a problem which needs a three user inputs, and I used Scanner class for this:
public static void main(String[] args) {
int M = 0;
int A = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please, insert the normal dose in ml:");
M = input.nextInt();
System.out.println("Please, insert the set of experiments (3 integers per line, stop by 0 0 0):");
try {
while (input.hasNextInt()) {
System.out.print(input.hasNext());
int i = input.nextInt();
A += i;
System.out.println(A);
}
} catch (Exception x) {
System.out.print(x.getMessage());
}
System.out.println("Loop ended");
}
The strange thing is that input.hasNextInt() gets stuck or something after I Insert the three values, It seem that it keeps looping or something even though there are no inputs in the console, can some one provide some help for me?
That's because input.hasNextInt() waits until a integer value is available. It would return false if an alphanumeric value was informed.
You have to define another way to break while loop, maybe with a counter or, like your message says, checking whether 3 values are equal to 0.
Hello everyone I am new to the site and this is my first question from my Java programming class.
I have to create a program that asks a math question and tells the user if he is right or wrong, but the requirements also state that I need to create a method that generates a new question if the first question is correct, so when the computer asks what is 5 times 5 and the user inputs 25 the method should generate two new random numbers and ask the user for a result.
This is my code so far. I don't expect the answers as this is a school assignment but if anyone could give a direction it would be greatly appreciated it as this is my first java college course.
import java.security.SecureRandom; //program uses class SecureRandom
import java.util.Scanner; //program uses class Scanner
public class CAI
{
public static void main(String[] args)
{
System.out.println("Alex - Assignment 4\n");
//create Scanner for input from command window
Scanner input = new Scanner(System.in);
//randomNumbers object will produce secure random numbers
SecureRandom randomNumbers = new SecureRandom();
//generates two random numbers from 1 to 9 excluding 0
int random1 = 1+ randomNumbers.nextInt(9);
int random2 = 1+ randomNumbers.nextInt(9);
int answer; // declares answer from user
//calculates real result of first integer times second integer
int result = (random1 * random2);
//display generated integers
System.out.printf("What is %d times %d?\n",random1, random2);
do
{
answer = input.nextInt(); //keeps taking answer from user if wrong
if(answer == result) //if correct answer then print very good!
System.out.println("Very Good!");
else // if wrong answer then print no please try again
System.out.println("No. Please try again");
}
while (answer != result);
}
I think you have the basic way that your loop statements work mixed up. A do statement is going to execute its block of code once and wont inherently loop on its own. A while loop will repeat until you tell it to stop. So without telling you exactly how to structure your assignment ;) you should look at those two things. But your code does compile and does do one run through of what you want it to do. So this means that the problem you have is in the logic aspect of your code. This means that the computer doesn't understand based on the structure of your code when to execute the sections of your code.
So my advice is to try writing it out in plain English first (pseudocode) that way you can work out how the logic of your program should run and then translate it into code. Sometimes just saying "I want x to happen when y. But I only want this to happen if event z has happened." can help you understand logical how something has to work.
Best of luck
You could add a while loop before the generation of the random numbers that would repeat until answer== "exit". Something along those lines would work fine
You should put a break; statement in the bottom else loop and put everything from your public static void declaration in an "infinite" for loop. When the user inputs an incorrect answer, the program will go to the else loop and break. Otherwise, it will keep on repeating in the "infinite" for loop. Here is a sample code showing what you could do.
import java.security.SecureRandom; //program uses class SecureRandom
import java.util.Scanner; //program uses class Scanner
public class CAI
{
public static void main(String[] args)
{
boolean loopTest = false;
while (loopTest= true)
{
System.out.println("Alex - Assignment 4\n");
//create Scanner for input from command window
Scanner input = new Scanner(System.in);
//randomNumbers object will produce secure random numbers
SecureRandom randomNumbers = new SecureRandom();
//generates two random numbers from 1 to 9 excluding 0
int random1 = 1+ randomNumbers.nextInt(9);
int random2 = 1+ randomNumbers.nextInt(9);
int answer; // declares answer from the user
//calculates real result of first integer times second integer
int result = (random1 * random2);
//display generated integers
System.out.printf("What is %d times %d?\n",random1, random2);
do
{
answer = input.nextInt(); //keeps taking answer from user if wrong
if(answer == result) //if correct answer then print very good!
System.out.println("Very Good!");
else // if wrong answer then print no please try again
System.out.println("No. Please try again");
break;
}
while (answer != result);
}
}
}
*Note that the last } was not included in your program.