Java If Statements - Beginner [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
So slowly relearning java since I've forgotten all of it from college. I've always wondered if I do my loops in a weird way. I feel there has to be a better way to do loops. I'm pretty sure I always make them far longer than they should be. Anyways I'm following http://programmingbydoing.com/a/twenty-questions.html as it makes me have to google a lot and forces me to come to an understanding rather than just copying code. I'm on this 20 questions part (the link). Here is the code I wrote for it, which works. But is there a better way I could do this? Or what are the other possible ways I could have done this. Does && count as a nested if statement.
edit* Come to think of it. Any critiques at all are welcome. Not necessarily just my loops. If there is anything I am doing the long version of or anything that I'm doing a strange way please let me know.
*edit2. Whoops sorry. Did not know there was a codereview area. Would have posted there if I knew it existed.
import java.util.Scanner;
public class TwoQuestions
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
String answerOne, answerTwo;
System.out.println("Two questions game!");
System.out.println("Think of an object, and I'll try to guess it");
System.out.println("");
System.out.println("");
System.out.println("Question 1 - Is it an animal, vegetable, or random thing?");
answerOne = keyboard.next();
System.out.println("");
System.out.println("Question 2 - Is it bigger than a breadbox?");
answerTwo = keyboard.next();
if (answerOne.equals("animal") && answerTwo.equals("yes"))
{
System.out.println("You are thinking of a moose!");
}
else if (answerOne.equals("animal") && answerTwo.equals("no"))
{
System.out.println("You are thinking of a squirrel");
}
else if (answerOne.equals("mineral") && answerTwo.equals("yes"))
{
System.out.println("You are thinking of a Camaro");
}
else if (answerOne.equals("mineral") && answerTwo.equals("no"))
{
System.out.println("You are thinking of a paper clip");
}
else if (answerOne.equals("vegetable") && answerTwo.equals("yes"))
{
System.out.println("You are thinking of a watermelon");
}
else if (answerOne.equals("vegetable") && answerTwo.equals("no"))
{
System.out.println("You are thinking of a carrot");
}
else
{
System.out.println("Please make sure you are spelling correctly, no caps");
}
}
}

There is nothing wrong with your conditional statements, but those aren't loops.
Read this for information on loops: http://www.tutorialspoint.com/java/java_for_loop.htm
For your else case, you should ask the user for another input so they don't have to rerun the program if they make a typo.

Related

Someone have a look at my source code for a number guessing game that seems to keep failing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Hello please may someone run my code and assist me in debugging it. I'm having a lot of troubles trying to figure it out and i have not a lot of guidance when it comes to coding.
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
reccomendations to fix it. Thanks in advance
a brief of what i'm trying to do:
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
import javax.swing.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
/*
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
recomendations to fix it. Thanks in advance
*/
enterScreen();
if (enterScreen() == 0){
number();
userIn();
answer();
}
}
public static int enterScreen (){
String[] options = {"Ofcourse", "Not today"};
int front = JOptionPane.showOptionDialog(null,
"I'm thinking of a number between 0 and 100, can you guess what is is?",
"Welcome",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, options, "Yes" );
if(front == 0){
JOptionPane.showMessageDialog(null, "Goodluck then, you might need it. :D");
}
else {
JOptionPane.showMessageDialog(null, "okay i dont mind");
}
return front;
}
private static int number(){
double numD;
numD = (Math.random() * Math.random()) * 100;
int numI = (int) numD;
System.out.println(numD);
return numI;
}
private static int userIn(){
String userStr = JOptionPane.showInputDialog("What number do you think im thinking of?");
int user = Integer.parseInt(userStr);
return 0;
}
private static void answer(){
// here is the problem
if(userIn() == number()){
JOptionPane.showMessageDialog(null, "Well done! You must be a genius.");
}
else {
JOptionPane.showMessageDialog(null, "Shame, TRY AGAIN!");
userIn();
}
}
}
Your problem is this part:
enterScreen();
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You can leave out the first enterScreen(). Because you call it again in the if statement. If you look at the return type of the method: public static int, it returns and int. This makes it so that the outcome of the method is directly available in the if statement. The fist enterScreen is basicly useless, because you dont use the result.
You could do this:
int num = enterscreen();
if (num == 0) {
number();
userIn();
answer();
}
Which is basicly the same as:
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You call enterScreen() twice. Just call it once, and compare the value returned only once.
Also, StackOverflow typically is not for "Here's my code, fix it" kind of not questions.
https://stackoverflow.com/help/how-to-ask
You call enterScreen() and userIn() functions twice or more. Please Computer Science and coding. Hint: Computer's execute intructions from top to bottom.

