How to take integers being printed by a method? - java

I am making a very simple blackjack game with one class and at least 2 methods. I want to take the random generated numbers that are being output (cards being dealt) and add them so I can make an if else statement to check if the total is over 21 causing the player to lose.
import java.util.*;
public class BlackJack {
private Scanner scan;
static Random generator = new Random();
public BlackJack(){
scan = new Scanner (System.in);
}
public static void main(String[] args) {
StarterCards();
Hit();
}
public static void Hit() {
System.out.println("Hit? (y or n)");
String yes = new String ("y");
Scanner input = new Scanner(System.in);
String yesorno = input.nextLine();
if(yesorno.equals(yes)) {
RandomCard();
Hit();
if()
} else {
System.out.println("Game Over");
}
}
public static void RandomCard() {
int card = generator.nextInt(10) + 1;
System.out.println("Card : "+ card);
int total2 = card;
}
public static void StarterCards() {
int card1 = generator.nextInt(10) + 1;
int card2 = generator.nextInt(10) + 1;
System.out.println("Card : "+ card1);
System.out.println("Card : "+ card2);
}
}

Re:
How to take integers being printed by a method?
The solution: don't have the method print anything. Instead have the method return the number, and let the calling code print it or do with the number whatever it wants to do.
i.e.,
public int myMethod() {
int someNumber = ....; // calculate it here
// System.out.println(someNumber); // don't print it here!
return someNumber
}

Related

Vector in java always overwriting everything with the last value

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.

How to make an arraylist for the last dice rolls?

I've created a basic dice game. I would like to have a feature where if you choose to no longer play, you will get a list of all your previous rolls. I've made a method for generating the 2 random numbers for the dices. I can't access them since they are in the method.
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class DicegameV2 {
// method for generating random number for dice
static void dice_roll() {
Random rand = new Random();
int dice1 = rand.nextInt(6) +1;
int dice2 = rand.nextInt(6) +1;
System.out.println("you rolled " + dice1 + " and " + dice2);
}
public static void main(String[] args) {
ArrayList<Integer> last_dice_rolls = new ArrayList<Integer>();
boolean rollAgain = true;
// gets username
Scanner scanner = new Scanner(System.in);
System.out.println("What's your username?");
String username = scanner.nextLine();
System.out.println("Hello, " + username);
while (rollAgain) {
System.out.println("Roll the dice?");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("yes"))
dice_roll();
else if (choice.equalsIgnoreCase("no")) {
System.out.println("Thanks for playing!\nyour last rolls was " + last_dice_rolls);
rollAgain = false;
} else {
System.out.println("Please input yes or no");
}
}
}
}
You have the right idea with creating an ArrayList to keep the rolls in, but, as you found, your rolls are in dice1 and dice2 variables in the dice_roll method, so you can't put them into your ArrayList.
You could, as akuzminykh suggested, return the rolls from dice_roll(), but that's a bit tricky as it's two numbers, and a method returns one value, so you'd have to wrap them in something to return them (which is the right thing to do but a bit complex for a first program).
Java is object-oriented, which means that methods belong to objects, which can also keep data. That would be a good way of keeping the non-transient data you're trying to accumulate.
However, your methods are "static", which means they aren't part of any object. main() has to be static, as that's how programs in Java are started.
So you have several steps to make this work:
Have your main() method just create a new DicegameV2 object and call a play() method on it
move the current contents of the main() method into this new play() method, which is not static.
move the ArrayList last_dice_rolls out of the method, so it is not a local variable but an object member
make the dice_roll() method non-static, so it can access the last_dice_rolls member, like last_dice_rolls.add(dice1);
loop over last_dice_rolls and output the values at the end
Your new main() method would look like this (I'm not going to write your whole program)
public static void main(String[] args) {
DicegameV2 game = new DicegameV2();
game.play();
}
you can create a class Rolls
public class Rolls{
private int idRoll;
private int dice1;
private int dice2;
public void setIdRoll(int id){
idRoll = id;
}
public void setDice1(int d1){
dice1 = d1;
}
public void setDice2(int d2){
dice2 = d2;
}
public String toString(){
return "Roll number: " + idRoll + " dice1: " + dice1 + " dice2: " + dice2 + "\n";
}
}
and then use it on your main class
import java.util.*;
public class DicegameV2{
// method for generating random number for dice
public static void dice_roll(Rolls rolls) {
Random rand = new Random();
int dice1 = rand.nextInt(6) +1;
int dice2 = rand.nextInt(6) +1;
rolls.setDice1(dice1);
rolls.setDice2(dice2);
System.out.println("you rolled " + dice1 + " and " + dice2);
}
public static void main(String[] args) {
//I decided use LinkedList
List<Rolls> last_dice_rolls = new LinkedList<Rolls>();
int idRoll = 0;
boolean rollAgain = true;
// gets username
Scanner scanner = new Scanner(System.in);
System.out.println("What's your username?");
String username = scanner.nextLine();
System.out.println("Hello, " + username);
while (rollAgain) {
System.out.println("Roll the dice?");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("yes")){
Rolls rolls = new Rolls();
rolls.setIdRoll(idRoll++);
dice_roll(rolls);
last_dice_rolls.add(rolls);
}
else if (choice.equalsIgnoreCase("no")) {
System.out.println("Thanks for playing!\nyour last rolls was " + "\n");
for(Rolls r: last_dice_rolls){
System.out.println(r);
}
rollAgain = false;
} else {
System.out.println("Please input yes or no");
}
}
}
}
Make the arrayList last_dice_rolls an an attribute of the class Dicegame v2 so you can access it everywhere in your class.if you declare it in the main method,it will be accessible in the main method only.Try this:
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class DicegameV2 {
private static List<Integer> last_dice_rolls;
static void dice_roll() {
if(last_dice_rolls == null)
last_dice_rolls = new ArrayList<Integer>();
Random rand = new Random();
int dice1 = rand.nextInt(6) +1;
int dice2 = rand.nextInt(6) +1;
last_dice_rolls.add(dice1);
last_dice_rolls.add(dice2);
System.out.println("you rolled " + dice1 + " and " + dice2);
}
public static void main(String[] args) {
boolean rollAgain = true;
// gets username
Scanner scanner = new Scanner(System.in);
System.out.println("What's your username?");
String username = scanner.nextLine();
System.out.println("Hello, " + username);
while (rollAgain) {
System.out.println("Roll the dice?");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("yes"))
dice_roll();
else if (choice.equalsIgnoreCase("no")) {
System.out.println("Thanks for playing!\nyour last rolls was ");
for(int roll : last_dice_rolls)
System.out.println(roll);
rollAgain = false;
} else {
System.out.println("Please input yes or no");
}
}
}
}
java
share edit follow flag

