How to add a roll dice function and a check guess function? - java

How to add a roll dice method and a check guess method?
My code:
package oui;
import java.util.Scanner;
public class dicecalc {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
int numGuess;
System.out.println("Enter the number the numer the dice will roll: ");
numGuess = kb.nextInt();
int dice1=(int)(Math.random()*6+1);
int dice2=(int)(Math.random()*6+1);
int sum = dice1 + dice2;
System.out.println("Roll: total = " + sum);
{
if (sum != numGuess) {
System.out.println("Sorry with a " + sum + " You LOSE :(");
} else {
System.out.println("Woah!!! With a " + sum + " You WIN!!!!!!!");
}
}
}
}
I need to have this assignment resubmitted because I forgot those things but I don't know how to add it. Please help. I already have tried for days.

Here's one possible basic layout. Replace the ??? with some code!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number the numer the dice will roll: ");
int numGuess = kb.nextInt();
int sum = sumOfTwoDiceRolls();
System.out.println("Roll: total = " + sum);
{
if (!checkGuess(numGuess, sum)) {
System.out.println("Sorry with a " + sum + " You LOSE :(");
} else {
System.out.println("Woah!!! With a " + sum + " You WIN!!!!!!!");
}
}
}
public static int sumOfTwoDiceRolls() {
return ??? ;
}
public static int singleDiceRoll() {
// Math.random() * (max - min + 1) + min
return (int)(Math.random() * (6 - 1 + 1) + 1);
}
public static boolean checkGuess(int guess, int numberToGuess) {
return ??? ;
}
}

Related

