This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
how to create a counter in a dr java program
this is the code that I am working on...
I would like to know how to reset the interactions window after every question is asked so that the window is clear for the next question to be shown to the user but I do not want the Score to be reset either so that I can display the score at the end. I am looking for the correct syntax and code to do this.
//Neel Patel
//Friday October 9th, 2009
/*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.");
int Score=0;
// 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"))
{
Score++;
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"))
{
Score++;
System.out.println("Correct!");
}
else
{
System.out.println("you got this questions wrong");
}
// question 3
System.out.println(" ");
System.out.println("Question 3. ");
System.out.println("Who is the only person in the history of the NBA to average a triple double for an entier season?");
System.out.println("Type in Answer here:");
String Question3= In.getString();
if (Question3.equalsIgnoreCase("Oscar Robertson"))
{
Score++;
System.out.println("Correct!");
}
else
{
System.out.println("you got this questions wrong");
}
// question 4
System.out.println(" ");
System.out.println("Question 4. ");
System.out.println("how many players was the first basketball game played with?");
System.out.println("Type in Answer here:");
String Question4= In.getString();
if (Question4.equalsIgnoreCase("9 on 9||18"))
{
Score++;
System.out.println("Correct!");
}
else
{
System.out.println("you got this questions wrong");
}
}
}
You need to use a loop of some sort. So you can start by creating arrays to store the questions and answers like this:
String[] questions = {" \nQuestion 1. \nHow tall is a basketball hoop? \nType in Answer here:",
" \nQuestion 2. \nWho invented basketball? \nType in Answer here: "};
String[] answers = {"10 Feet", "James Naismith"};
int score = 0;
String ans = "";
Then you can write a loop like this:
for(int i = 0;i < questions.length; i++){
System.out.println(questions[i]);
ans= In.getString();
if (ans.equalsIgnoreCase(answers[i]))
{
System.out.println("Correct!");
score++;
}
else
{
System.out.println("you got this questions wrong");
}
}
System.out.println(score);
And finally to clear the screen itself you cannot do that directly in Java but you may be able to run the cls command (assuming you run Windows) but that makes your code platform specific.
Runtime.getRuntime().exec("cls");
One brute-force (and, unlike cls, platform-independent) method for clearing the console would be to print a whole bunch of newliness to the console. This approach could have the added benefit of being seen as befitting an 11th grade CS project.
Related
I've just started learning programming for the first time and I am working through Java to start. I am doing a common coding exercise of programming a guessing game using loops and conditionals. My program is required to do the following:
Pick a random number between 1 and 100
Repeatedly prompt the user to guess the number
Report to the user that he or she is correct or that the guess is high
or low after each guess
Offer the user the option to quit mid-game
Count the number of guesses in a game and report the number upon a correct guess
Ask the user if they want to play again upon a successful game
I have been a little bit shaky with loop syntax so far and need some help with my program because there are a lot of issues I don't know how to fix. Would anyone be kind enough to lend me a hand? Please forgive the many probably obvious mistakes.
import java.util.Scanner;
import java.util.Random;
public class Guess
{
public static void main (String[] args)
{
final int MAX = 100;
int answer, guess = 0, count = 0;
String another = "y";
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
Scanner scan = new Scanner(System.in);
System.out.println("I'm thinking of a number between 1 and " + MAX
+ ". Guess what it is: ");
guess = scan.nextInt();
while (another.equalsIgnoreCase("y"))
{
while (guess != answer)
{
while (guess > MAX || guess < 1)
{
System.out.println("Invalid input. Please re-enter a number"
+ " between 1 and " + MAX + ":");
guess = scan.nextInt();
}
if (guess == answer)
{
count++;
System.out.println("You guessed correctly!");
}
else if (guess > answer)
{
count++;
System.out.println("You guessed too high. Guess again? Y/N:");
another = scan.nextLine();
}
else if (guess < answer)
{
count++;
System.out.println("You guessed too low. Guess again? Y/N:");
another = scan.nextLine();
}
}
}
System.out.println("It took you " + count + "guess(es) to win.");
System.out.println("Do you wish to play again? Y/N:?");
another = scan.nextLine();
count = 0;
answer = generator.nextInt(MAX) + 1;
}
}
One problem is that you're not letting the user quit midway through the game because even if the user guesses a number within the 1 to 100 range and doesn't get the right answer, his or her answer to Guess again: Y/N: won't be checked since the current loop it is in only compares guess to answer, never another. Therefore, you'll end up being in an infinite loop in this case because if the user guesses 57 when the answer is 50, you'll just continuously prompt the user if he or she wants to guess again.
My recommendation would be to remove the second while loop
while (guess != answer)
{
//other stuff
}
and place the code inside that loop into the outside while loop
while(another.equalsIgnoreCase("y")){
//other stuff
}
And if you want the user to be able to play again, I would recommend putting this snippet of code you had earlier inside the if statement where you check if the user has guessed correctly,
if (guess == answer)
{
count++;
System.out.println("You guessed correctly!");
System.out.println("It took you " + count + "guess(es) to win.");
System.out.println("Do you wish to play again? Y/N:?");
another = scan.nextLine();
count = 0;
answer = generator.nextInt(MAX) + 1;
}
This way, if the user wins the game, their choice to play again will be checked in the while loop. One last thing I would recommend is moving this line
guess = scan.nextInt();
inside the while loop that checks another so that if the user wants to play again, the game will prompt the user for a guess.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Want to have this code to search for dates between 1950-2050 and find out when Nothing happened, World cup, Olympic games or the info you write does not match any of the dates.
So the OL occurs when the number between 1950-2050 is divided by 4. And the WC occurs between even years of the OL like 2002(2004 WC)2006.
Then we have the dates no OL/WC occur between 1950-2050, that year nothing happened. And last if you put in like 700 it should just say the last else.
Scanner input = new Scanner(System.in);
System.out.println("Write year between 1950-2050: ");
int keyboard = input.nextInt();
int OL = (keyboard);
int WC = (keyboard);
int nothingspec = (keyboard);
int instru = (keyboard);
if(nothingspec) {
System.out.println("This year nothing special happened.");
}
else if(OL) {
System.out.println("Yes this year it the olympic games. ");
}
else if(WC) {
System.out.println("Yes this year it was a world cup in soccer.");
}
else(instru) {
System.out.println("Your instructions were wrong please try again.");
}
input.close();
As much as i understand it should be something like this
System.out.println("Write year between 1950-2050: ");
int keyboard = input.nextInt();
int OL = (keyboard);
int WC = (keyboard);
int nothingspec = (keyboard);
int instru = (keyboard);
boolean blOL = false;
boolean blWC = false;
//this occurs whenever the number can be divided by 4
if(keyboard>=1950&&keyboard<=2050){
if(OL%4==0) {
System.out.println("Yes this year it the olympic games. ");
blOL=true;
}
//This will happen every time the date can be divided to 2 so as you said 2002, 2004, 2006 and so on.
else if(WC%2==0) {
System.out.println("Yes this year it was a world cup in soccer.");
blWC = true;
}
//This is when nothing has happend.
else if(blOL==false && blWC==false) {
System.out.println("This year nothing special happened.");
}
else{
System.out.println("Your instructions were wrong please try again.");
}
}
else{
System.out.println("Your instructions were wrong please try again.");
}
input.close();
Please try this and tell me if this is what you needed.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
so, for my Java class I need to make a HiLo game. I figured the game out on my own, but I wanted to take it a step further, and after the user completes the game(guesses the right number) I want to ask them if they would like to play again.
The problem is, I can't seem to figure out exactly how. I have tried several things and at the moment I'm trying to get them to enter either yes or no to continue playing the game. If someone could help me figure out what I'm doing wrong and explain it to me, that would be great. Thanks!
Random generator = new Random();
Scanner scan = new Scanner(System.in);
int answer, guess;
answer = generator.nextInt(101);
System.out.println("Lets play a game. Guess the number(0-100): ");
guess = scan.nextInt();
while (guess != answer){
System.out.println("Wrong guess.");
if (guess > answer){
System.out.println("Your guess was higher than the answer. Guess again: ");
}
else{
System.out.println("Your guess was lower than the answer. Guess again: ");
}
guess = scan.nextInt();
}
if (guess == answer)
System.out.println("You got it! The number was " + answer);
//after initial game finishes, we ask if they want to play again.
System.out.print("Want to play again? ");
String again = scan.nextLine();
while (again != "no"){
System.out.println();
System.out.print("Great! lets play again.");
System.out.println("Take a guess(0-100 inclusive): ");
guess = scan.nextInt();
while (guess != answer){
System.out.println("Wrong guess.");
if (guess > answer){
System.out.println("Your guess was higher than the answer. Guess again: ");
}
else{
System.out.println("Your guess was lower than the answer. Guess again: ");
}
guess = scan.nextInt();
if (guess == answer)
System.out.println("Your got it! The number was " + answer);
System.out.println("Want to play again? (0 for no, 1 for yes): ");
again = scan.nextLine();
}
}
System.out.println("Thanks for playing!");
}
}
The != operator does not check if two strings contain the same characters. What you want to do is:
while (again.equals("yes")) {
...
}
You should also try to put your game code inside another loop, so at the end of the game (still inside the loop) you can ask the player if they want to play again. If yes, the loop has to be executed again, otherwise it stops.
This way the player can play an infinite number of games and you don't need to duplicate your game code. Example (to get an idea of what the structure could look like):
// start with "yes" in order to enter the game loop initially
String again = "yes";
while(again.equals("yes")) {
answer = generator.nextInt(101);
System.out.println("Lets play a game. Guess the number(0-100): ");
guess = scan.nextInt();
while (guess != answer){
System.out.println("Wrong guess.");
if (guess > answer){
System.out.println("Your guess was higher than the answer. Guess again: ");
}
else{
System.out.println("Your guess was lower than the answer. Guess again: ");
}
guess = scan.nextInt();
}
System.out.println("You got it! The number was " + answer);
// ask them if they want to play again. only "yes" will start another game
System.out.println("Do you want to play again (yes/no)?");
again = scan.nextLine();
}
I'm trying to do as the picture shows here:
This is my code:
import java.util.Scanner;
public class IcsProject
{
public static void main(String [] args)
{
Scanner keyboard= new Scanner (System.in);
int menuNum,ID,semNum,semCode,semCourses;
do{
System.out.println("Please Enter your Choice from the menu:");
System.out.println("1. Enter Student Sanscript");
System.out.println("2. Display Transcript Summary");
System.out.println("3. Read Student Franscript from a File");
System.out.println("4. Write Transcript Summary to a File");
System.out.println("5. Exit");
menuNum = keyboard.nextInt();
if (menuNum == 2 || menuNum == 3 || menuNum == 4)
System.out.println("Not working");
} while (menuNum > 1 && menuNum < 5);
//// Option 1: Enter student transcript
if (menuNum == 1)
System.out.println("Please enter your student's FIRST and LAST name:");
String stuName = keyboard.nextLine();
System.out.println("Please enter the ID number for " + stuName);
ID = keyboard.nextInt();
System.out.println("Please enter the number of semesters");
semNum = keyboard.nextInt();
for(int i=1 ; i < semNum ; i++)
{System.out.println("Please enter semester code for semester n# " + semNum);
semCode = keyboard.nextInt();
System.out.println("Please enter the number of courses taken in " + semCode );
semCourses = keyboard.nextInt();}
System.out.println("Enter course code, credit hours, and letter grade ")
///I stopped here
}
Do I have to use array starting from the semester code? show me an example please.
After entering all the values The program should show the Menu again so I can choose from it. How to do that?
I'm having a problem at the first question "entering the student first and last name"
The program just skip it and move to next question. Is there a mistake with my keyboard.nextLine();
I would use a list of objects which have all the fields you want to record.
For examples, just use google.
http://www.google.com/search?q=java+list+examples 27.9 million result
http://www.google.com/search?q=java+object+examples 18 million results.
http://www.google.com/search?q=java+array+examples 15 million results.
Regarding issue #2 - put the menu in a separate method. use a loop that it's condition is the menu or something similar to process according to the result from menu (this is abstract, I think you can figure it out from here):
while(doAnotherLoop)
{
switch(showMenu())
{
case 1:
...
case 2:
...
case 5: // Exit
doAnotherLoop = false;
}
}
Regarding issue #3. You read an int: menuNum = keyboard.nextInt(); but the line is not over, so the next nextLine (String stuName = keyboard.nextLine();) takes the rest of the line. use nextLine() and parse the integers instead.
/---------------------------------------
-----------------Quizzes.java------------
----------------------------------------/
import java.util.Scanner;
import java.text.NumberFormat;
public class Quizzes
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
NumberFormat per = NumberFormat.getPercentInstance();
//User to input keys for quiz
System.out.println("How many questions are in the quiz?");
int numques = scan.nextInt();
int[] keys = new int[numques];
for (int i=0; i<keys.length; i++)
{
System.out.print("Please enter the key for # " + (i+1)+ ": " );
keys[i] = scan.nextInt();
}
//User to input answer
System.out.println("\nGrading Quizzes");
System.out.println("--------------------");
int correct=0;
for (int i=0; i<keys.length; i++)
{
System.out.println("Please enter the answer for # " + (i+1)+ ": ");
int answer= scan.nextInt();
if (answer== keys [i])
{
System.out.print("Number "+(i+1)+" is correct.\n");
correct++;
}
else
{
System.out.print("Number "+(i+1)+" is incorrect.\n");
}
}
double cal=(double) correct/numques;
System.out.println("Total number of correct is "+correct);
System.out.println("The percent correct is " +per.format(cal));
System.out.println("Would you like to grade another quiz? (y/n)");
String user_input=scan.next();
while(user_input.equals("y"))
{ correct=0;
for (int i=0; i<keys.length; i++)
{
System.out.println("Please enter the answer for # " + (i+1)+ ": ");
int answer= scan.nextInt();
if (answer== keys [i])
{
System.out.print("Number "+(i+1)+" is correct.\n");
correct++;
}
else {
System.out.print("Number "+(i+1)+" is incorrect.\n"); }
}
cal=(double) correct/numques;
System.out.println("Total number of correct is "+correct);
System.out.println("The percent correct is " +per.format(cal));
}
System.out.println("Goodbye!");
}
}
How would I make the program go back to where the user would have to enter the answer using the while loop? No matter what I tried, right when it prints out, "Would you like to grade another quiz, and if the user type y, it would just end. Can anyone point out what I'm doing wrong
Edit 1: Well I got it to re-run again after the while loop but it keep asking me to input the answer for the question over and over and over again, it doesn't break out of the loop,it doesn't go back to the part where it asked if I wanted to grade another. This is the output
How many questions are in the quiz?
2
Please enter the key for # 1: 1
Please enter the key for # 2: 2
Grading Quizzes
Please enter the answer for # 1:
1
Number 1 is correct.
Please enter the answer for # 2:
3
Number 2 is incorrect.
Total number of correct is 1
The percent correct is 50%
Would you like to grade another quiz? (y/n)
y
Please enter the answer for # 1:
1
Number 1 is correct.
Please enter the answer for # 2:
2
Number 2 is correct.
Total number of correct is 2
The percent correct is 100%
Please enter the answer for # 1:
1
Number 1 is correct.
Please enter the answer for # 2:
2
Number 2 is correct.
Total number of correct is 2
The percent correct is 100%
Please enter the answer for # 1:
while(user_input.equals('y'))
should be
while(user_input.equals("y")) // see the double quotes here
Problem with your code is that character 'y' is autoboxed to instance of Character class which is the subclass of Object.
Class Object is the root of the class
hierarchy. Every class has Object as a
superclass. All objects, including
arrays, implement the methods of this
class
So is the candidate for public boolean equals(Object).
String implementation of boolean equals(Object) checks whether the instance is of type String. if it fails, it will simply return false.
If you want to compare with 'y', then try this.
while(user_input.equals(((Character)'y').toString()))
I will put the question a while loop and it will be something like
while (true) {
// ask the users the questions
// ask if he wants to continue... if no then break; else continue
}
Ok add a while(true) at the beginning of your program and add the appropriate brackets to encompass the whole method's contents. Then, delete the current while loop you have. Say after you get your input for user_input:
if (user_input.equals("y")) {
}
else {
break;
}
You will replace this while with your while(user_input.equals("y")) loop and the problem you pointed will go away but i think still your code will not work as you expected. I think your will need these more correction on your code
while loop should be this one while(user_input.equalsIgnoreCase("y"))
Put the opening and closing braces for while loop and in end while after finishing your for loop put these two statement to check again and again.
follow the following snap of code
while(user_input.equalsIgnoreCase("y"))
{
for (int i=0; i<keys.length; i++)
{
....
}
System.out.println("Would you like to grade another quiz? (y/n)");
user_input=scan.next();
}