Ending a round of Farkle in Java - java

I'm working on a Farkle assignment in Java, and I need the round to end and points to be lost for that turn if no 1s or 5s are rolled on the dice. The code I have will end the round if the first roll of the dice doesn't have any 1s or 5s, but the game will keep letting me roll until I get nothing but 1s and 5s if that makes sense. The prompt for this portion reads:
"The inner do-while loop
controlls each round of the game, ending when the user chose to secure their earned points
or when no further points were rolled."
Here's what I've got this far:
import java.util.Scanner;
import java.security.SecureRandom;
public class Farkle
{
static int[] rolls = new int[]{0,0,0,0,0};
static int round=0, totalScore=0, count1s5s =0;
public static void reset()
{
for(int i=0;i<5;i++)
rolls[i]=0;
}
public static int returnPoints()
{
int sum=0;
for(int i=0;i<5;i++)
{
if(rolls[i] == 1)
sum=sum+100;
if(rolls[i]==5)
sum=sum+50;
}
return sum;
}
public static void countFace()
{
for(int i=0;i<5;i++)
{
if(rolls[i] == 1 || rolls[i]==5)
count1s5s++;
}
}
public static void rollDice()
{
SecureRandom rand = new SecureRandom();
for(int i=0;i<5;i++)
{
if(rolls[i]!=1 && rolls[i]!=5)
{
int randValue = rand.nextInt(6)+1;
rolls[i] = randValue;
}
}
}
public static void display()
{
for(int i=0;i<5;i++)
{
System.out.print(rolls[i]+" ");
}
System.out.println();
}
public static void main(String[] args)
{
while(totalScore<1000)
{
char ch;
round++;
System.out.println("Beginning round "+round);
do
{
count1s5s = 0;
System.out.printf("Your roll: ");
rollDice();
display();
countFace();
System.out.printf("Keep rolling? (y/n) ");
Scanner in = new Scanner(System.in);
ch = in.next().charAt(0);
if(count1s5s == 0)
{
System.out.println("No new points scored; the round ends in a loss");
break;
}
}
while(ch!='n');
totalScore = totalScore+returnPoints();
System.out.println("Round "+round+" complete. Your current score is "+totalScore);
reset();
}
}
}
I've tried placing my if statement in my main class in different places within the do-while, but that hasn't done what I was hoping it would and rearranging the do-while hasn't done it either. I'm stuck and any help would be appreciated. Please let me now if there's any further clarification needed.

The problem is that you're not differentiating between what you rolled previously vs. what you rolled this round. countFace() can't tell whether a 1 or 5 was rolled this round or last round. Split this into two different arrays / Collections to solve the problem.
Right now, you're asking the user whether to keep rolling even if no 1's or 5's are rolled; is that what you want?
Also, create a SecureRandom just once, not every time through the loop.

Related

How to create an addition loop of random numbers?

After writing 1 on scanner I want a random dice number generated and after pressing 1 again I want another random number generated but now I want it added with previous number. I want to make a loop, I want to keep pressing 1 and keep adding random numbers till I reach a certain number.
Thank you.
import java.util.Random;
import java.util.Scanner;
public class dice {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int k = 0; k < 100; k++) {
Scanner scan = new Scanner(System.in);
int s = scan.nextInt();
System.out.println(s);
int previous = s;
if (s == 1) {
Random ran = new Random();
int n = ran.nextInt(6) + 1;
System.out.print(n);
int next;
while (true) {
next = scan.nextInt();
if (next == 1) {
System.out.println(previous);
}
previous = n + 10;
}
}
}
}
}
Define previous outside the for loop, and replace
int previous = s;
previous = n + 10;
with
previous += s;
previous += n + 10;
Scanner sc=new Scanner(System.in);
int sum=0;
for(;;)
{
if(sc.nextInt()==1)
{
int num = (int)(Math.random()*6); // using the pre-defined random function in java.lang.Math class
System.out.println("Dice Value: "+num);
sum+=num; // shorthand adding the number for each iteration
}
//if(sum>100)
// break;
//if statement to check if value of sum is greater/lesser than a specific number
}
System.out.println("Final Answer: "+sum)
Something like this might work (not yet tested): an infinite loop that can be terminated as per choice.
If you are looking for a way that the program works as soon as you physically press the '1' key on your keyboard, without having to press the enter key, something like a keyevent might work:
https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html
Please do let me know if there are any errors or doubts :)

