I have the following code on Java which works fine now but I'm wondering how to make the same program but with multiple methods (object oriented programming). Right now all the code is in the main method and I'd like to make it so it has at least one other method where the calculations are made and that method would be called in the main method.
The program asks the user different kinds of multiplication questions like 2*3, 9*5 and so on
import java.util.Random;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
Random number = new Random();
while (true) {
int nmb1 = number.nextInt(10) + 1;
int nmb2 = number.nextInt(10) + 1;
int multi = nmb1 * nmb2;
int question;
// read the user's input ...
do {
question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + nmb1 + "*" + nmb2));
if (question != multi) {
JOptionPane.showMessageDialog(null, "Wrong, try again");
}
}
while (question != multi);
// .. and repeat until the user types the correct answer
JOptionPane.showMessageDialog(null, "Right");
}
}
}
If anyone can offer any help I would appreciate it.
You can simply wrap up your calculation and user input in a method call multiplication() as shown in the code below. The method will return a boolean value to identify if the user has answer the question correctly. HTH.
import java.util.Random;
import javax.swing.JOptionPane;
public class Main{
public static void main(String[] args) {
boolean correctAnswer;
Random number = new Random();
int nmb1;
int nmb2;
int multi;
while (true) {
nmb1 = number.nextInt(10) + 1;
nmb2 = number.nextInt(10) + 1;
multi = nmb1 * nmb2;
// read the user's input ...
do {
correctAnswer = multiplication(nmb1,nmb2,multi);
}
while (correctAnswer != true);
// .. and repeat until the user types the correct answer
JOptionPane.showMessageDialog(null, "Right");
}
}
public static boolean multiplication(int number1,int number2,int answer)
{
int question;
question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + number1 + "*" + number2));
if (question != answer) {
JOptionPane.showMessageDialog(null, "Wrong, try again");
return false;
}
return true;
}
}
Related
I'm a beginner in java and I have the following exercise to solve:
Read a set of sports lottery bets to an unspecified number of players. After that, read the template, compare the result and display a message.
Bet Class: must contain the player's name and an integer vector with thirteen positions to store the bet: 1 – winner of team A, 2 – winner of team B, and 0 for draw. Create the necessary constructor methods and the toString method.
ReadBets Class: This class must have an attribute that is a vector of objects of the Bet class. In addition, this class must have a method to read the person's name and their sports lottery game. Create the necessary constructor methods and the toString method.
ReadTemplate Class: This class should read the correct answers from the sports lottery game and store the result in an integer vector. Create the necessary constructor methods and the toString method.
GenerateResult Class: this class must compare the players' bets with the result of the template and, if you have 6 correct answers, show the winner's name, his game and the message: “WINNER, CONGRATULATIONS”. Otherwise, show the player name and the message “Try again, this time you didn't win”.
Main Class: implement in this class the control and execution flow for this problem creating the necessary objects to solve this class.
There is a complicating factor for me which is that each object bet is composed of a string name with a vector with the bets.
I made a solution to the problem that already reads validating only the allowed values (0,1,2), reads the template and compares.
However, I noticed that the last name typed and the last bets are always being recorded in the vector. In all positions.
I'm hours assembling and disassembling the code and I can't find a way to solve it.
I read that it may have to do with the new but I didn't understand how to solve it because at each position of the vector of objects I need to give a new to create the object with the internal vector that will store that player's bets.
Below are my classes:
MAIN:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
public void execute(){}
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
//ReadBet a = new ReadBet();
V_Bets a = new V_Bets();
System.out.println("Enter the total bets that will be placed");
a.totalBets(input.nextInt());
a.Data entry();
a.Data output();
ReadTemplate g = new ReadTemplate();
g.getTemplate();
GenerateResult gr = new GenerateResult();
gr.generateResult();
}
}
BETS:
import java.util.Arrays;
public class Bet {
private static String name;
public static int[] Bet vector =new int [6];
/*public String getName(){
return this.name;
}*/
public static String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
#Override
public String toString() {
return "Bet [name=" + name + ",Betvector=" + Arrays.toString(Betvector) + "]";
}
public int getBet(int i) {
return this.vector Bets[i];
}
public void setBets(int[] bets) {
this.vector Bets = bets;
}
public int[] getCloneArray() {
returnVectorBets.clone();
}
}
V_BETS
import java.util.Scanner;
public class V_Bets {
Input Scanner = new Scanner (System.in);
private int size;
public static Total BetBets[] = new Bet[100];
//total Bets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
private Bet bets = new Bet();
int i=0;
int j=0;
public void dataentry() {
for(j=0;j<size;j++) { //for external - from J that controls the total bets that will be registered
totalBets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
System.out.println("Enter the name of the Player:");
totalStakes[j].setName(input.next()); //setting the player's name
// loop to set the guesses
System.out.println("Please enter guesses for each Sports Lottery game");
System.out.println("1 - Winner Team A, 2 - Winner Team B and 0 - Tie");
for ( i=0;i<bets.vetorApostas.length;i++) // receive the bet until it reaches 6
{
System.out.println("Game "+i +":");
totalStakes[j].vectorStakes[i] = input.nextInt(); // receive the user's bets
while (totalApostas[j].vectorApostas[i] < 0 ) // if the user enters a negative number it says to try again
{
System.err.println("Negative Number, try again:");
totalBets[j].vectorBets[i]= entry.nextInt();
}
if (totalApostas[j].vetorApostas[i] > 2) // if the number is greater than 2 it says to try again
{
while (totalBets[j].vectorBets[i] > 2 ) {
System.err.println("Please enter numbers between 0 and 2");
totalBets[j].vectorBets[i]= entry.nextInt();
}
}
}
}
}
/*public void dataoutput() {
//System.out.println("The player's name is:"+total Bets[i].getName());
System.out.println("Your Bet:");
for ( i=0;i < Bet.vectorBeats.length; i++){
System.out.print(+TotalStakes[i].vectorStakes[i].getStakes(i)+ " ");
}
}
public void dataoutput() {
System.out.println("Your Bet::");
for (j=0; j<totalBets[i].vectorBets.length; j++) {
System.err.print("Player "+Total Bets[j].getName()+" ");
for (i = 0; i < totalBets[i].vectorBets.length; i++) {
System.err.print(total Bets[j].vector Bets[i] + " ");
}
}
}*/
public void totalOfBets(int size) {
this.size = size;
}
public int getSize() {
return size;
}
}
TEMPLATE:
public class Template {
//private String name;
public static int[]vectorTemplate =new int [6];
public int getBet(int i) {
return this.vectorTemplate[i];
}
public void setBets(int[] bets) {
this.vectorTemplate = bets;
}
public int getTemplate(int i) {
return this.vectorTemplate[i];
}
public void setTemplate(int[] bets) {
this.vectorTemplate = bets;
}
}
READ TEMPLATE:
import java.util.Arrays;
import java.util.Scanner;
public class ReadTemplate {
private Template template = new Template();
Input Scanner = new Scanner (System.in);
int guesses;
int counter=0;
int j;
int x;
int i;
public void getTemplate() {
System.out.println(" ");
for ( j=0;j<6;j++) // Receive numbers until it reaches 6
{
System.out.println("Now Enter Game Template: "+j);
template.vectorTemplate[j]= entry.nextInt(); // Receive user numbers
while (template.vetorTemplate[j] < 0 ) // If you enter a negative number, ask the user to type again
{
System.err.println("Negative Number, try again:");
template.vectorTemplate[j]=input.nextInt();
}
if (template.vectorTemplate[j] > 2) // if the number is greater than 2 ask again
{
while (template.vectorTemplate[j] > 2 )
{
System.err.println("Please enter numbers between 0 and 2");
template.vectorTemplate[j]=input.nextInt();
}
}
}
//printing the template
System.out.println("Template:");
for (i = 0; i < template.vectorTemplate.length; i++) {
System.out.print(template.vectorTemplate[i] + " ");
}
}
}
GENERATE RESULTS:
public class GenerateResult extends ReadTemplate {
private Bet bets = new Bet();
private Template template = new Template();
//private v_bets v_bets = new v_bets();
private int size;
public void generateResult() {
//Checking if it's right
int x;
V_Bets a = new V_Bets();
for(j=0;j<2;j++) {
int i=0;
int counter=0;
for (x = 0; x < template.vectorTemplate.length; x++) {
if (a.totalStakes[j].vectorStakes[i] == template.vectorTemplate[x]) {
counter++;
}
i++;
}
System.out.println(" ");
System.out.println("Counter of Equals! "+counter);
if (counter <= 5){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("Try again, this time you won");
}
else if (counter == 6){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("WINNER,CONGRATULATIONS!");
}
}
}
public void totalOfBets(int size) {
this.size = size;
}
}
I am immensely grateful to anyone who can help understand where I went wrong and how to evolve.
I have initiated the variable 'answer' in the near header of the class.
Later on when, a random number within an entered range has been generated, that same variable gets a new different value (due to the random generator). But as you can see, the variable 'answer' is indicated in two different colors (blue vs light brown), and as you expect, the routines that I have made are therefore not working. Somehow answer is not equal to answer. What did I do wrongly???? (unfortunately here you don't see the difference in colors).
In eclipse the color of 'answer' at the very top static int answer = 0; is BLUE.
But the one int answer = ThreadLocalRandom.current().nextInt(1, userinput); is GREY
Here's my code:
package Package1;
import java.util.concurrent.ThreadLocalRandom;
import java.util.Scanner;
public class test6KOPIE
{
static int numberofattempts = 0;
static int maxnummerofattemptsallowed = 5;
static int answer = 0;
public static void main(String[] args)
{
if (answer == 0)
{
Scanner maxinput = new Scanner(System.in);
System.out.println("Under which number do you want to guess");
int userinput = maxinput.nextInt();
int answer = ThreadLocalRandom.current().nextInt(1, userinput);
System.out.println(answer);
main(args);
}
else if (numberofattempts < maxnummerofattemptsallowed)
{
Scanner higherlower = new Scanner(System.in);
System.out.println("Higher or Lower");
int digit = higherlower.nextInt();
if (answer == digit)
{
System.out.println("very well");
}
else {
if (answer > digit )
{
++numberofattempts;
System.out.println("Higher, you have " +(maxnummerofattemptsallowed - numberofattempts)+" attempt(s) left)");
System.out.println(numberofattempts);
main(args);
}
else
{
++numberofattempts;
System.out.println("Lower, you have " +(maxnummerofattemptsallowed - numberofattempts)+" attempt(s) left)");
main(args);
}
}
higherlower.close();
}
else {
System.out.println("Maximum number of attempts used, the answer was" +answer);
}
}
This is because you are re-initializing your answer variable by retyping int before it. If you simply want to reassign the value, the line should be:
answer=ThreadLocalRandom.current().nextInt(1, userinput);
I am making a simple maths game, with 20 addition, subtraction and multiplication questions. I am trying to add a highscore functionality that appears at the end with the score that shows the user if they have beaten the highscore, and if they havent what the highscore currently is.
Below is the code i have so far for the game.
package au.edu.usc.mathgame;
import java.util.Random;
import java.util.Scanner;
/**
* A simple console-based maths quiz for primary school children.
*
*
public class Main {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int score = 0;
// now ask some random addition questions.
for (int i = 0; i < 10; i++) {
int a = rand.nextInt(20);
int b = rand.nextInt(20);
int questionType = rand.nextInt(3);
Question q = new Question(a, b, questionType);
q.showQuestion();
// Code to print test results
int response = input.nextInt();
boolean result = q.checkAnswer(response);
if (result) {
score = score + 1;
}
}
System.out.printf("Your Total Score is %2d ",score);
}
}
package au.edu.usc.mathgame;
import java.util.Random;
public class Question {
private int value1;
private int value2;
private int answer;
private int questionType;
private String operator;
public Question(int a, int b, int questionType) {
value1 = a;
value2 = b;
Random rand = new Random();
// Sets the operator based on the question type and calculates the answer
if (questionType == 0) {
operator = "+";
answer = a + b;
}
else if (questionType == 1) {
operator = "-";
answer = a - b;
}
else if (questionType == 2) {
operator = "*";
answer = a * b;
}
}
/**
* Selects operator and prints question.
*
*
*/
public void showQuestion() {
System.out.printf("What is %2d %s %2d? ", value1, operator, value2);
}
// checks and prints answers
public boolean checkAnswer(int response) {
if (response == answer) {
System.out.printf(" Yes!\n");
return true;
} else {
System.out.printf(" No, the answer is %d.\n", answer);
return false;
}
}
}
This is a very simple game and i just want to add a highscore functionality
You can maintain a text file which contains the high score. Whenever your game is finished you should read that file and compare it with the current player score. If its less than the high score, Display the high score on screen else replace the value inside the file with the current player score.
For how to read and write the file in java, you can reference the below link:
Java - Files and I/O
So I have three required codes I have already figured out. They are the codes for a quadratic formula, codes for an ISBN checker, and a code for Newtons Method. I'm supposed to make a menu with options 1, 2, and three each containing these codes respectively.
I guess this means I need different methods for this right? I was never really taught - I was told we had to always put in public class void main (String []args){ for everything, and I was just told there were variations to this?
For Quadratics formula, the information is : Return - void and parameters of three doubles, Newtons method: Return - double and parameters of 1 double, and ISBN checker: Return: Boolean and Parameters of 1 string. I don't really understand the parameters thing either. Help would be appreciated. I know this aesthetically looks horrible, but because my codes for now are relatively short I just edit the style when I' done. I know a lot of things are wrong in this too and I've spent time trying to figure them out.
import Java.util.Scanner;
public class HelperMethod{
public static void main(String[] args) {
Scanner userInputScanner = new Scanner (System.in);
System.out.println ("You have three options. press one for the quadratic Formula, 2 for the newtons Method, and 3 for an ISBN checker.");
int input = userInputScanner.nextInt();
if (input = 1){
}else if (input = 2) {
private class NewtonsMethod {
public static void NewtonsMethod(String[] args) {
Scanner userInputScanner = new Scanner (System.in);
double guess, fX, fPrimeX, newGuess;
System.out.println ("enter in a value give");
guess = userInputScanner.nextDouble();
System.out.println ("Your guess is " + guess);
while (true) {
fX = (6 * Math.pow (guess,4)) - (13 * Math.pow (guess,3)) - (18 * Math.pow (guess,2)) + (7 * guess) + 6;
fPrimeX = (24 * Math.pow (guess,3)) - (39 * Math.pow (guess,2)) - 36 * guess + 7;
newGuess = guess - (fX / fPrimeX);
System.out.println ("A possible root is " + newGuess);
if (Math.abs(newGuess - guess) < 0.00001) {
break;
} else {
guess = newGuess;
}
}
System.out.println ("The root is: " + newGuess);
}
}
}else{
private class BookNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char f;
int e, g, h;
int result = 0;
System.out.println ("Pleas enter a thirteen digit number");
String a = scanner.nextLine();
if (a.length() == 13){
for (int i = 0; i < 13; i ++) {
f = a.charAt(i);
e = Character.digit(f, 10);
if (i % 2 == 0) {
g = e * 1;
result = result + g;
} else {
g = e * 3;
result = result + g;
}
}
System.out.println ("The added sum of you numbers is " + result);
if (result % 10 == 0) {
System.out.println ("This combination IS a ISBN number");
} else {
System.out.println ("This is NOT an ISBN number");
}
} else {
System.out.println ("This combination is not thirteen digits long");
}
}
}
}
}
}
First of all, right now you're setting input to 1 in your first if statement. To compare input to 1 instead, use the == operator, i.e. if (input == 1) {.... Secondly, you don't really need to use classes, you can simply have methods NewtonsMethod(), BookNumber() etc. and run them when the input is correct.
public class HelperMethod{
public static void main(String[] args) {
int input;
//Handle user input
switch (input) {
case 1:
newtonsMethod();
break;
case 2:
bookNumber();
break;
case 3:
anotherMethod();
break;
}
}
public static void newtonsMethod() {
//Your code
}
public static void bookNumber() {
//Your code
}
public static void anotherMethod() {
//Your code
}
}
Methods should never be inside one another. That is what classes are for. A method is an element within a class. For example, in your case your class was named "HelperMethod". Your methods need to begin after the main method's code block is closed with a curly brace "}"
as an example
// This would be your main method.
public static void main(String args[]) {
// Your method is CALLED here.
someMethod();
{
// Then this is where your next method would start.
public static void someMethod() {
// Your code for the method of course goes here.
}
Of course you need your class setup and needed imports ABOVE the main method but you have that setup correctly already. With this setup, it makes it easy to call public methods that are in other classes. Your private methods are not really needed unless you intend to use more than one class, at which point you will need to import that class and then call the method like so
SomeClass.someMethod();
I'm working on a roulette game and I'm having an error with my makeDecision method in my Roulette class. The reason is because I am having trouble with the updatePot method in my Player class and am not sure what to do in it. I am using 4 classes, here is my code for each:
public class Assign3 {
public static void main(String[] args) {
Roulette roulette = new Roulette();
roulette.run();
}
}
and
public class Roulette {
private String decision;
Player player = new Player();
Wheel wheel = new Wheel();
private void makeDecision(){
String bet = player.getBet();
try {
int value = Integer.parseInt(bet);
if (value == wheel.getValue()){
decision = " you win 40 times your bet";
player.updatePot(40);
} else {
decision = "you lose the game";
player.updatePot(0);
}
} catch (NumberFormatException e){
if (bet.equals("odd")){
if (wheel.getValue() %2 == 0){
decision = "you lose the game";
player.updatePot(0);
} else {
decision = "you win double your bet";
player.updatePot(2);
}
} else if (bet.equals("equals")){
if (wheel.getValue() %2 == 0){
decision = "you win double your bet";
player.updatePot(2);
}
}
}
}
private void displayDecision(){
}
public void run(){
System.out.println("Welcome to Cache Creek style Roulette..bet an amount and type\n"
+ " if you select the correct colour, you win double your bet\n"
+ " if you select the correct odd/even, you win double your bet\n"
+ " if you select the right number, you win 40 times your bet\n"
+ " otherwise you lose your bet\n"
+ " If you lose all your money, the game is over");
do {
player.setBetAmount();
player.setBet();
wheel.spin();
wheel.display();
makeDecision();
displayDecision();
} while (true);
}
}
and
package Assignment3;
import java.util.Scanner;
public class Player {
private int pot = 0;
private int amount = 0;
Scanner input = new Scanner(System.in);
public void setBetAmount() {
System.out.print("\nHow much do you want to bet? ");
amount = input.nextInt();
int pot =100;
if (amount > pot || amount < 1){
System.out.print("Invalid bet amount..How much do you want to bet? ");
amount = input.nextInt();
}
}
public void setBet() {
System.out.print("What is your bet? (odd/even/red/black/exact number)");
}
public String getBet() {
return null;
}
public void updatePot(int i) {
}
}
and
package Assignment3;
import java.util.Random;
public class Wheel {
private int value;
private String colour;
Random random;
public Wheel(){
value = 0;
colour = null;
random = new Random();
}
public int getValue(){
return value;
}
public void setValue(int value){
this.value = value;
}
public String getColour(){
return colour;
}
public void spin(){
value = random.nextInt(39)+1;
colour = (random.nextInt(1)==0)?"red":"black";
}
public void display(){
System.out.print(value+" "+colour);
}
}
the input for your program has to be a String because your Player can input both text or a specific number. You then have to check this String for the occurence of either (odd/even/red/black) or a valid number. If neither is true then the input is invalid.
When looking at your code you need to think about how you want your updatePot method to work.
Should it set the pot to the given value (that's what the method name would suggest to me)
Should it add the given value to the pot or
Should it multiply the current pot value by the given value
When you have decided how it should work you have to update your Roulette.makeDecision() method.
Good luck with your assignment!
Markus
Just change the datatype of bet from String to int and then add your updatePot methode. You will also need to adjust your NumberFormatException.