I need help converting my code from c++ to java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
One of my assignments is to convert a famous coding game called NIM from C++ to Java using three different methods. I'm having trouble converting it from C++ to Java. Can anyone help me fix my problem?
This is what they gave me in C++:
#include <iostream.h>
#include <lvp\random.h>
#include <lvp\bool.h>
//-----------------------------------------------------------------------------
void UserMove(int &NumStones)
/* Pre: NumStones > 0
Post: User has taken 1, 2, or 3 stones from pile */
{
cout << "How many would you like? ";
int TakeStones;
cin >> TakeStones;
while (TakeStones<1 || TakeStones>3 || TakeStones>NumStones) {
cout << "Value must be between 1 and 3" << endl;
cout << "How many would you like? ";
cin >> TakeStones;
}
NumStones-=TakeStones;
}
//-----------------------------------------------------------------------------
void ComputerMove(int &NumStones)
/* Pre: NumStones > 0
Post: Computer has taken 1, 2, or 3 stones from pile */
{
int TakeStones;
do {
TakeStones=1+random(3);
} while (TakeStones<1 || TakeStones>3 || TakeStones>NumStones);
cout << "The computer takes " << TakeStones << "." << endl;
NumStones-=TakeStones;
}
//-----------------------------------------------------------------------------
void PlayNim(NumStones)
/* Post: A game of Nim played with NumStones stones */
{
while (true) {
if (NumStones>0) {
cout << "There are " << NumStones << " stones. ";
UserMove(NumStones);
}
else {
cout << "You win!";
break;
}
if (NumStones>0) {
cout << "There are " << NumStones << " stones. ";
ComputerMove(NumStones);
}
else {
cout << "Computer wins!";
break;
}
}
}
//-----------------------------------------------------------------------------
int main()
{
randomize();
int NumStones=15+random(16);
PlayNim(NumStones);
return(0);
}
And this is what I got from converting it over to Java:
import java.lang.Math;
import java.util.Scanner;
import java.util.Random;
public class Nim {
public static void Usermove(int numstones) {
Scanner input = new Scanner(System.in);
numstones = 0;
int takestones;
System.out.println("How many would you like: ");
takestones = input.nextInt();
while (takestones > numstones) {
System.out.println("Value must be between 1 and 3");
System.out.println("How many would you like? ");
takestones = input.nextInt();
}
numstones-=takestones;
}
public static void Computermove(int numstones) {
Random rand = new Random();
int takestones;
int random = rand.nextInt(3);
do {
takestones=1 + random;
} while (takestones > numstones);
System.out.println("The computer takes" + takestones + ".");
numstones-=takestones;
}
public static void PlayNim(int numstones) {
while(true){
if (numstones>0) {
System.out.println("There are" + numstones + "stones");
Usermove(numstones);
}
else {
System.out.print("You Win!");
break;
}
if (numstones>0) {
System.out.println("There are" + numstones + "stones");
Computermove(numstones);
break;
}
}
}
public static void main(String[] args) {
Random rand = new Random();
int random = rand.nextInt(16);
int NumStones=15+random;
PlayNim(NumStones);
return(1);
}
}
I see several issues with your Java code.
UserMove() in the Java code sets numstones=0 upon entry, whereas UserMove() in the C++ code does not do that. You don't want UserMove() to zero out the input before modifying it.
The while loop of UserMove() in the Java code does not match the while loop of UserMove() in the C++ code. You are not checking the user's input to make sure it is between 1..3, inclusive.
The do..while loop of ComputerMove() in the Java code does not match the do..while loop of ComputerMove() in the C++ code. The C++ code generates a new random number on each loop iteration, but the Java code generates one random number before the loop and then reuses it on each iteration.
But, most importantly, in the C++ code, UserMove() and ComputerMove() (and presumably PlayNim(), too) take their int parameters by reference, which allows any modifications made by the functions to their parameter values to be reflected back to variables in the callers. However, in the Java code, the same functions take their int parameters by value instead, and as such any modifications made to their parameter values are not reflected back to the callers.
Java does not support pass-by-reference semantics, so you will have to re-write the logic a little bit. There are several ways you can do that.
You can wrap the int inside of a mutable class wrapper, such as Java's AtomicInteger or Apache's MutableInt, and pass around an instance of that class, eg:
import java.lang.Math;
import java.util.Scanner;
import java.util.Random;
import org.apache.commons.lang3.mutable;
public class Nim {
public static void Usermove(MutableInt numstones) {
Scanner input = new Scanner(System.in);
int takestones;
System.out.println("How many would you like: ");
takestones = input.nextInt();
while ((TakeStones < 1) || (TakeStones > 3) || (TakeStones > NumStones)) {
System.out.println("Value must be between 1 and 3");
System.out.println("How many would you like? ");
takestones = input.nextInt();
}
numstones.subtract(takestones);
}
public static void Computermove(MutableInt numstones) {
Random rand = new Random();
int takestones;
do {
takestones = 1 + rand.nextInt(3);
}
while ((TakeStones < 1) || (TakeStones > 3) || (TakeStones > NumStones));
System.out.println("The computer takes " + Integer.toString(takestones) + ".");
numstones.subtract(takestones);
}
public static void PlayNim(MutableInt numstones) {
while (true) {
if (numstones.intValue() > 0) {
System.out.println("There are " + numstones.toString() + " stones");
Usermove(numstones);
}
else {
System.out.print("You Win!");
break;
}
if (numstones.intValue() > 0) {
System.out.println("There are " + numstones.toString() + " stones");
Computermove(numstones);
break;
}
}
}
public static void main(String[] args) {
Random rand = new Random();
MutableInt NumStones = new MutableInt(15 + rand.nextInt(16));
PlayNim(NumStones);
}
}
You can use return values instead of pass-by-reference parameters, eg:
import java.lang.Math;
import java.util.Scanner;
import java.util.Random;
public class Nim {
public static int Usermove(int numstones) {
Scanner input = new Scanner(System.in);
int takestones;
System.out.println("How many would you like: ");
takestones = input.nextInt();
while ((TakeStones < 1) || (TakeStones > 3) || (TakeStones > NumStones)) {
System.out.println("Value must be between 1 and 3");
System.out.println("How many would you like? ");
takestones = input.nextInt();
}
return numstones - takestones;
}
public static int Computermove(int numstones) {
Random rand = new Random();
int takestones;
do {
takestones = 1 + rand.nextInt(3);
}
while ((TakeStones < 1) || (TakeStones > 3) || (TakeStones > NumStones));
System.out.println("The computer takes " + takestones + ".");
return numstones - takestones;
}
public static int PlayNim(int numstones) {
while (true) {
if (numstones > 0) {
System.out.println("There are " + Integer.toString(numstones) + " stones");
numstones = Usermove(numstones);
}
else {
System.out.print("You Win!");
break;
}
if (numstones > 0) {
System.out.println("There are " + Integer.toString(numstones) + " stones");
numstones = Computermove(numstones);
break;
}
}
}
public static void main(String[] args) {
Random rand = new Random();
int NumStones = 15 + rand.nextInt(16);
PlayNim(NumStones);
}
}
You can move the int into the Nim class itself, and remove the static from the class methods, eg:
import java.lang.Math;
import java.util.Scanner;
import java.util.Random;
public class Nim {
int numstones;
Random rand;
public Nim() {
rand = new Random();
numstones = 15 + rand.nextInt(16);
}
public void Usermove() {
Scanner input = new Scanner(System.in);
int takestones;
System.out.println("How many would you like: ");
takestones = input.nextInt();
while ((TakeStones < 1) || (TakeStones > 3) || (TakeStones > NumStones)) {
System.out.println("Value must be between 1 and 3");
System.out.println("How many would you like? ");
takestones = input.nextInt();
}
numstones -= takestones;
}
public void Computermove() {
int takestones;
do {
takestones = 1 + rand.nextInt(3);
}
while ((TakeStones < 1) || (TakeStones > 3) || (TakeStones > NumStones));
System.out.println("The computer takes " + Integer.toString(takestones) + ".");
numstones -= takestones;
}
public void PlayNim() {
while (true) {
if (numstones > 0) {
System.out.println("There are " + Integer.toString(numstones) + " stones");
Usermove();
}
else {
System.out.print("You Win!");
break;
}
if (numstones > 0) {
System.out.println("There are " + Integer.toString(numstones) + " stones");
Computermove();
break;
}
}
}
public static void main(String[] args) {
Nim game = new Nim();
game.PlayNim();
}
}