Program That Teaches Someone Multiplication with Random Numbers

I am writing a program (game) that teaches someone multiplication. In this program, random pair of numbers are to be generated and inserted into the question: "What is x * y = z?" If the person answers correctly, then the system will print out "Very Good!" If the person does not answer the question correctly, then the system will print out, "No. Please try again." (Which, in return, the program will continue to ask the question until the person answers the question correctly.) As the person answers the question correctly, a new method will generate another question for the person to answer.
My code is breaking at the variable "answer" and the if statement "(guess != answer)."
Here is my code:
public class Exercise_535 {
public class Multiply{
SecureRandom randomNumbers = new SecureRandom();
int answer;
}
public void Quiz() {
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter your answer: ");
guess = input.nextInt();
while(guess != -1)
{
checkResponse(guess);
System.out.println("Enter your answer: ");
guess = input.nextInt();
}
}
public void createQuestion(){
SecureRandom randomNumbers = new SecureRandom();
int digit1 = randomNumbers.nextInt();
int digit2 = randomNumbers.nextInt();
answer = digit1 * digit2;
System.out.printf("How much is %d times %d\n", digit1, digit2);
}
public void checkResponse(){
if (guess != answer)
System.out.println("No. Please try again.");
else{
System.out.print("Very Good!");
createQuestion();
}
}
}
Is there anyone that is able to help, or at least point me in the correct direction?
Thanks.
It is important to understand the scope of variables. In java if you create a variable (where you say int guess or int answer) that variable only lives within whatever curly braces you put it in -> { }. So if you need that variable in another method, you need to pass it that variable in the parentheses. checkResponse() doesn't know what guess or answer are, because they aren't declared in that scope, and you don't pass them in at the start of the function (you could have checkResponse(int guess, int answer) and then pass those in when you call it, for example).
You have an inner class Multiply, is there a reason you created a class within a class? There are reasons to do that, but it doesn't seem like you have any reason to do that here.
Also I don't see a main function, which is the entry point to a Java program, and all other functions need to be called from there (so Main() could then call Quiz() in your case, which would then call your other two functions). Computers read programs one line at a time, and when you call a function/method (like Quiz()) it jumps to that part, and then returns when that function calls "return".
I know this is a lot of information, but it doesn't seem like you understand how Java programs flow. What are you using to study Java? If you are reading a book or doing a course, I recommend reviewing some of the earlier lessons, to understand the flow of the program better. It is difficult for people to answer your question because the way your code is set up doesn't have a logical flow (which is why it isn't working). Hope this helps a little.

Java Rock Paper Scissors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
looked at the other thread but I could not figure out why my program after i input my choice i.e. Rock The program either gives 2 answers or none at all. I know its similar to a previous thread but I don't understand why the reply varies. Any help would be appreciated.
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
System.out.println("Do you want to play Rock Paper Sissors?");
System.out.println("Yes or No?");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
if (input.equals("Yes")){
System.out.println("OK pick your weapon!");
String weapon = scan.nextLine();
Random rand = new Random();
rand.nextInt(3);
if (rand.nextInt(3) == 0){
//*0=Rock
if (weapon.equals("Rock")) {
System.out.println("I choose Rock, so did you... tie.");
}
else if (weapon.equals("Paper")){
System.out.println("I choose Rock and you choose Paper...You Win :( !");
}
else if (weapon.equals("Scissors")){
System.out.println("I choose Rock and you choose Paper...You Lose :) !");
}
}
if (rand.nextInt(3) == 1){
//*1=Paper
if (weapon.equals("Rock")) {
System.out.println("I choose Paper and you choose Rock...You Lose :) !");
}
else if (weapon.equals("Paper")){
System.out.println("I choose Paper, so did you...tie.");
}
else if (weapon.equals("Scissors")){
System.out.println("I choose Paper and you choose Scissors...You Win :( !");
}
}
if (rand.nextInt(3) == 2){
//*2=Scissors
if (weapon.equals("Rock")) {
System.out.println("I choose Scissors and you choose Rock...You Win :( !");
}
else if (weapon.equals("Paper")){
System.out.println("I choose Scissors and you choose Paper...You Lose:) !");
}
else if (weapon.equals("Scissors")){
System.out.println("I choose Scissors, so did you...tie.");
}
}
}
else {
System.out.println("OK have a nice day.");
}
}
}
Thanks for helping.
You have three if statements each generating their own random value, so it's possible for all three if statements to be executed. You should save off the result of rand.nextInt(3) once, and use that in the three consecutive if statements. I would change the three if statements in a row to a series of if/else if statements as well.
You seem to almost have the correct solution down where you call
rand.nextInt(3);
once before the initial if statements, just save that result to a variable.

