Completely new to programming, and I was doing a project and I am confused on how I can make it work. Please help me
boolean answer1 = true;
for (int i=0;i<q.questionbank.length;++i)
{ q.Question = input(q.questionbank[i]);
while(answer1 == true)
{
if (q.Question.equals(a.correctans) || (q.Question.equals(a.impossibleans) || (q.Question.equals(a.wrongans))))
{
score = printquiz(answer,score,q.Question);
answer1 = false;
}
else
{
print("Not a Valid Answer, please try again\n");
}
}
}
return score;
Over here, I have a class called questionbank and quiz. The correctans/impossibleans/wrongans are part of the quiz data type. whereas the q.question is part of questionbank. I have some question on an array in the questionbank data type. I want to use for loop to go through the questions and if the user input the correct answer, there score goes up. It works for the first question but doesnt for the second question. usually when they answer correctly, I have another method printquiz that has decision statements to tell the user if their answer is correct or wrong, and assign them points. but its not even going to that method after the first iteration of the loop. I am confused on what is going on. Please help me
This is how I would have set it up. Assume the answer to be false until you get one. Then set it to true to exit the loop.
for (int i = 0; i < q.questionbank.length; ++i) {
q.Question = input(q.questionbank[i]);
answer1 = false;
while (!answer1) {
if (q.Question.equals(a.correctans) || (q.Question.equals(a.impossibleans) || (q.Question.equals(a.wrongans)))) {
score = printquiz(answer, score, q.Question);
answer1 = true;
} else {
print("Not a Valid Answer, please try again\n");
}
}
}
The second time doesn't work, because you set answer1 to false and never set it back to true again. So the while loop is not being entered anymore (= doesn't evaluate to true anymore) after the answer1 = false line of code in the if statement has been reached the first time.
To fix this, try to put answer1 = true inside the for loop, before the while loop.
Related
I've made a piece of java code that collects user data iteratively and asks a y/n question to break or continue the loop. But the code seems to branch: carrying on with the loop but also the rest of the code in sequence at the same time.
for(i = 0; i < alphabetLength; i++){
...
continueQuery = JOptionPane.showInputDialog("Another activity? (y/n)");
if ("y".equals(continueQuery)) {
}
else if ("n".equals(continueQuery)){
//i = i + 30;
//break;
}
You're obviously not showing the whole picture here which leaves things up for speculation and assumption. That's a real poor way to ask a question, but never the less I'll give this a poke.
Using a Input Dialog is a strange option to use for simply asking the User if he or she wants to utilize yet another Activity. Have you considered what is to happen if the User simply closes the Input Dialog which forces it to return null. By merely closing the Input Dialog it should be considered as the same as entering "n" ...... or should it? What if the User enters anything other than "y" or "n" like maybe just a whitespace. What is to happen then? There's a lot of things that need to be taken into consideration here and....more (unnecessary) code.
I think what you are looking for is the continue keyword which in a for loop causes the loop to skip all loop code after the statement call and immediately jump to the next iteration of that loop:
for (int i = 0); i < alphabetLength; i++) {
..............................
..............................
String continueQuery = JOptionPane.showInputDialog("Another activity? (y/n)");
if ("y".equals(continueQuery)) {
continue;
}
else if ("n".equals(continueQuery) || continueQuery == null){
break;
}
..............................
..............................
}
Notice how I've also added a condition within the else if should the User simply close the Input Dialog window. Oh, and if you want the flow to break out of the for loop when "n" is supplied then simply un-comment the break statement.
Of course, if the call to the Input Dialog is the last code within your for loop then you wont need the continue statement, you wont need to check for "y" at all since the the next iteration is automatically going to happen anyways. You would just need:
if ("n".equals(continueQuery) || continueQuery == null){
break;
}
As I said earlier, using an Input Dialog is a strange option to use for this sort of prompt since the User is only required to enter either "y" or "n" for Yes or No. A better option would be to use a simple Confirm Dialog instead where as the User has the option to select either a Yes, No, and perhaps the Cancel button if you like, something like this:
for (int i = 0); i < alphabetLength; i++) {
..............................
..............................
int userOption = JOptionPane.showConfirmDialog(null, "Would you like another Activity?",
"Another Activity?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (userOption == JOptionPane.YES_OPTION) {
continue;
}
else if (userOption == JOptionPane.NO_OPTION) {
break;
}
..............................
..............................
}
I have a Java program that asks user questions and totals their scores. I am trying to display the correct total of answered questions at the end of the program. However, I have no idea how to, can some please help me!
Here is an example of how my code looks like l! But this is not my actual code this is from another source!
Import java.util.Scanner;
public class App
{
public static void main(String[] args) {
// The array of questions.
String questions[] = {
"Plants derive most of their dry mass from the air.",
"Aluminium is the most common metal in the Earth's crust.",
"Vitamin C has be shown to prevent colds.",
"We lose the most heat through our heads.",
"Dogs are unable to digest chocolate.",
"Apple pips contain cyanide.",
"Cholesterol is a nat
"When you're on a diet, you lose weight by oxidising fat to a gas and exhaling it.",
"Human beings are unable to sense when the oxygen level of the air is low.",
"Most of the Y chromosome is passed unchanged from father to son" };
// The array of answers. The entries correspond to the questions.
boolean answers[] = { true, true, false, false, false, true, false,
true, true, true };
// Display the opening text.
System.out.println("Answer each of the following questions with 't' (true) or 'f' (false)");
// We'll use this to get user input.
Scanner input = new Scanner(System.in);
// Add up the user's score here as we go along.
int score = 0;
// The is the index into the questions array and the answers array.
int questionNumber = 0;
// Create a blank line.
System.out.println();
// The do-while loop will keep running while questionNumber is less
// than the question array length.
do {
// Display the question
System.out.println(questions[questionNumber]);
// Display a little prompt to make it clearer that the user has to
// enter something.
System.out.print("> ");
// Get the user's answer.
String userAnswer = input.nextLine();
// Check that the user has entered t or f.
if (!userAnswer.equals("t") && !userAnswer.equals("f")) {
System.out.println("Please enter t for true or f for false.\n");
// Invalid input!
// Skip the rest of this loop iteration and ask the same question again.
continue;
}
// Check the answer.
if (userAnswer.equals("t") && answers[questionNumber] == true) {
// If the answer's t and the right answer is "true", the answer was correct.
score++;
System.out.println("correct\n");
} else if (userAnswer.equals("f") && answers[questionNumber] == false) {
// If the answer's f and the correct answer is "false", the answer was correct.
System.out.println("correct\n");
score++;
}
else {
// Wrong answer!
System.out.println("incorrect!\n");
}
// Now we can move to the next question when we go round the loop again.
questionNumber++;
} while (questionNumber < questions.length); // end of do-while.
// This isn't really necessary, but closing the Scanner prevents a warning icon in Eclipse.
input.close();
// Tell the user their score.
System.out.println("You scored: " + score);
// Rank the score! Only one of the alternatives below will execute.
// Java will check them in order from top to bottom.
if(score < 5) {
// Less than 5 -- not so good.
System.out.println("Hmmm, maybe you're the artistic type. Try the test again!");
}
else if(score < 8) {
// The score wasn't less than 5, but it IS less than 8.
System.out.println("Not bad! But have another go.");
}
else if(score <= 9) {
// The score wasn't less than 8, but it IS less than, or equal to, 9.
System.out.println("Pretty good! But no perfect. Try again!");
}
else {
// The score was more than 9 -- must be 10 because we've only got 10 questions.
System.out.println("You're a certified science genius!");
}
}
}
You can use a list and add the question nummer when the user has answered the question correctly.
Before your do-while-loop you have to add
ArrayList<Integer> correctQuestions = new ArrayList<Integer>();
Then in your do-while-loop you have to add when the answer is correct
correctQuestions.add(questionNumber);
At the end of you program (outside the do-while-loop) you can make the output like this:
System.out.println("You answered the following questions correctly");
for (int k : correctQuestions) {
System.out.println(questions[k]);
}
Simply declare a boolean array containing user answers in your class:
public boolean[] userAnswers = new boolean[questions.length]; //remove the access modifier if you want to declare the array inside main instead of the class
Now in your do-while loop, after parsing the user input, do this:
userAnswers[questionNumber] = userAnswer.equals("t");
Outside of your do-while loop (after you close the Scanner), do the following to print all the questions and the user's answer:
for (int i = 0; i < questions.length; i++) {
System.out.println("User answered \"" + userAnswers[i] + "\" on question " + (i + 1) + ": " + questions[i]);
}
I'm trying to make a very basic game where you guess a number between 1-1000 using a do loop. Everything works, except when I finally make the correct guess, I am still prompted to make another guess, and when I enter the same correct guess again, the program terminates like it's suppose to.
Why do I have to make that extra guess to finally get my program to work? Am I looping around an extra time? Also, if I make a correct guess (the compiler will say I am correct then still prompt me), then a wrong guess (the compiler will tell me I'm wrong), then the correct guess again, the program will only terminate after I make the correct guess a second time.
The second do loop at the bottom is what I put in my main method. Everything above is in a method I wrote called play.
public static boolean play()
{
boolean c;
int n = 0;
do {
String input = JOptionPane.showInputDialog("Enter a number between 1-1000");
n = Integer.parseInt(input);
if (n == guess)
{
System.out.println("Correct");
c = true;
}
else if (n < guess)
{
System.out.println("Not Right");
c = false;
}
else
{
System.out.println("Not Right");
c = false;
}
guess++;
} while (c == false);
return c;
}
In main method:
do {
game1.play();
} while (game1.play() != true);
This loop runs the play method twice in each iteration of the loop :
do {
game1.play(); // first call
} while (game1.play()!=true); // second call
You are not testing the value returned by the first call, so even if it returns true, you would still call game1.play() again, which will display "Enter a number between 1-1000" again.
Replace it with:
boolean done = false;
do {
done = game1.play();
} while (!done);
This would only call play() one time in each iteration of the loop.
That said, I'm not sure why you need the outer loop.
You can just replace in with one call to game1.play(), since game1.play() will loop until the correct number is entered.
Currently this is my code, and I need to display " Please enter a valid choice" when the user don't pick A,B,C,D,E or F as their choices. The problem is if I put the statement " Please enter a valid...." on the "else" conditional, Java would ask me to initialized the variable ActivityFactor as there will not be one if the user don't select the correct choice. Anyone know how I can fix this? Or any idea how I should code a program to do such?
if((inGender.equalsIgnoreCase("M") ||(inGender.equalsIgnoreCase ("F"))) && inActivity.equalsIgnoreCase("A"))
ActivityFactor = 1.0;
else if ((inGender.equalsIgnoreCase("M") ||(inGender.equalsIgnoreCase ("F"))) && inActivity.equalsIgnoreCase("B"))
ActivityFactor = 1.3;
else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("C"))
ActivityFactor = 1.6;
else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("C"))
ActivityFactor = 1.5;
else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("D"))
ActivityFactor = 1.7;
else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("D"))
ActivityFactor = 1.6;
else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("E"))
ActivityFactor = 2.1;
else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("E"))
ActivityFactor = 1.9;
else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("F"))
ActivityFactor = 2.4;
else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("F"))
ActivityFactor = 2.2;
else
{
ActivityFactor = -1;
}
//After
if(ActivityFactor != -1){
tdee = (nBMR * ActivityFactor);
System.out.println(tdee);}
else
{ System.out.println("Please enter a valid choice");
}
If non of the conditions in the if statements is true, then you don't assign anything to ActivityFactor, and it is not initialized when used in the line double TDEE = (nBMR * ActivityFactor);.
Either initialize it before the code you've shown here, give it a default value in the last case, or loop until you get a valid value.
initialise ActivityFactor to an usual value before your conditional.
For example you may do this:
// knowing that it can never be -1
// so if that value remains, you know that user entered wrong letter
ActivityFactor = -1
// then the conditional begins
if((inGender.equalsIgnoreCase("M") ||(inGender.equalsIgnoreCase ("F"))) && inActivity.equalsIgnoreCase("A"))
...
// after conditional...
if(activityFactor != -1){
double TDEE = (nBMR * ActivityFactor);
}
By the way, I suggest you use 'activityFactor' instead of ActivityFactor.
Either initialize your variable before the loop, or place the whole loop inside a function and then do something like:
double TDEE = (nBMR * getActivityFactor());
Also, have a look at this : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
happy coding! ;)
You should do two things:
Enclose the logic in method
Throw an exception if argument do not match the method logic.
You can solve this problem throwing an exception that you will catch.
private double getTDEE (String inGender, String inActivity) {
//logic
else {
throw new IllegalArgumentException("Please enter a valid choice");
}
return (nBMR * ActivityFactor);
}
Exception tutorial
As you're already aware, the problem with your code is that execution continues regardless of whether the user has entered valid input. Due to this, much refactoring is due - I would also attempt to make the conditional statements a little bit prettier; but that's personal preference.
Possible solutions:
a) Use a loop - Then break out of the loop when the user has entered satisfactory input..
while( true ){
/* get input from the user */
/* run through validation checks...
and -break- out of the loop when they're satisfied */
}
/* do calculations here */
b) Use a function to abstract all this logic away.. (as Psyclops suggests)
Personally, I would use a combination of these approaches - have all of this logic extracted away in to a function which returns false when no valid input is entered, and then use a construct like while(! yourFunction() ) to simply loop through it until it's completed. You could using passing by reference to avoid having to use the return type for anything other than a boolean value.
I wouldnt initialise the variable before the loop! This just means the programme will continue to execute; however it wont have any appropriate data in there - which is potentially worse than the application just crashing.
I haven't exactly gifted you the answer in code - but hopefully it's a starting point to allow you to think about how to conceptually compose/design such a solution. That's generally the hardest part.. ;) Good luck.
I just got a task asking me to do repeated addition from 1 to 21, as follows :
1,4,6,9,11,14,16,19,21
and get the total.
I tried this code but it returned to be a +2 addition, and it even bypass the prerequisite of bil<=21
public class test
{
public static void main(String[]args)
{
int bil=1;
long total=0;
boolean mult = true;
for(bil=1; bil<=21;bil++)
{
if(mult=true)
{
bil+=1;
mult=false;
}
else if(mult=false)
{
bil+=2;
mult=true;
}
System.out.println(bil);
total=total+bil;
}
System.out.println("----+");
System.out.println(total);
}
}
(if it's TL;DR)
Basically the request is 1+4+6+9+11+14+16+19+21=?
I can't seem to get these code to work, please help me?
EDIT : Thanks guys I got it now :D
You need boolean mult = false; so that the first time the loop runs, bil is incremented by 3 and not 2.
First, you are not comparing your boolean with ==. Therefore, every time the for() loop executes, the first block will be the one that enters since mult = true will always store true in mult... and then qualify that if() block to run.
If this assignment wasn't intentional, then you need to change it to == and also put some logic in your loop to toggle mult appropriately.
Basically when it runs through the first loop it only adds one because of the state of the boolean but also there should be an == operator to check instead of just an =
Try this:
for (bil = 1; bil < 21; bil++) {
if (bil % 2 == 0) { // If bil is divisible by 2, then add 2
bil += 2;
continue;
}
bil += 3;
}