How to fix NoSuchElementExeption in Java [duplicate]

This question already has answers here:
Why is this code getting a Java NoSuchElement exception?
(3 answers)
Closed 5 years ago.
I've made a simple game with 2 classes. It uses a scanner and when I try it it says java.util.NoSuchElementExeption. It also says the errors are on row 19 in RNGlog and 24 in RNG. Please help
First class: RNG
public class RNG {
public static void main(String[] args) {
RNGlog log = new RNGlog();
int max = log.max();
int min = log.min();
double counter = 3;
//Variables outside of loop
System.out.println("Write a number between " + max + " and " + min + ".");
System.out.println("If your number is higher than " + max + ", it will be " + max + ". Vice versa for " + min + ".");
System.out.println("If your number is higher than the random number, you win credits!");
System.out.println("You start with 2 credits.");
System.out.println("You lose if you hit 0 credits. Good luck!");
//Introduction
while(counter > 0) {
//Loop start
double r = Math.random() * 10;
float in = log.getIn(); //Error here
//Random number generator, input
double credit = 6 - in;
//Credit Win generator
if(in > r) {
counter = counter + credit;
//Counter refresh
System.out.println("Great job! The number was " + r + ".");
System.out.println("You won " + credit + " credits. Nice.");
System.out.println("Credit counter:" + counter + ".");
//Winning messages
}
else {
counter = counter - 1;
//Counter refresh
System.out.println("Nearly, n00b! It was " + r + ", how did u no realize.");
System.out.println("You lost 1 credits!");
System.out.println("Credit counter:" + counter + ".");
//Losing messages
}
if(counter <= 0) {
System.out.println("Game over! Better luck next time.");
//Game ender
}
}
}
}
Second class: RNGlog
import java.util.Scanner;
public class RNGlog {
int max() {
int max = 6;
return max;
}
int min() {
int min = 0;
return min;
}
float getIn() {
Scanner scan = new Scanner(System.in);
float imp = scan.nextFloat(); //Error here
if(imp < min()) {
imp = min();
}
//Stops number lower than 0
if(imp > max()) {
imp = max();
}
//Stops numbers higher than 6
scan.close();
return imp;
}
}
Would be really apriciated if someone could help!
NoSuchElementException : if the input is exhausted
you must test before with scanner.hasNext()
and if (scan.hasNextFloat())