Why won't my program loop correctly?

I'm new to programming and I'm making a guessing game where the program randomly generates a number between 1 and 10, the user then is asked to guess what the number is, the user should be able to keep guessing until he guesses correctly and the system asks them if they want to play again,
In my code I've printed the number that the system has randomly generated so that it is quicker to complete the game whilst testing. When I try and execute the program and enter the number that the system has generated the message that they are correct and asking if they want to play again does not come up.
Any help would be greatly appreciated!
Thank you in advance,
(Also, anything wrong with this question just tell me, it's my first time asking on here)
Here is my code,
import java.util.Scanner;
import java.util.Random;
public class GuessingGame1 {
public static int randomizer() {
Random rand = new Random();
int num = rand.nextInt(10)+1;
System.out.println(num);
int count = 0;
return num;
}
public static int userInput() {
System.out.println("I've thought of a number between 1 and 10");
System.out.println("Enter your guess...");
Scanner scan = new Scanner(System.in);
int guess = scan.nextInt();
return guess;
}
public static String compare() {
int count = 0;
String result = null;
if (userInput() == randomizer()) {
System.out.println("You guessed it - I was thinking of " + randomizer());
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (userInput() > randomizer()) {
result = "Lower!";
count++;
return result;
}
else if (userInput() < randomizer()) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
do {
randomizer();
do {
userInput();
compare
} while (userInput() != randomizer());
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
The problem is that you call twice to Randomizer!
call randomizer once as parameter to compare and return boolean from compare for a match.
You must change your methods something like this
public static String compare(int a,int b) {
int count = 0;
String result = null;
if (a == b) {
System.out.println("You guessed it - I was thinking of " + b);
count++;
result = "It took you " + count + " guesses.";
return result;
}
else if (a > b) {
result = "Lower!";
count++;
return result;
}
else if (a < b) {
result = "Higher";
count++;
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scanLine = new Scanner(System.in);
String playAgain = "";
int a;
int b;
do {
do {
a=userInput();
b= randomizer();
System.out.println(compare(a,b));
} while (a != b);
System.out.println("Play again? Yes/No");
playAgain = scanLine.nextLine();
} while (playAgain.equalsIgnoreCase("yes") || playAgain.equalsIgnoreCase("y"));
}
}
you have left the () in compare and the count will always be zero as it is been initialized when the compare function is called.

Reroll dices in yahtzee game

I´m trying to create a simple yahtzee game where an array is filled with 5 random numbers and where the player can choose to roll specific dices again. However I cant figure out how to write the method that is supposed to replace specific numbers in the array with new random numbers and return it. Any suggestions how to approach this?
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class YatzyGame {
private final Integer NBROFDICE = 5;
private final Integer DICEMAXVALUE = 6;
Random rnd = new Random();
Scanner keyboard = new Scanner(System.in);
public void startGame() {
int[] dice = new int[NBROFDICE];
rollDice(dice);
printDice(dice);
System.out.println("Do you want to reroll any dices? " + "Y/N");
String answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("y")) {
rerollDice(dice);
} else if (answer.equalsIgnoreCase("n")) {
calculateSum(dice);
} else {
System.out.println("Wrong command!");
}
}
public int[] rollDice(int[] dice) {
for (int i = 0; i < dice.length; i++) {
dice[i] = rnd.nextInt(DICEMAXVALUE) + 1;
}
return dice;
}
public int[] rerollDice(int[] dice) {
System.out.println("What dices do you want to reroll? Dices index are 0-4");
int diceToReroll = keyboard.nextInt();
// Replace the numbers at the index the user specifies with new random numbers and return the array.
}
public void printDice(int[] dices) {
System.out.println("Your dices show: " + Arrays.toString(dices));
}
public void calculateSum(int[] dices) {
int sum = 0;
for (int i : dices) {
sum += i;
}
if (sum == 30) {
System.out.println("YAHTZEE! Your total score is 50! Congratulations!");
} else
System.out.println("Your total score is: " + sum);
}
public static void main(String[] args) {
new YatzyGame().startGame();
}
}
public int[] rollDice(int[] dice) {
System.out.println("What dice do you want to reroll? Dices index are 0-4");
int diceToRoll = keyboard.nextInt();
dice[diceToRoll] = rnd.nextInt(DICEMAXVALUE) + 1;
}
Like this you can make a function:
public int[] reroll(int amountOfRerolls, int[] dices){
for(int i =0;i<dicesToReroll;i++){
this.rollDice(dices);
}
return dices;
}
This makes the programm a bit more modal since you can reuse your rollDice() method wherever you need it. Also you could expand it a bit by handing in the indexes that are allowed to be rerolled in case needed.
edit: style

How do I use the interface for this number reverse program, instead of using the program entry itself? (JAVA)

I need to know how to add the input as the number to be reversed. This questions answer should help anyone who has the need to make an input go into a program and come out modified.
import java.util.Scanner;
public class NumberReverse {
public int reverseNumber(int number){
System.out.print("Enter a number: "); <------ input
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
NumberReverse nr = new NumberReverse();
System.out.println("Result: " +nr.reverseNumber(Where I want the input to go / or you can put a number here inside of the program, instead of using the interface.));
}
}
I think best way to handle input in the main method and then trigger to reverseNumber with input value;
public class NumberReverse {
public int reverseNumber(int number){
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
try {
NumberReverse nr = new NumberReverse();
System.out.println("Result: " +nr.reverseNumber(Integer.valueOf(input)));
} catch (NumberFormatException nme) {
System.err.println("You entered not numeric value...!");
}
}
}
You can pass the number as the argument of the main:
public static void main(String a[]) {
NumberReverse nr = new NumberReverse();
System.out.println("Result: "+ nr.reverseNumber(Integer.parseInt(a[0])));
}
If you don't want interface, then remove Scanner statements and pass number as argument like below
public int reverseNumber(int number){
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
reverseNumber nr = new reverseNumber();
System.out.println("Result: " +nr.reverseNumber(52)); //pass the number you wish to reverse
}

Categories