/*This is a quiz program that will ask the user 10 questions. the user will answer
* these questions and will be scored out of 10.*/
class Quiz {
public static void main(String args[]) {
// Instructions
System.out.println("instructions");
System.out.println(" ");
System.out
.println("1. You wll be asked ten questions through out the quiz.");
System.out
.println("2. The first question will appear, you will have to answer that question for the next question to appear.");
System.out
.println("3. When you answer the last question you will be told your score.");
System.out.println(" ");
System.out.println("welcome to the basketball quiz.");
// question 1
System.out.println(" ");
System.out.println("Question 1. ");
System.out.println("How tall is a basketball hoop? ");
System.out.println("Type in Answer here:");
String Question1 = In.getString();
if (Question1.equalsIgnoreCase("10 Feet")) {
System.out.println("Correct!");
} else {
System.out.println("you got this questions wrong");
}
// question 2
System.out.println(" ");
System.out.println("Question 2. ");
System.out.println("Who invented basketball? ");
System.out.println("Type in Answer here:");
String Question2 = In.getString();
if (Question2.equalsIgnoreCase("James Naismith ")) {
System.out.println("Correct!");
} else {
System.out.println("you got this questions wrong");
}
}
}
This is my program that I am writing. I want to make a counter that will keep score of every question that is answered right and then display it to the user after the questions are finished. I tried using this:
int score=0;
score=score+1;
It doesn't not work for the 2nd question, but works for the 3rd... it gives me an error.
Is there another way I can do this or am I doing something wrong?
It looks like you are on the right track. You need to declare a socre variable at the begiunning of the program.
int score = 0;
Then in each question where you print out "correct" you can increment the score like this:
score++;
At the end of the program after the last question you can print the score.
Maybe you should post the error you got when you tried it.
UPDATE:
The syntax is score++ NOT score=++. That is, take out the = sign.
What you did is correct. Heed the comment on your post; you need semi-colons at the end of your posted solution. Also, per the Java Language Specification, it's best to name your variable with all lower case characters:
int score = 0;
// question code
score += 1;
or
score = score + 1;
or
score++;
You need to place the variable declaration (int score = 0;) outside of any loops (your if/else loops). It would be best to place it at the first line of the main method.
Your problem is possible because you have a whitespace character after the name "James Naismith" in the comparison for their given answer. For it to be evaluated to true the user must answer with the exact string "James Naismith " instead of "James Naismith"
Edit: Nevermind, This should not cause an error but it is something to bring your attention to still because it could affect the result of the program.
Related
I am programming a monopoly-esque game with java on eclipse.
I am currently working on a method that allows players to loop through their own squares and choose which one to develop.
for (int loop2 = 0; loop2 < currentPlayer.getOwnedSquares().size(); loop2++) {
count++;
System.out.println("Would you like to develop this property " + count + ". "
+ currentPlayer.getOwnedSquares().get(loop2).getName() + " (y/n)");
propertyChoice = scanner.nextLine();
if (propertyChoice.equalsIgnoreCase("Y")) {
break;
}else if (propertyChoice.equalsIgnoreCase("N")) {
continue;
}
}
System.out.println("Please choose a development option");
System.out.println("1.Buy a start-up");
System.out.println("2.Buy a global corporation");
int option = scanner.nextInt();
I am unable to get the loop to present only one owned square at a time so the player can choose to select y/n for which one the want to develop. If the player was to pick "N" The loop would then present the next owned property in the array and the player would make another decision and so on..
If the player was to pick "Y" then the loop would break and move on the development options for the chosen owned square.
Any advice on how to realise this would be hugely appreciated.
You have to move the check for user input out of the loop, so the algorithm would look like this:
Print all the owned squares in a loop.
Ask user (outside the loop) which square he wants to develop. For example, a user can simply provide a positional number of a square which you can get by
currentPlayer.getOwnedSquares().get(Integer.valueOf(userInput));
Do whatever you need with selected square.
I just modified the code to test, and it works as you want. I think there is something else problematic which you haven't shared.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int count=0;
String propertyChoice;
Scanner scanner = new Scanner(System.in);
for (int loop2 = 0; loop2 < 5; loop2++) {
count++;
System.out.println("Would you like to develop this property " + count
+ " (y/n)");
propertyChoice = scanner.nextLine();
if (propertyChoice.equalsIgnoreCase("Y")) {
break;
}else if (propertyChoice.equalsIgnoreCase("N")) {
continue;
}
}
System.out.println("Please choose a development option");
System.out.println("1.Buy a start-up");
System.out.println("2.Buy a global corporation");
}
}
Output:
Would you like to develop this property 1 (y/n)
n
Would you like to develop this property 2 (y/n)
n
Would you like to develop this property 3 (y/n)
y
Please choose a development option
1.Buy a start-up
2.Buy a global corporation
Process finished with exit code 0
Try putting scanner.nextLine(); inmediately before propertyChoice = scanner.nextLine();
Edit: if this doesn't work, notice that the else has no brackets surrounding the second if block. I don't know if this will work as I do not see the classes you are refering to and cannot say there is the error. The code you've shown doesn't seem to have any other issue.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
I can't figure out why my code isn't working.
It appears to be breaking around the if not equal to yes or no area.
Here's my code:
public static void main(String[] args) {
// TODO code application logic here
Scanner user_input = new Scanner(System.in);
String name;
System.out.println("Hello, what is your name?");
name = user_input.next();
System.out.println("");
String name_answer;
System.out.println("Your name is " + name + ". Is this correct? (yes/no)");
name_answer = user_input.next();
System.out.println("");
if (!name_answer.equals("yes" + "no")) {
System.out.println("Answer not valid. Please input again.");
name_answer = user_input.next();
while (!name_answer.equals("yes" + "no")) {
System.out.println("Answer not valid. Please input again.");
name_answer = user_input.next(); } }
if (name_answer.equals("yes")) {
System.out.println("Thank you, " + name + ". Please proceed to the next question.");
} else if (name_answer.equals("no")) {
System.out.println("Please reinput your name correctly.");
while (name_answer.equals("no")) {
String name_again;
System.out.println("");
System.out.println("What is your correct name?");
name_again = user_input.next();
System.out.println("");
System.out.println("Your name is " + name_again + ". Is this correct? (yes/no)");
name_answer = user_input.next(); }
If i comment out the not-equals block of code (displayed below), the program works. However, with the block of code in, the program breaks.
if (!name_answer.equals("yes" + "no")) {
System.out.println("Answer not valid. Please input again.");
name_answer = user_input.next();
while (!name_answer.equals("yes" + "no")) {
System.out.println("Answer not valid. Please input again.");
name_answer = user_input.next(); } }
My goal is to have any answer not equal to "yes" or "no" be reinputted while a "yes" or "no" brings the program to another step. Thanks for the help.
The technical problem with your code is that you're using concatenation instead of logical operators. "yes" + "no" evaluates to "yesno", which will probably never match your input string.
More fundamentally, the problem is that you're trying to bundle two boolean evaluations into one. Logically, you want to proceed if the answer is not "yes" and the answer is not "no". In Java syntax:
if (!name_answer.equals("yes") && !name_answer.equals("no")) {
If you want to test multiple values at a time, you can use this shortcut:
if (!Arrays.asList("yes", "no", "foo", "bar").contains(name_answer)) {
I want to be able to choose an array index using input.
Object stud1 [][] = {
{1,2,3},
{"favorite food: ","pet name: ","bday: "}
}
System.out.println("how many inputs?");
If a user inputs 1, then "favorite food:" will prompt the user and if the user inputs 2, then
both "favorite food: " and "pet name: " will prompt the user and so on.
After the user completes the prompt input, this will display:
favorite food: chicken
pet: doge
birthday: december 25,1994
/////////////////////////////////////////my code/////////////////////////////////////////////
This question is similar to my other question, I just could not find the right answer for my question because I think it was confusing and not specific enough.
It's kind of working already but the problem is that when I input 1 then it still outputs everything. I only want it to output everything if the user inputs 3 which is the number of indexes in my array.
I am not pretty good with arrays yet especially multi array, I'm still experimenting.
String ctr1;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
if (num1 <= stud1.length) {
for (int x = 1; x<stud1.length;x++){
for (int i = 0; i<stud1[x].length;){
/*System.out.print("Enter Value #" + x++ +":");
ctr1 =Integer.parseInt(in.readLine());
i++;*/
System.out.println(stud1[x][i]);
ctr1 =in.readLine();
i++;
}
}
I'm sorry but I don't think this is a good example for multidimensional arrays... nothing is really being done with the first element here: {1,2,3}.
To answer the specific question of why all 3 elements are printing out when the user only inputs a "1", it is because that value is being read into the variable num1, but num1 is not used anywhere in the loop that prints the output. If you want the input to control how many values are printed, then num1 needs to be used in the for loop's test expression (the middle phrase in the parentheses). I think a good first step is to change your inner loop like so:
for (int i = 0; i<num1;i++){
System.out.println(stud1[1][i]);
ctr1 =in.readLine();
}
Also note that the i++ is moved inside the parentheses for the for loop. That's really where it belongs, if you're using for.
Hope this helps!
So I've been working on this Java program where the computer asks the user if he wants to know the square of a number. If the user's answer is either 'Y' or 'y', the computer asks the user the number he wants he wants to know the square of, and prints the square of the number. Then the computer asks the user if he wants to know the square of another number. If answer is 'Y' or 'y', the computer takes a number and prints the square. The user is again asked if he wants to know the square of another number. Like this it goes on.
I've also written code for cases where the user's answer is negative, or neither positive nor negative. By this, I meant cases where the user's answer is 'N' or 'n'. This program runs into a problem somewhere, and does not work from A to Z the way I want it to. See, when I run the code, the computer asks me if I want to know the square of a number, and I enter 'y'. I then get asked the number I want to know the square of. I enter the number and the computer prints out its square. Then I get asked if I want to know the square of another number. I enter 'y'. Then I am asked the number I want to know the square of and I enter a number. The computer prints the square of the number. Then the program asks if I want to know the square of another number and just ends, whereas it was supposed to take my answer. I've been working for almost 16 to 17 hours trying to find the bug, but I couldn't. Could you please maybe test the code and tell me where I went wrong? Thanks.
This is the code:
package looppracticea;
import java.util.Scanner;
public class LoopPracticeA {
public static void main(String[] args) {
Scanner geek = new Scanner(System.in);
Scanner geek2 = new Scanner(System.in);
long taken_number, taken_number2;
String answer, answer2, answer_not_recognized, if_answer_is_no;
answer_not_recognized = "You didn't enter any of the recognized answers.";
if_answer_is_no = "'Kay. Whatever.";
System.out.println("Do you want to know the square of a number? (Y/N)");
answer = geek.nextLine();
if (answer.equals("Y") || answer.equals("y")) {
System.out.println("The number you want to know the square of is:");
taken_number = geek.nextLong();
System.out.println("That number squared is " + taken_number * taken_number + ".");
System.out.println("Do you want to know the square of another number? (Y/N)");
answer2 = geek2.nextLine();
switch (answer2) {
case "N":
System.out.println(if_answer_is_no);
break;
case "n":
System.out.println(if_answer_is_no);
break;
case "Y":
while (answer2.equals("Y")) {
System.out.println("The number you want to know the square of is:");
taken_number2 = geek2.nextLong();
System.out.println("That number squared is " + taken_number2 * taken_number2 + ".");
System.out.println("Do you want to know the square of another number? (Y/N)");
answer2 = geek2.nextLine();
}
break;
case "y":
while (answer2.equals("y")) {
System.out.println("The number you want to know the square of is:");
taken_number2 = geek2.nextLong();
System.out.println("That number squared is " + taken_number2 * taken_number2 + ".");
System.out.println("Do you want to know the square of another number? (Y/N)");
answer2 = geek2.nextLine();
}
break;
default:
System.out.println(answer_not_recognized);
break;
}
} else if (answer.equals("N") || answer.equals("n")) {
System.out.println(if_answer_is_no);
} else {
System.out.println();
System.out.println(answer_not_recognized);
}
}
}
Here are the fixed contents of your main:
Scanner geek = new Scanner(System.in);
long taken_number;
String answer;
String answer_not_recognized = "You didn't enter any of the recognized answers.";
String if_answer_is_no = "'Kay. Whatever.";
boolean firstTime = true;
while(true)
{
if(firstTime)
System.out.println("Do you want to know the square of a number? (Y/N)");
else
System.out.println("Do you want to know the square of another number? (Y/N)");
answer = geek.nextLine();
if (answer.equalsIgnoreCase("y"))
{
System.out.println("The number you want to know the square of is:");
taken_number = geek.nextLong();
System.out.println("That number squared is " + taken_number * taken_number + ".");
answer = geek.nextLine();
}
else if (answer.equalsIgnoreCase("n")) {
System.out.println(if_answer_is_no);
break;
} else {
System.out.println();
System.out.println(answer_not_recognized);
break;
}
if(firstTime)
firstTime = false;
}
The problem is you have to read the line twice to get to the line you want.
The first nextLine will read the enter
Also I reduced the code by:
leaving only one Scanner since that is enough
used equalsIgnoreCase instead of 2 equals
used only one answer and taken_number variable since that was enough
put the variables declaration on separate lines because it is easier to maintain an a convention.
combined both input readings into one, with a boolean telling me if it is the first time so I know what message to output.
reading the nextLine() 2 times because the first one is the enter
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 9 years ago.
Improve this question
In my following piece of code I am looking to compare a piece of a text file.
However, for some reason, no matter what the user types in the value comes up
correct.
I'm trying to compare the value without worrying about its case or about any
leading or trailing white space.
// Display the question to the user
System.out.println("Question: " + myList.get(random1));
// Accept user input
System.out.print("Please type your answer: ");
// Store the user answer in a variable but lowercase
answer = scanner.nextLine().toLowerCase();
System.out.println();
// Display the officially correct answer from the arraylist
System.out.println("Answer: " + myList.get(random1 +1));
// if the user answer matches the official answer, tell them they're
// correct and award points
// else tell them they suck LOL
if(myList.get(random1 + 1).contains(answer) == false) {
System.out.println("Correct!");
totalScore = totalScore + awardedPoints;
System.out.println("You won " + awardedPoints);
}
else {
System.out.println("You suckkkkkkk");
}
// Display total accumulated points
System.out.println("Your total points are: " + totalScore);
// Wait for user to hit any key before displaying the next question
System.out.print("Hit Enter");
scanner.nextLine();
Try this.
// Display the officially correct answer from the arraylist
String correctAnswer = myList.get(random1 +1);
System.out.println("Answer: " + correctAnswer); // Instead use a variable
// if the user answer matches the official answer, tell them they're
// correct and award points
// else tell them they suck LOL
if(correctAnswer.equalIgnoreCase(answer)) { // efficient than contains() method
System.out.println("Correct!");
totalScore = totalScore + awardedPoints;
System.out.println("You won " + awardedPoints);
}
else {
System.out.println("You suckkkkkkk");
}