Search a randomly generated array for how many times a singular random number is present within the initial array

I have printed my array of 20 integers and then printed a single random number after this. I need to search/count the initial array for how many times the single # is present. So far I have been able to all but search/count for the single random number, it continues to search for any random number within the first array and count that number rather than searching for my single #.
My code:
import java.util.Scanner;
import java.util.Random;
class Main{
public static final Random RND_GEN = new Random();
public int[] createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
return randomNumbers;
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
}
public void searchArray(int[] randomNumbers,int numSearch) {
int count = 0;
System.out.println("Single # is: " + (RND_GEN.nextInt(10) + 1));
for (int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
if (count == 0) {
System.out.println("Single #" + numSearch + " was not found!");
} else {
System.out.println("Single # "+ numSearch + " was found " + count + " times");
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] numbers = new int[20];
numbers = createNum(numbers);
printNum(numbers);
int numSearch = RND_GEN.nextInt(10) + 1;
searchArray(numbers, numSearch);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}

Check if user enters negative numbers straight away?

I am trying to make a program where the user enters a number and the program computes the max and min and keeps asking untill it encounters negative.
DETAILED DESCRIPTION:-
However if the user enters a negative number at start up it should print "Max and min are undefined!" and end.
But if a positive number is entered the program prints max and min ,still keeps asking for more numbers untill a negative number is encountered ,seeing negative number it still prints max and min and then ends.
Is there a way to do this?
What i have tried is given below:-
import java.util.Scanner;
public class NegativeNum {
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
double num = keys.nextInt();
double Max = num+0.5;
double Min = num-0.5;
if(num<0) {
System.out.println("Max and Min undefined");
}
while(num>0) {
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("\nEnter another: ");
num = keys.nextInt();
}
{
num = num*-1;
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("Number is Negative! System Shutdown!");
System.exit(1);
}
}
}
Just calculate the maximum and minimum value during iteration
while(num>0) {
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("\nEnter another: ");
num = keys.nextInt();
if(Math.abs(num) > max) {
max = Math.abs(num);
}
if(Math.abs(num) < min) {
min = Math.abs(num);
}
}
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("Number is Negative! System Shutdown!");
System.exit(1);
import java.util.Scanner;
public class NegativeNum {
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
double num = keys.nextInt();
double Max = num+0.5;
double Min = num-0.5;
if(num<0) {
System.out.println("Max and Min undefined");
System.exit(1);
}
while(true) {
double temp_num = num;
num = Math.abs(num);
Max = num+0.5;
Min = num-0.5;
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
if ( temp_num < 0 )
break;
System.out.println("\nEnter another: ");
num = keys.nextInt();
}
System.out.println("Number is Negative! System Shutdown!");
}
}
import java.util.Scanner;
public class NegativeNum {
private static int entryCount = 0; // Count the Number of Entries
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
double num = keys.nextInt();
double Max = num+0.5;
double Min = num-0.5;
while(true) {
if( num < 0 && entryCount == 0) { // Make sure if it's first entry and it's negative too
System.out.println("Number is Negative! System Shutdown!");
System.exit(1);
}
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("\nEnter another: ");
num = keys.nextInt();
entryCount++;
}
}
}
This code successfully runs all the cases:-
import java.util.Scanner;
public class class2
{
public void positive(double num)
{
double Max = num+0.5;
double Min = num-0.5;
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
System.out.println("\nEnter another: ");
}
public void negative(double num,String k)
{
double Max = num+0.5;
double Min = num-0.5;
System.out.println("Max = " + Max);
System.out.println("Min = " + Min);
if(k=="terminate")
{
System.out.println("System is shutting down");
System.exit(1);
}
System.out.println("\nEnter another: ");
}
public static void main(String []args)
{
class2 obj=new class2();
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
boolean bol=true;
String k="";
double num = keys.nextInt();
int count=1;
if(num<0 && count ==1)
{
k="terminate";
count=count+1;
System.out.println("Max and Min undefined");
System.exit(1);
System.out.println("\nEnter another: ");
num = keys.nextInt();
}
while(bol==true)
{
while(num>0)
{
count=count+1;
obj.positive(num);
num = keys.nextInt();
}
while(num<0 && count!=2)
{
k="terminate";
obj.negative(num,k);
num = keys.nextInt();
}
count=count+1;
}
}
}