Program not getting terminated

I've been doing a Java MOOC, and I'm stuck on a submission as my program does not terminate although I get desired output.
The problem says:
Create a method called printText which prints the phrase "In a hole in the ground there lived a method" and a newline. Then expand the program so that the main program asks the user for the number of times the phrase will be printed (i.e. how many times the method will be called).
I think the problem might be in my while loop not getting terminated.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("How many times?");
int n = Integer.valueOf(scanner.nextLine());
int a = 0;
while (true) {
if (a < n) {
printText();
a++;
}
}
}
public static void printText() {
System.out.println("In a hole in the ground there lived a method");
}
Your a < n condition should be associated with your loop. Although the if ensures that printText() is only called n times, it does not prevent the infinite loop from continuing forever:
while (a < n) {
printText();
a++;
}
Alternatively, you can keep your infinite loop but break when a >= n:
while (true) {
if (a < n) {
printText();
a++;
} else {
break;
}
}
But the first solution is more readable, in my opinion.
You are almost on track, get rid of outer loop while loop and change if (a < n) to while(a<n)
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("How many times?");
int n = Integer.valueOf(scanner.nextLine());
int a = 0;
while(a < n) {
printText();
a++;
}
}
public static void printText() {
System.out.println("In a hole in the ground there lived a method");
}
}

N prime numbers in java

