I am I very beginner programmer and I am stuck on how I can reroll the dice in my program. The project that I am working on is Yahtzee. In Yahtzee, you roll 5 dice and you can choose what dice to reroll ('r') and what dice to keep ('k'). In all, I am trying to roll 2 times.
package yahtzee1;
import java.util.Scanner;
public class Yahtzee1 {
/**
* Allows the get information from the user like to keep or reroll
* #param prompt
* #return
*/
public static char getcharFromUser(String prompt) {
Scanner sc = new Scanner(System.in);
System.out.println(prompt);
char c = sc.next().charAt(0);
return c;
}
/**
* generate 5 random numbers from 1 to 6, inclusive
* #param dice array to store the numbers
*/
public static void roll(int[] dice) {
for (int i = 0; i < 5; i++) {
dice[i] = (int) (Math.random() * 6 + 1);
}
}
/**
* generate 5 random numbers from 1 to 6, inclusive
*
* #param dice array to store the numbers
*/
public static void printDice(int[] dice) {
for (int i = 0; i < 5; i++) {
System.out.print(dice[i]);
}
}
/**
* After the 5 dice are "rolled" user picks which dice to re-roll or keep
* #param dice
* #param option
*/
public static void reRoll(int[] dice, String option) {
//help here
}
/**
*
* #param dice
*/
public static void playRound(int [] dice){
for (int i = 0; i < 2;i++){
reRoll(dice, option);
roll(dice);
printDice(dice);
}
}
/**
* play Yahtzee
* #param args the command line arguments
*/
public static void main(String[] args) {
int[] dice = new int[6];
playRound(dice);
}
}
the section in my code where I need help is in the method reRoll.
You can do something like this:
public static void reRoll(int[] dice, String option) {
//Change the split parameter to whatever you need the delimiter to be
for(String numString: option.split(" ")){
int die = Integer.parseInt(numString);
dice[die-1] = (int) (Math.random() * 6 + 1);
}
}
public static void playRound(int [] dice){
roll(dice);
printDice(dice);
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 2;i++){
System.out.print("Enter dice to reroll: ");
String option = sc.nextLine();
reRoll(dice, option);
printDice(dice);
}
sc.close();
}
Related
Okay so for a project I need to loop through as many dice rolls as the user wants and store them in an array to print out at the end with an advanced for loop. I have everything else done but I am stuck on how to integrate an array/advanced for loop into my existing code.
This is the class used to deal with all the dice functions:
package paradiseroller;
public class PairOfDice
{
public int sides = 6;
public int die1; // Number showing on the first die.
public int die2; // Number showing on the second die.
public PairOfDice()
{
// Constructor. Rolls the dice, so that they initially
// show some random values.
roll(); // Call the roll() method to roll the dice.
}
public void roll()
{
// Roll the dice by setting each of the dice to be
// a random number between 1 and 6.
die1 = (int) (Math.random() * sides) + 1;
die2 = (int) (Math.random() * sides) + 1;
}
public int getDie1()
{
// Return the number showing on the first die.
return die1;
}
public int getDie2()
{
// Return the number showing on the second die.
return die2;
}
public int getTotal()
{
// Return the total showing on the two dice.
return die1 + die2;
}
}
This is the main file in which I need to use the array and for loop:
package paradiseroller;
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
String choice = "y";
Scanner sc = new Scanner(System.in);
while (choice.equalsIgnoreCase("y")) {
PairOfDice dice; // A variable that will refer to the dice.
int rollCount; // Number of times the dice have been rolled.
dice = new PairOfDice(); // Create the PairOfDice object.
rollCount = 0;
System.out.println("\nIt took " + rollCount + " rolls to get a 2.");
System.out.print("Would you like to continue? y/n");
choice = sc.nextLine();
}
}
}
For going as long as you want and storing it in a array then printing, let g be the amount the user wants
PairOfDice[] result = new PairOfDice[g];
// setting
for (int i = 0; i < g; i++)
{
result[i] = new PairOfDice();
}
// printing
for (PairOfDice r : result)
{
System.out.println(r.getDie1() + " " + r.getDie2());
}
Think of : as in so it's getting each int IN result and assigning it to r for each iteration.
Keep in mind this is for if you want to put it in a array (kinda bad in this case) if you just want to print immediately then you could use
for (int i = 0; i < g; i++)
{
dice = new PairOfDice();
System.out.println(dice.getDie1() + " " + dice.getDie2());
}
This also gives you access to the slot that it's in thanks to i.
So I am trying to make a hang man game using a website that returns random word. I'm using that random word for the hangman game.
What I am stuck on is validating a guess the user makes. Here is the code, I am just putting everything in main first then making separate methods to do the work for me after this works.
public static void main(String[] args) throws Exception {
randomWord = TestingStuff.sendGet();
int totalTries = 1;
char[] guesses = new char[26];
int length = randomWord.length();
Scanner console = new Scanner(System.in);
System.out.print("* * * * * * * * * * * * * * *"
+ "\n* Welcome to Hangman! *"
+ "\n* * * * * * * * * * * * * * *");
System.out.println("\nYou get 10 tries to guess the word by entering in letters!\n");
System.out.println(randomWord);
/*
Cycles through the array based on tries to find letter
*/
while (totalTries <= 10) {
System.out.print("Try #" + totalTries);
System.out.print("\nWhat is your guess? ");
String guess = console.next();
char finalGuess = guess.charAt(0);
guesses[totalTries - 1] = finalGuess; //Puts finalGuess into the array
for (int i = 0; i < totalTries; i++) { //checks to see if the letter is already guessed
if (finalGuess != guesses[i]) {
for (int j = 0; i < length; j++) { //scans each letter of random word
if (finalGuess.equals(randomWord.charAt(j))) {
}
}
} else {
System.out.println("Letter already guessed, try again! ");
}
}
}
}
What I am stuck on is inside of the while loop where it says:
for (int i = 0; i < totalTries; i++) { //checks to see if the letter is already guessed
if (finalGuess != guesses[i]) {
for (int j = 0; i < length; j++) { //scans each letter of random word
if (finalGuess.equals(randomWord.charAt(j))) {
}
}
} else {
System.out.println("Letter already guessed, try again! ");
}
}
It is giving me an error saying "char cannot be dereferenced". Am I missing something here?
finalGuess is a primitive char - you can't use methods, such as equals on it. You could just compare the two chars using the == operator:
if (finalGuess == randomWord.charAt(j)) {
This question already has answers here:
Java algorithm to make a straight pyramid [closed]
(4 answers)
Closed 8 years ago.
public class Main {
public static void main(String[] args) {
int i,j,k;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
for(k=3;k>0;k--)
{
System.out.println(" ");
}
System.out.println("*");
}
System.out.println("\n");
}
}
}
output is :
*
*
*
*
*
*
*
*
*
*
BUILD SUCCESSFUL (total time: 0 seconds)
Try this:
public static void main(String[] args) {
for(int i=0;i<5;i++) {
for(int j=0;j<5-i;j++) {
System.out.print(" ");
}
for(int k=0;k<=i;k++) {
System.out.print("* ");
}
System.out.println();
}
}
Output:
*
* *
* * *
* * * *
* * * * *
Just for your knowledge System.out.println will print on a new line where System.out.print will print in the same line.
OK, now that I have change the public static String to public static int the last function does not print out.
Thank you all for you're help.
Here is the full program. The last function does not seem to print.
import java.lang.String;
import java.util.Scanner;
public class stringFuncts{
/**
* #param <String> <str> <Takes in a String and reverses it.>
* #return <rev> <returns the reversed string>
*/
public static String reverseString (String str){
String rev = "";
int length = str.length();
for ( int i = length - 1 ; i >= 0 ; i-- ){
rev = rev + str.charAt(i);
}
return rev;
}
/**
* #param <int> <n> <It will sum up the odds of a set number>
* #return <results> <Will print out the total of the odds values>
*/
public static int sumOfOdds (int n){
int results = 0;
for(int i = 1; i <= n*2; i += 2){
results = results + i;
}
return results;
}
/**
* #param <int> <blanks> <Will count the amount of whitespace in the phrase>
* #return <numBlanks> <Will return the amount of whitespace found in the String>
*/
public static int numberOfBlanks(String blanks){
int numBlanks = 0;
for(int i = 0; i < blanks.length(); i++) {
if(Character.isWhitespace(blanks.charAt(i)))
numBlanks++;
}
return numBlanks;
}
public static void main(String [] args){
Scanner input = new Scanner(System.in);
String str;
int n = 0;
String blanks;
System.out.println("Enter a string to reverse");
str = input.nextLine();
System.out.println("The reverse output is: " + reverseString(str));
System.out.println("");
System.out.println("Enter a value to sum the odds");
n = input.nextInt();
System.out.println("The sum of the odds " + sumOfOdds(n));
System.out.println("");
System.out.println("Enter a string to find the amount of blanks");
blanks = input.nextLine();
System.out.print("The number od blanks in the string is: " + numberOfBlanks(blanks));
}
}
In your numberOfBlanks() return type is of String data type
change it to int data type
Your function is declared as public static String. You're trying to return a number, so the correct declaration would be public static int.
import java.lang.String;
import java.util.Scanner;
public class stringFuncts{
/**
* #param <String> <str> <Takes in a String and reverses it.>
* #return <rev> <returns the reversed string>
*/
public static String reverseString (String str){
String rev = "";
int length = str.length();
for ( int i = length - 1 ; i >= 0 ; i-- ){
rev = rev + str.charAt(i);
}
return rev;
}
/**
* #param <int> <n> <It will sum up the odds of a set number>
* #return <results> <Will print out the total of the odds values>
*/
public static int sumOfOdds (int n){
int results = 0;
for(int i = 1; i <= n*2; i += 2){
results = results + i;
}
return results;
}
/**
* #param <int> <blanks> <Will count the amount of whitespace in the phrase>
* #return <numBlanks> <Will return the amount of whitespace found in the String>
*/
public static int numberOfBlanks(String blanks){
int numBlanks = 0;
for(int i = 0; i < blanks.length(); i++) {
if(Character.isWhitespace(blanks.charAt(i)))
numBlanks++;
}
return numBlanks;
}
public static void main(String [] args){
Scanner input = new Scanner(System.in);
String str;
int n = 0;
String blanks;
System.out.println("Enter a string to reverse");
str = input.nextLine();
System.out.println("The reverse output is: " + reverseString(str));
System.out.println("");
System.out.println("Enter a value to sum the odds");
n = input.nextInt();
System.out.println("The sum of the odds " + sumOfOdds(n));
System.out.println("");
input.nextLine();
System.out.println("Enter a string to find the amount of blanks");
blanks = input.nextLine();
System.out.print("The number od blanks in the string is: " + numberOfBlanks(blanks));
}
}
Output:
Enter a string to reverse
this
The reverse output is: siht
Enter a value to sum the odds
3
The sum of the odds 9
Enter a string to find the amount of blanks
this is spartan!
The number od blanks in the string is: 2
I have a program that I have been working on for quite awhile now. I am need to make a program that solves a user specified summation puzzle through backtracking.
The user enters three separate strings, the first two strings added together should equal the third string.
example:
java + next = scala
4656 + 7980 = 12636
I believe I am on the right track, but I need to take the index's of each value on the <Character> ArrayList and have them sum to a number less than 20,000. How would I go about doing this?
below is the code I have so far:
import java.util.*;
public class SummationPuzzle
{
public static ArrayList<Character> fsList = new ArrayList<Character>();
public static ArrayList<Character> lastW = new ArrayList<Character>();
public static ArrayList<Character> finaList = new ArrayList<Character>();
/**
* Reads in 3 words entered by user and converts the first two string into a single <Character> ArrayList
* takes the third string entered and converts it into it's own <Character>ArrayList
* #param firstW
* #param secondW
* #param thirdW
*/
public static void convertStr(String firstW, String secondW, String thirdW)
{
String combined = firstW + secondW;
for(int i = 0; i< combined.length(); i++)
{
fsList.add(combined.charAt(i));
}
for(int j = 0; j< thirdW.length(); j++)
{
lastW.add(thirdW.charAt(j));
}
System.out.println( fsList +" "+lastW);
swapAdd(fsList, lastW);
//feeds the resulting lists into the swapAdd method
}
/**#param
* This method Swaps the first char of fsList with the char at fsList[1]to make sure it matches the char at lastW[1]
* #param fsList
* #param lastW
*/
public static void swapAdd(ArrayList<Character> fsList, ArrayList<Character> lastW)
{
Collections.swap(lastW, 0,1);
System.out.println(lastW + " lastW swap first char");
char temp = lastW.get(1);
int j= 0;
System.out.println(fsList+ " before swap");
if(!fsList.get(1).equals(temp) && fsList.contains(temp))
{
j = fsList.indexOf(temp);
Collections.swap(fsList,1,j);
}
System.out.println(fsList+ " after swap");
removeDuplicate(fsList, lastW);
}
/**
* Combines two <Character> ArrayList into a one <Character> ArrayList with single instances of the char
* #param fsList
* #param lastW
*/
public static void removeDuplicate(ArrayList<Character> fsList, ArrayList<Character> lastW)
{
ArrayList<Character> tempList = new ArrayList<Character>();
tempList.addAll(fsList);
tempList.addAll(lastW);
for(char dupLetter : tempList)
{
if(!finaList.contains(dupLetter))
{
finaList.add(dupLetter);
}
}
System.out.println(finaList + "This is the list with duplicates removed");
System.out.println(lastW);
}
//main method
public static void main(String[] args)
{
//Receive user input
Scanner userIn = new Scanner(System.in);
System.out.println("Please enter your first word");
String firstW = userIn.next().trim();
System.out.println("Please enter your Second word");
String secondW = userIn.next().trim();
System.out.println("Please enter your Third word");
String thirdW = userIn.next().trim();
//print the summation puzzle
System.out.println(firstW+ " + " + secondW + " = "+ thirdW);
convertStr(firstW, secondW, thirdW);
}
}