Let users input create object - java

I'm writing this program where the user takes a math test. The problem Im now facing and have been trying to fix is how to display the final score at the end of the test.
I have a counter and the score increments for every correct answer, but how do I (at the end) display the final/total score? Any help is appreciated.
This is one of three classes btw.
import java.util.Scanner;
public class Questions {
Scanner scan = new Scanner(System.in);
int answer = 0;
int point = 0;
String correct = "Correct";
public void pointers(){
point++;
System.out.println(point + " point added to total score");
}
public void totalPoints(){
pointers();
}
public void showQuestions(){
System.out.println("\n--------------\nQuestion #1: 1+1 = ? ");
answer = scan.nextInt();
if(answer == 2){
System.out.println(correct);
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #2: 340-23 = ? ");
answer = scan.nextInt();
if(answer == 317){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #3: 900/3 = ? ");
answer = scan.nextInt();
if(answer == 300){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #4: 23*2 = ? ");
answer = scan.nextInt();
if(answer == 46){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
System.out.println("\nQuestion #5: -4+6 = ? ");
answer = scan.nextInt();
if(answer == 2){
System.out.println("Correct!");
pointers();
}else{
System.out.println("Wrong!");
}
}
}

The problem is that you're trying to get the input first and then you're asking for the age. When you type keyboard.nextInt() it is expecting an input immediately. So the problem is here:
*int age = keyboard.nextInt();
* System.out.println("Age: " + age);
*age = keyboard.nextInt();
My suggestion is to just remove the first keyboard.nextInt():
Example:
System.out.println("\nName: " + name);
name = keyboard.nextLine();
System.out.println("Age: " + age);
final int age = keyboard.nextInt();
and that's about it. Just be careful where you place your method calls, e.g. they should be after your println()'s.

No idea what you try to achieve, but
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final Scanner keyboard = new Scanner(System.in);
System.out.println("Hello, it is time to take a math test.\nFirst we need you to enter some information about yourself.");
System.out.print("\nEnter name: ");
final String name = keyboard.nextLine();
System.out.print("Enter Age: ");
final int age = keyboard.nextInt();
keyboard.close();
System.out.println("Your personal information: " + name + " of " + age + " years old.");
}
}
output:
C:\Temp\123431>java -classpath .;Main.class Main
Hello, it is time to take a math test.
First we need you to enter some information about yourself.
Enter name: ttt
Enter Age: 321
Your personal information: ttt of 321 years old.
C:\Temp\123431>java -classpath .;Main.class Main

Related

How to make 'end game' method in java

so i made a game, in which user needs to guess the random number or letter. I want to make it so that when the user writes 'end game' during the game (when he guesses the number), he is being redirected to the menu (using the main(args); method). In fact, String value cannot be writen in int input. So when i write 'end game' during the game cycle, it just crashes. What should i do?
Heres code of my game:
import java.util.Scanner;
public class TwoGames {
public static void main(String[] args) { // main menu
Scanner scan = new Scanner(System.in);
System.out.println("Choose the game\n Type 'letter' or 'number' to choose the game");
String UserAnswer = "";
UserAnswer = scan.next();
if (UserAnswer.equalsIgnoreCase("number")) {
number(args);
}else if(UserAnswer.equalsIgnoreCase("letter")){
letter(args);
}
scan.close();
}
public static void letter (String[] args) {
Scanner scan = new Scanner(System.in);
String playAgain = "";
String ReTurn = "";
String Stop = "";
int numberOfTries = 0;
do {
System.out.println("Guess the Letter");
char randomLetter = (char) (Math.random() * 26 + 65);
char enteredLetter = 0;
while(true){
enteredLetter = Character.toUpperCase(scan.next().charAt(0));
numberOfTries = numberOfTries + 1;
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
break;
}
else if(enteredLetter>randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too high");
}
else if(enteredLetter<randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too low");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye! \n Type 'return' to return to main menu");
ReTurn = scan.next();
if (ReTurn.equalsIgnoreCase("return"))
main(args);
scan.close();
}
public static void number(String[] args) { //heres the number guessing game
Scanner scan = new Scanner(System.in);
String playAgain = "";
String ReTurn = "";
String Stop = "";//variable to stop game
do {
int theNumber = (int)(Math.random() * 100 + 1);
int numberOfTries = 0;
do {
int guess = 0;
while (guess != theNumber) {
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt();
numberOfTries = numberOfTries + 1;
if (guess < theNumber)
System.out.println(guess + " is too low. Try again.");
else if (guess > theNumber)
System.out.println(guess + " is too high. Try again.");
else {
System.out.println(guess + " is correct. You win!");
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
}
}
} while (Stop.equalsIgnoreCase("end game"));
main(args);// this sends user to main menu
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye! \n Type 'return' to return to main menu");
ReTurn = scan.next();
if (ReTurn.equalsIgnoreCase("return"))
main(args);
scan.close();
}
}
I am novice programmer, so yeah, thats might be a dumb question, because im learning. Anyway, any help and explanation would be useful.
To solve this problem, you should input a string, check if it equals to "End game" message and if not continue your code.
For example, replace this line:
guess = scan.nextInt();
In this code:
String input = scan.next();
if(input.equals("End game")){
main(args);
return;
}
guess = Integer.parseInt(input);
That code get a String input called input, check if he equals to "End game" and if not continue your guess loop.

variable doesn't increase when code is executed

Tester is called and executed if the player inputs a certain name.
Variable testerWrong doesnt add one when testerWrong++ is executed
private void Tester(){
int testerTotal;
int testerScore;
int testerWrong;
testerTotal = 0;
testerScore = 0;
testerWrong = 0;
System.out.println("");
System.out.println("Hello tester, you're the designated tester. Would you like to take the quiz? Y/N");
Scanner yesno = new Scanner(System.in);
String YesNo = yesno.next();
if(YesNo.equals("Y") || YesNo.equals("y")){ //This type of code will appear very often
System.out.println("Okay, let's being!"); //if the user input (YesNo) is Y or y then...
}else{
if(YesNo.equals("N") || YesNo.equals("n")){
System.out.println("Okay, maybe some other time");
}else{ //else...
System.out.println("Sorry, i do not recognise what you entered. Please restart the program.");
}
}
System.out.println("");
QUIZ enter = new QUIZ();
enter.e2c();
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Question #1");
System.out.println("");
System.out.println("The answer is A");
System.out.println("");
System.out.println(" - A. ");
System.out.println(" - B. ");
System.out.println(" - C. ");
System.out.println(" - D. ");
Scanner testerQ1 = new Scanner(System.in);
String TesterQ1 = testerQ1.next();
if(TesterQ1.equals("A") || TesterQ1.equals("a")){
testerScore++;
System.out.println("Correct! You have answered " + testerScore + " correct and " + testerWrong + " incorrect!");
System.out.println("");
System.out.println("Next Question.");
System.out.println("");
}else{
testerWrong++;
System.out.println("Incorrect! You have answered " + testerScore + " correct and " + testerWrong + " incorrect!");
System.out.println("");
}
Is there a way to make the variable execute without having to add a system output before it?
Thanks
This is not a minimal (way too many print statements) or even complete example (the QUIZ class is not included).
Narrowing your code down to a minimum example:
import java.util.Scanner;
public class Tester {
public static void main(String args[]) {
int testerScore = 0;
int testerWrong = 0;
System.out.println("The answer is A");
Scanner scanner = new Scanner(System.in);
String answer = scanner.next();
if (answer.equals("A") || answer.equals("a")) {
testerScore++;
System.out.print("Correct!");
}
else {
testerWrong++;
System.out.println("Incorrect! ");
}
System.out.println(" You hve answered " + testerScore +
" correct and " + testerWrong + " incorrect!");
}
}
This works for me. Compare your code against this and see what you are doing differently.
If you cannot find the problem that way, run your code in a debugger. Step through the program to see what it does when.
You may also want to follow Java naming conventions (variables start with lower case letters, classes start with upper case letters but aren't all upper case), to make it easier for others to read your code.

How to call a statement over and over again in Java

import java.util.*;
public class TestProject
{
public static void theMath()
{
double add = 1;
double subtract = 2;
double multiply = 3;
double divide = 4;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Pick first number
System.out.println("Please enter a number: ");
int intOne = input.nextInt();
// Pick second number
System.out.println("Please enter another number: ");
int intTwo = input.nextInt();
//User chooses operator
System.out.println("Now please choose an operator (1 for add, 2 for subtract, 3 for mulitply, 4 for divide): ");
int userChoice = input.nextInt();
// Add
if (userChoice == add)
System.out.println("Your answer is: " + (intOne + intTwo));
// Subtract
else if (userChoice == subtract)
System.out.println("Your answer is: " + (intOne - intTwo));
// Multiply
else if (userChoice == multiply)
System.out.println("Your answer is: " + (intOne * intTwo));
// Divide
else if (userChoice == divide)
System.out.println("Your answer is: " + (intOne / intTwo));
// If wrong input
else
{
System.out.println("Nothing happens!");
System.out.println("Please make sure you entered a number and an operator.");
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
theMath();
System.out.println("Would you like to do another calculation?");
String redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}
}
I was wondering how I could recall the main method an infinite amount of times if I wanted to. What I was doing was just copying and pasting it over and over again but there has to be a better way. And also, I would like to know how to return a value has a decimal(so I could do 25/6 and get the correct answer).
Why not put only the statements that should be repeated inside a loop?
String redo;
do{
System.out.println("Would you like to do another calculation?");
redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}while(redo.equals("yes"))
As for the other part of your question. If you have two int values and want to get a decimal from a division, you can do it like this:
int x = 2;
int y = 3;
double result = (double)x/y;
System.out.println(result);
This is called casting.

Using multiple if else statements and why they loop?

When I type in this code it gives me a return that once I use yes for the first time, on the name, it uses that return for all of them for example: if I said my name is Justin, and I said that "Yes" it is, then say I mistyped my age, then it would not give me a chance to change it, it would say "Great!". How do I fix this? I am in 9th grade so I don't know too much about programming, sorry for the noob question. Thanks in advance!
import java.util.Scanner;
public class helloworld_main {
private static Scanner scan;
public static void main(String args[])
{
scan = new Scanner(System.in);
String name, age, year, yes, no, no1, no2;
System.out.print("Please enter your name --> "); // user prompt
name = scan.nextLine();
System.out.print("Please enter your age --> "); // user prompt
age = scan.nextLine();
System.out.print("Please enter the year you were born --> "); // user prompt
year = scan.nextLine();
// Their Name
System.out.println("So your name is... " + name + ". Right?"); // correction if name is not correct
yes = scan.nextLine();
if ("Yes".equals(yes))
{
System.out.println("Great!");
} else {
System.out.println("Oh. Please retype it.");
no = scan.nextLine();
System.out.println("Hello, " + no);
}
// The Age
System.out.println("The age you entered is..." + age + ". Right?");
if ("Yes".equals(yes))
{
System.out.println("Great!");
} else {
System.out.println("OK. Please reenter your age.");
no1 = scan.nextLine();
System.out.println("OK, I love " + no1 + " year olds!");
}
// Year Born
System.out.println("The year you were born is... " + year + ". Right?");
if ("Yes".equals(yes))
{
System.out.println("Fantastic!");
} else {
System.out.println("Ok then, please tell me what year you were born again.");
no2 = scan.nextLine();
System.out.println("Cool! I know someone else born in " + no2);
}
scan.close();
}
}
You need to read the user input again after you prompt for it again. Add:
yes = scan.nextLine();
after:
System.out.println("The age you entered is..." + age + ". Right?");
and:
System.out.println("The year you were born is... " + year + ". Right?");

Can someone figure out whats wrong with my code?

I've run a debugger and everything, but I can't find out whats wrong! I run the code, and it accepts a as an asnwer, but if i put b, it runs the code saying "This is not an A or a B"
import java.util.Scanner;
public class messingAround {
public static void main(String[] args){
Scanner ques = new Scanner(System.in);
String question;
System.out.println("Would you like to:");
System.out.println("A: Solve a math problem");
System.out.println("B: Display Pi");
System.out.println("Type A or B (no caps)");
question = ques.next();
if(!(question.equals("a")) || question.equals("b")){
System.out.println("Sorry that isn't an A or a B");
System.out.println("Try running the code again");
}else if(question.equals("a")) {
double fnum, snum, answer;
String type;
Scanner intString = new Scanner(System.in);
System.out.println("Enter your first number: ");
fnum = intString.nextDouble();
System.out.println("Enter your second number: ");
snum = intString.nextDouble();
System.out.println("What would you like to do? (+ - * /)");
type = intString.next();
if(type.equals("*")){
answer = fnum * snum;
System.out.println("The product is: " + answer);
}else if(type.equals("+")) {
answer = fnum + snum;
System.out.println("The sum is: " + answer);
}else if(type.equals("-")) {
answer = fnum - snum;
System.out.println("The difference is: " + answer);
}else if(type.equals("/")) {
answer = fnum / snum;
System.out.println("The dividend is: " + answer);
}
}else if(question.equals("b")) {
System.out.println("3.14159265359");
}
}
}
if(!(question.equals("a")) || question.equals("b")){
parens are a bit off. Try this:
if(!(question.equals("a") || question.equals("b"))){

Categories