So I've written this code in java which should output numbers on the screen from 1 to n(given by the user) and it should write "-prime" near the ones that are prime.
import java.util.Scanner;
public class primeMass {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n;
int i,j;
System.out.print("Dati n: ");
n = sc.nextInt();
for(i=1;i<=n;i++)
for(j=2;j<=n/2;j++)
{
if(i%j==0)
System.out.println(i);
else System.out.println(i +"-prime");
}}
}
If I input 6 for example i get :
Dati n: 6
1-prime
1-prime
2
2-prime
3-prime
3
4
4-prime
5-prime
5-prime
6
6
I'm new to this, and i'm really struggling with my algorithmic, could you tell me how should i change my program so it outputs correct values, and explain to me what i did wrong ? Thank you
UPDATE:
I've done it, thank you everyone for helping me out : this is the outcome:
import java.util.Scanner;
public class primeMass {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n;
int i,j;
boolean gasit = false;
System.out.print("Dati n: ");
n = sc.nextInt();
for(i=1;i<=n;i++) {
gasit=false;
for(j=2;j*j<=i;j++)
{
if(i%j==0) gasit=true;}
if(!gasit) {System.out.println(i+"-prime");}
else {
System.out.println(i);}
}
}
}
You print something on every iteration of the inner loop.
Instead, you should print something after all iterations have completed, e.g.
boolean found = false;
for(j=2;j<=n/2;j++) {
if(i%j==0) found = true;
}
if (!found) {
System.out.println(i + "-prime");
} else {
System.out.println(i);
}
Additionally, you shouldn't be going up to n/2: you perhaps mean i/2 (a number doesn't have any factors greater than itself); but you can make it even tighter, since you don't have to check for factors greater than sqrt(i). Or, stated another way, that j * j <= i.
So you can make your loop declaration:
for(j=2; j*j<=i; j++) {
The problem is that the second loop goes until n/2, it should go until i/2 to check if i is prime. A more optimzed version of the primality check algorithm goes until sqrt(i), as suggested in comments.
The next issue is that you are concluding, in a false way, that if in the first case if(i%j==0) you say not prime, otherwise you say it is prime, which is not true necessairly. You should iterate the whole interval of values between [2:i/2] to conclude that i is prime.

I am trying to make three dice roll simultaneously until they land on the same number

I am trying to make my program be able to show the count of how many times it takes until 3 dice land on the same number and then tell the use how many times it took, the number that it had landed on and have them repeat this process 3 times. However, I can't figure out how to make the program work. Currently, only Try, Dice 1, Dice 2, Dice 3 pop up, and then the amount of rolls it took under Try. How do I make the rest of this program work? Thanks!
import java.util.Random;
public class Q1
{
public static void main(String[] args){
Random g=new Random();
boolean same=false;
int dice1=0;
int dice2=0;
int dice3=0;
int count=0;
System.out.println("Try\tDice 1\tDice 2\tDice 3");
do{
System.out.println();
count++;
dice1=g.nextInt(6)+1;
dice2=g.nextInt(6)+1;
dice3=g.nextInt(6)+1;
System.out.print(count+"\t");
if(dice1==dice2 && dice2==dice3){
same=true;
System.out.println("It took"+count+"times and they all landed on number "+??);
}
}
while(!same);
}
}
same will always be true because you never set it to false in your code, yet in your do-while loop you're checking for !same, which will always return false since same is always true.
Try this:
import java.util.Random;
public class Q1
{
public static void main(String[] args){
Random g=new Random();
boolean same=false;
int dice1=0;
int dice2=0;
int dice3=0;
int count=0;
System.out.println("Try\tDice 1\tDice 2\tDice 3");
do{
System.out.println();
count++;
dice1=g.nextInt(6)+1;
dice2=g.nextInt(6)+1;
dice3=g.nextInt(6)+1;
System.out.print(count+"\t");
if(dice1==dice2 && dice2==dice3){
same=true;
System.out.println("It took"+count+"times.");
}
}
while(!same);
}
}

Methods Help in Java

public static void main(String[] args)
{
int i = 0;
i = rollDice(11);
System.out.print(" \nThe number of rolls it took: " + i);
i = rollDice(5);
System.out.print(" \nThe number of rolls it took: " + i);
}
public static int rollDice(int desiredNum)
{
int dice1 = 0;
int dice2 = 0;
Random rand = new Random();
int sum = 0;
int count = 0;
do
{
dice1 = rand.nextInt(6) +1;
dice2 = rand.nextInt(6) +1;
sum = dice1 + dice2;
count++;
} while(sum != desiredNum);
return count;
}
}
Im wanting to make it where the user can enter their own desired sum of the numbers to be rolled .Also I'm wanting it to display the value of each rolled die as its rolled. It needs to allow the user to call the rollDice method as many times as they want to.
Heres my exmaple output
EX- Please enter the Desired number: 8
Roll 1: 4 6 Sum: 10
Roll 2: 3 5 Sum: 8
It took 2 rolls to get the Desired number.
The original code above WAS a lab i had to do a few weeks ago. But we have just started this. And im trying to get ahead of the class. And this community helps alot. Thanks in advance.
The simplest solution here is to read user input using a Scanner, until the user enters a nominated character which ends the program.
e.g.
public static void Main(String[] args) {
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter desired number:");
String in = scan.nextLine();
rollDice(Integer.parseInt(in));
// Implement console output formatting here
} while(!in.equalsIgnoreCase("q"))
}
Here, the user can roll the dice for their desired number as many times as they want. When they are finished, entering "q" or "Q" in the console will end the program.
Also see the Javadoc for Scanner.
Try separating it into a few different methods like this. It'll help you think about the problem in smaller parts.
public static void main(String[] args) {
String input = "";
while(true) {
//Request input
System.out.println("Please enter the Desired number:");
input = getInput();
//Try to turn the string into an integer
try {
int parsed = Integer.parseInt(input);
rollDice(parsed);
} catch (Exception e) {
break; //Stop asking when they enter something other than a number
}
}
}
private static String getInput() {
//Write the method for getting user input
}
private static void rollDice(int desiredNum) {
//Roll the dice and print the output until you get desiredNum
}
To repeat, add a statement where the user enters a character that determines whether or not the program repeats itself. For example:
char repeat = 'Y';
while (repeat == 'Y' || repeat == 'y') {
// Previous code goes here
System.out.println("Try again? {Y/N} --> ");
String temp = input.nextLine();
repeat = temp.charAt(0);
}

Categories