What is the difference between if-else and if return and which is better? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
This is how I usually code:
public void foo (int x) {
if (x == 1) {
System.out.println("You entered one!");
} else if (x == 2) {
System.out.println("You entered two!");
} else if (x == 3){
................. and so on.
I realized that the following also produces the same results:
public void foo (int x) {
if (x == 1) {
System.out.println("You entered one!");
return;
}
if (x == 2) {
System.out.println("You entered two!");
return;
}
if (x == 3) {
...... and so on.
Which one would be better to use, even though they produce the same results and why?
I realize that there is a switch statement.
In this case, there will be almost no performance diffence. It comes down to readability.
I personally prefer a switch:
switch(x) {
case 1:
System.out.println("You entered one!");
break;
case 2:
System.out.println("You entered two!");
break;
case 3:
System.out.println("You entered three!");
break;
}
This is a "primarily opinion-based" question, but the main opinions are:
if/else (or, more importantly, fall-through to return) is better because it's bad to exit in the middle of a method. It's bad to exit in the middle because code should be structured with nested blocks ({}) and a logical progression of setup and the mirror takedown logic, and a return in the middle can result in bypassing takedown logic, often introducing subtle bugs.
if/return is better because exiting in the middle of a method is "cleaner". If the method is designed to fall-through to the return, one tends to get more and more deeply nested conditionals, as logic later in the method bypasses the "error" or "quick exit" cases that would have been handled by an embedded return. This can result in subtle bugs, and makes the code messy.
Obviously, both can't be right. Or can they?? In some cases the first argument would hold sway, in other cases the second. Anyone who claims that there's a hard-and-fast rule one way or the other (that isn't simply restating a language restriction) is just parroting some "expert" who has never really done real programming.

How does a state transition table work? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to try making a state machine, but I am fairly new to programming. I read something about a state transition table to switch between states if you input something. I do not quite understand how that works and how it translates to Java code. Can anyone please explain?
A state machine refers to a program that tracks states relative to user input.
I want to be able to input a string and then the progam gives a
message and the state changes. For example: "do work", the program
says:"going to work" and changes state. after a while it says"done
with working" and the state changes back. kind of like a very small
game
Using your example from the comments, we could do something like;
import java.util.Scanner;
enum GoingState {
TO_HOME,
TO_WORK,
TO_SHOP,
}
public class StateGame{
public static GoingState state = GoingState.TO_WORK;
public static void main(String args[]){
Scanner scanIn = new Scanner(System.in);
System.out.println("Where do you want to go?");
if(scanIn.nextLine().toLowerCase().contains("home")){
state = GoingState.TO_HOME;
System.out.println("Going home.");
}
else if(scanIn.nextLine().toLowerCase().contains("work")){
state = GoingState.TO_WORK;
System.out.println("Going to work.");
}
else if(scanIn.nextLine().toLowerCase().contains("shop")){
state = GoingState.TO_SHOP;
System.out.println("Going to the shop.");
}
else{
System.out.println("No valid input");
}
}
}
In the above example I am using enums to track state, but it could just as easily be an int or String, or an Object that tracks the state. This, of course, is an incredibly over simplified example.
State machines usually track which state transitions are possible (which I haven't done) using a state transition map (or table), which tell the program whether it can or should change from one type of state to another type of state.
A very simple example of a state map could be where there is only a linear progression to your states, ie in the example above only being able to go from home to work, work to the shops, and back again without being able to go directly from the shops to home or vice versa. Tracking this could be fairly simple, because you could put the states in an array and check if where the user wanted to go was one above or below the current state in the array.
I hope this helps.
It is not actually a machine. In the simplest case it is a program which simply has an integer variable called state. The program reads an integer input and depending upon the input and the current value of the state, it sets a new value of state.
if (state == 0 && input == 0) {
state = 1;
}
if (state == 1 && input == 1) {
state = 2;
}
if (state == 2 && input == 2) {
state = 3;
}
if (state == 3 && input == 4) {
state = 4;
}
if (state == 4 && input == 8) {
state = 5;
}
// many more such statements to cover all combinations of state and input values
Instead of such a long chain of if statements, you can use switch-case, or more sophisticatedly a class hierarchy or enums etc. But the concept should be clear based on the above.

Categories