User input on same line?

I'm new to Java so forgive me. I'm writing a small little Guessing Game program.
import java.util.Scanner;
public class GuessingGame {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int menuOption;
// Main Screen //
System.out.println("Guessing Game");
System.out.println("---------------------");
System.out.println("1.) Play Game");
System.out.println("2). Exit");
System.out.println();
while (true) {
System.out.print("Please select a menu option: ");
menuOption = userInput.nextInt();
if (menuOption == 2) {
System.out.println("Exiting the game. Thanks for playing!");
break;
} else if (menuOption == 1) {
System.out.println("Let's start the game!");
getRandomRange();
} else {
System.out.println("Sorry, that's not a valid option. Please try again.");
continue;
}
}
}
/**
* Determine the range of numbers to work with
*/
public static void getRandomRange() {
int min;
int max;
System.out.print("Choose a minimum number: ");
min = userInput.nextInt();
System.out.print("Choose a maximum value: ");
max = userInput.nextInt();
getRandomNumber(min, max);
}
public static void getRandomNumber(int min, int max) {
int randomNumber = (int) (Math.random() * (max - min + 1)) + min;
getAGuess(min, max, randomNumber);
}
public static void getAGuess(int min, int max, int randomNumber) {
int guess;
while (true) {
System.out.print("Guess a number between " + min + " and " + (max) + ": ");
guess = userInput.nextInt();
if (guess == randomNumber) {
System.out.println("Correct! The random number is: " + randomNumber);
break;
}
}
}
}
When I prompt the user to guess a number and the number is incorrect, I want to be able to flush immediately flush the input stream and enter another guess on the same line.
For example:
Guess a number between 0 and 5: I enter my guesses here on this one line only.
I could take the print out of the loop but in that case, if I enter an inccorect number, the cursor jumps to the next line.
Hope this makes sense. Thanks!
If your goal is only to clear the console, then you could do:
Runtime.getRuntime().exec("cls");
Or if you are on Linux or OS X:
Runtime.getRuntime().exec("clear");
Now if you add previous line that you wanted to keep, you will need to keep then in an Array and reprint after each clear.
This won't work in IDE's.
If you want a more system-independent way, there is a library named JLine (GitHub), which is designed for a better console usage. It actually contains a method clearScreen.
You could also do:
System.out.print("\033[H\033[2J");
This will clear the screen and return the cursor to the first row.
A quick and dirty solution...
public class Main {
public static final void main(String[] data) {
Scanner userInput = new Scanner(System.in);
int min = 0;
int max = 10;
int randomNumber = (int) ((Math.random() * max) + (min + 1));
while (true) {
System.out.print("Guess a number between " + min + " and " + max + ": ");
int guess = userInput.nextInt();
if (guess == randomNumber) {
System.out.println("Correct! The random number is: " + randomNumber);
break;
} else {
for (int i = 0 ; i < 25; i++) {
System.out.println();
}
}
}
}
}

Categories