Calling Certain Methods - java

import java.util.Scanner;
import javax.swing.JOptionPane;
public class HW {
public static void main(String[] args){
while (retry == true){
getGuess();
getBet(balance);
checkGuess(getGuess());
updateBal(guessResult, betParsed);
goAgain(balance);
}
}
public static String getGuess(){
//Guess input
System.out.println("Guess: (H/T");
Scanner in = new Scanner(System.in);
boolean validInput = false;
String guess = null;
while (validInput == false){
guess = in.next();
if (guess.equals("H") || guess.equals("T")){
validInput = true;
} else {
JOptionPane.showMessageDialog(null, "Invalid Input: " + guess);
}
}
return guess;
}
public static boolean checkGuess(String sideGuess){
//Checks if the side is correct
double num = Math.round(Math.random());
boolean guessResult;
if (num == 0 && sideGuess.equals("H")){
System.out.println("Correct. The side was: H");
guessResult = true;
return true;
} else if (num == 1 && sideGuess.equals("T")){
System.out.println("Correct. The side was: T");
guessResult = true;
return true;
} else {
System.out.println("Incorrect.");
guessResult = false;
return false;
}
}
public static double getBet(double balance){
//Retrieves a bet from the user
Scanner in = new Scanner(System.in);
String betInput = null;
double betParsed = 0;
boolean validInput = false;
while (validInput == false){
betInput = in.next();
try {
betParsed = Double.parseDouble(betInput);
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invlaid Input: " + betInput);
}
if (betParsed > balance || betParsed < 0){
JOptionPane.showMessageDialog(null, "Invalid Input! You have: $" + balance);
} else {
validInput = true;
}
}
return betParsed;
}
public static double updateBal(boolean checkGuess, double getBet){
//Updates the balance based on the bet
double balance = 0;
if (checkGuess == true){
balance = balance + getBet * 2;
System.out.println("Your balance is now: $" + balance);
} else {
System.out.println("Your balance is now: $" + balance);
balance = balance - getBet;
}
return balance;
}
public static boolean goAgain(double balance){
//Determines if new play is needed
Scanner in = new Scanner(System.in);
boolean validInput = false;
String goAgainInput = null;
boolean retry;
while (validInput == false){
System.out.println("Go again? (Y/N)");
goAgainInput = in.next();
if (goAgainInput.equals("Y") || goAgainInput.equals("N")){
validInput = true;
} else {
JOptionPane.showMessageDialog(null, "Invalid Input: " + goAgainInput);
}
}
if (goAgainInput.equals("Y")){
retry = true;
return true;
} else {
System.out.println("You ended with: $" + balance);
retry = false;
return false;
}
}
}
Edited the code.
I'm trying to pass some defined variables into some of the methods, but it seems that I can't use them?
How can I fix this?
It seems they are not "local", which I cannot understand as they are defined in the methods.
I must be under thinking it.

The main() method should look like this, with only one parameter:
public static void main(String[] args) {
And for the second issue, updateBal() receives two parameters, but you're passing none. So the compiler is correctly complaining that you should pass them, according to what you want to do:
updateBal(false, 0); // pass the right values
Regarding the passing of parameters to the method, this is wrong:
getBet(balance);
checkGuess(getGuess());
updateBal(guessResult, betParsed);
You see, the variables guessResult and betParsed are local to the methods in which they were defined, you can't use them outside. And the methods return a value, which gets lost, because you're not using or storing it. Both problems have a simple solution - declare new variables local to the method:
double betParsed = getBet(balance);
boolean guessResult = checkGuess(getGuess());
updateBal(guessResult, betParsed);
Again, the same problem is here, in the main loop:
boolean retry = true;
while (retry) {
// ...
retry = goAgain(balance);
}
Bottom line: you must do something with the value returned by methods, and the variables declared inside a method will not be visible outside them.

Related

Program keeps printing "keep playing" instead of reading the code

Every time I run my program, if the point limit was not met it is supposed to ask the user to keep playing, and if they choose yes then it is supposed to go back to the loop and run the code again but it is not doing that. when I enter "yes" it just prints the amount of points i currently have rather than going back to the loop.
import java.util.*;
public class Blackjack {
private int points;
private int limit;
private Scanner scan;
public Blackjack() {
scan = new Scanner(System.in);
}
/*Purpose: To print the current points and the limit.
Input: Points and Limit
Output: Points and Limit
*/
public void displayPoints() {
System.out.println("Your points:" + points + "/" + limit);
}
/*Purpose: To ask the user for the game limit.
Input: Game limit
Output: Entered limit
*/
public void startGame() {
System.out.println("Enter point limit:");
limit = scan.nextInt();
displayPoints();
}
/*Purpose: To get the roll value from rolling a dice
Input: Nothing
Output: Random dice number
*/
public int getRoll() {
Random r = new Random();
int roll = r.nextInt(6) + 1;
System.out.println("You rolled:" + roll);
return roll;
}
/*Purpose: To see if the player wants to keep playing the game,
Input: yes or no
Output: User's response.
*/
public boolean askUser(boolean firstTime) {
if (firstTime == true)
System.out.println("Start Playing?");
else {
System.out.println("Keep playing?");
}
scan.next();
return firstTime;
}
/* Purpose: to display the result of points in the game.
Input: No input.
Output: amount of points in the game.
*/
public void displayResult() {
if (points == limit)
System.out.println("BlackJack!");
else if (points > limit)
System.out.println("Bust!");
else if (points < limit)
System.out.println("Stand at " + points + " points!");
}
/*Purpose: to play all methods
Input: none.
Output: Game results.
*/
public void play() {
boolean gameOver = false;
startGame();
askUser(true);
String response = "";
int roll = getRoll();
while (response.equals("yes") && gameOver == false)
getRoll();
points = points + roll;
displayPoints();
if (points >= limit)
gameOver = true;
else {
askUser(false);
}
displayResult();
}
public static void main(String[] args) {
Blackjack practice = new Blackjack();
practice.play();
}
}
You didn't get response when user type.
I think you can change your askUser method like below code.
public String askUser(boolean firstTime) {
if (firstTime == true)
System.out.println("Start Playing?");
else {
System.out.println("Keep playing?");
}
String response = scan.next();
return response;
}
then change play method like :
public void play() {
boolean gameOver = false;
startGame();
String response = askUser(true);
;
;
}
I have made small changes in your code. Try this:
package stack;
import java.util.*;
public class Blackjack{
private int points;
private int limit;
private Scanner scan;
private boolean firstime = true; //new
boolean gameOver; //new
private String answer;//new
public Blackjack(){
scan = new Scanner(System.in);
}
/*Purpose: To print the current points and the limit.
Input: Points and Limit
Output: Points and Limit
*/
public void displayPoints(){
System.out.println("Your points:" + points+"/"+limit);
}
/*Purpose: To ask the user for the game limit.
Input: Game limit
Output: Entered limit
*/
public void startGame(){//Changes
if(firstime == true) {
System.out.println("Start Playing?");
answer = scan.next();
}
switch(answer) {
case "yes":
System.out.println("Enter point limit:");
limit = scan.nextInt();
int roll = getRoll();
points = points + roll;
displayResult();
break;
case "no":
goodBye();
}
}
//New method
public void goodBye() {
System.out.println("Goodbye!");
scan.close();
}
/*Purpose: To get the roll value from rolling a dice
Input: Nothing
Output: Random dice number
*/
public int getRoll(){
Random r = new Random();
int roll = r.nextInt(6)+1;
System.out.println("You rolled:" + roll);
return roll;
}
/* Purpose: to display the result of points in the game.
Input: No input.
Output: amount of points in the game.
*/
public void displayResult(){//Changes
if(points == limit) {
gameOver = true;
System.out.println("BlackJack!");
displayPoints();
System.out.println("Keep playing?");
answer = scan.next();
}
else if (points > limit) {
gameOver = true;
System.out.println("Bust!");
displayPoints();
System.out.println("Keep playing?");
answer = scan.next();
}
else if (points < limit) {
gameOver = false;
System.out.println("Stand at " + points + " points!");
}
}
/*Purpose: to play all methods
Input: none.
Output: Game results.
*/
public void play(){//Changes
startGame();
ENDWHILE:while(gameOver == true || gameOver == false) {
if(answer.equals("yes")) {
firstime = false;
while(gameOver == true) {
points = 0;
startGame();
}
while(gameOver == false) {
startGame();
}
}else {
break ENDWHILE;
}
}
goodBye();
}
public static void main(String [] args){
Blackjack practice = new Blackjack();
practice.play();
}
}
this one is working.. you have made 2 little mistakes i have commented inside the code. need to wrap while loop content inside {}. and user input needs to be return as string in askUser function. the following code is working as you wanted.
package javaapplication1;
import java.util.*;
public class JavaApplication1 {
private int points;
private int limit;
private Scanner scan;
public JavaApplication1(){
scan = new Scanner(System.in);
}
public void displayPoints(){
System.out.println("Your points:" + points+"/"+limit);
}
/*Purpose: To ask the user for the game limit.
Input: Game limit
Output: Entered limit
*/
public void startGame(){
System.out.println("Enter point limit:");
limit = scan.nextInt();
displayPoints();
}
public int getRoll(){
Random r = new Random();
int roll = r.nextInt(6)+1;
System.out.println("You rolled:" + roll);
return roll;
}
public String askUser(boolean firstTime){
if(firstTime == true)
System.out.println("Start Playing?");
else {
System.out.println("Keep playing?");
}
return scan.next();
}
public void displayResult(){
if(points == limit)
System.out.println("BlackJack!");
else if (points > limit)
System.out.println("Bust!");
else if (points < limit)
System.out.println("Stand at " + points + " points!");
}
public void play(){
boolean gameOver = false;
startGame();
String resUser = askUser(true); // add a variable to catch the input //exp-"yes"
String response = "";
int roll = getRoll();
while(resUser.equals("yes")&& gameOver == false){ // you forget the { and use //the variable to check if it is yess or not
getRoll();
points = points + roll;
displayPoints();
if(points >= limit)
gameOver =true;
else{
resUser = askUser(false);//catching the new user input
}
}// you forget the }. if you are not wrapping the loop with {}, it will only //execute one line after the loop
displayResult();
}
public static void main(String [] args){
JavaApplication1 practice = new JavaApplication1();
practice.play();
}
}

While Loop Parsing Issue

I'm trying to give the user an infinite amount of inputs until they enter q. I'm using a while statement to run the program, but when the user tries to quit I get an error because the program would try and parse q as an integer. Any ideas on how I should change the structuring of this to prevent the error from occurring?
Scanner in = new Scanner(System.in);
System.out.println("What would you like your Fibonacci number to be?(enter q to quit)");
String value = in.next();
int trueValue;
while(!value.equalsIgnoreCase("q")) {
trueValue = Integer.parseInt(value);
Fibonacci userCase = new Fibonacci(trueValue);
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
System.out.println("Please enter another number.");
value = in.next();
trueValue = Integer.parseInt(value);
}
If it matters, here are the methods being called within the loop.
public int calculateFibonacci(int caseValue) {
if(caseValue == 0)
return 0;
else if(caseValue == 1)
return 1;
else
return calculateFibonacci(caseValue-1) + calculateFibonacci(caseValue-2);
}
public int getCaseValue()
{
return caseValue;
}
You can remove the last
trueValue = Integer.parseInt(value);
since you are already doing that at the start of the loop.
do{ getting the user value before checking } while(checking if it's ok);
/* https://stackoverflow.com/questions/40519580/trying-to-determine-if-a-string-is-an-integer */
private boolean isInteger(String str) {
if(str == null || str.trim().isEmpty()) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if(!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static String check(Scanner in) {
String value;
do {
System.out.println("Please enter a number or q to quit.");
value = in.next();
} while(!value.equalsIgnoreCase("q") && !isInteger(value));
return value;
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
String value = check(in);
while(!value.equalsIgnoreCase("q")) {
Fibonacci userCase = new Fibonacci(Integer.parseInt(value));
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
value = check(in);
}
in.close();
}

Trying to get isMultiple to execute properly

this executes, however it returns all answers as positive "8 is a multiple of 15" even if it is false. Not sure what I'm not seeing.
Here is what i have:
import java.util.*;
public class Multiples {
public static void main(String [] args){
boolean run = true;
while(run = true){
Scanner input = new Scanner(System.in);
System.out.print("Enter one number:");
int num1 = input.nextInt();
System.out.print("Enter a second number:");
int num2 = input.nextInt();
boolean result = isMultiple(num1,num2);
if(result = true){
System.out.println(num2 + " is a multiple of " + num1);
}
else{
System.out.println(num2 + " is not a multiple of " + num1);
}
System.out.println("Do you want to enter another pair(y/n)?");
String a = input.next();
if(YesOrNo(a)){
break;
}
}
}
public static boolean YesOrNo(String a){
if(a.equals("y"))
return false;
else if(a.equals("n"))
return true;
else
return true;
}
public static boolean isMultiple (int x , int y){
if(x % y == 0 || y % x == 0)
return true;
else
return false;
}
}
if(result = true){
replace with
if(result == true){
(or simply)
if(result){
You are assigning it instead of comparing.

Correct code will not compile?

This code seems perfectly fine for me (CS101) but my IDE throws up the error "This method must return a result of type boolean"
I don't want any tips on how to streamline my code or anything like that just want a reason for / solution as to why this is happening
public static boolean validation(String correct1, String correct2)
{
Scanner in = new Scanner(System.in);
boolean correctInput = false;
String userInput;
while (correctInput == false)
{
System.out.print("Type in " + correct1 + " or " + correct2);
userInput = in.next();
if ( userInput.equals(correct1) )
{
return true;
}else if ( userInput.equals(correct2) )
{
return false;
}else
{
System.out.println("Try again!");
}
}
}
Question is now solved, anyone interested why i needed this full code below:
import java.util.*;
public class CheckingInput
{
public static void main(String args[])
{
System.out.println("What is 1+1?");
boolean answer = validation("two", "three");
if(answer == true)
{
System.out.print("Correct!");
}else if(answer == false)
{
System.out.print("Wrong!");
}
}
public static boolean validation(String correct1, String correct2)
{
Scanner in = new Scanner(System.in);
boolean correctInput = false;
String userInput;
while (correctInput == false)
{
System.out.print("Type in " + correct1 + " or " + correct2 + ": ");
userInput = in.next();
if ( userInput.equals(correct1) )
{
correctInput = true;
return true;
}else if (userInput.equals(correct2))
{
correctInput = true;
return false;
}else
{
System.out.println("Try again!");
correctInput = false;
}
}
return false;// Doesn't really matter, loop will never reach here
}
I'm assuming the infinite loop is intentional, as you're awaiting a response from your user, so try the following:
public static boolean validation(String correct1, String correct2)
{
Scanner in = new Scanner(System.in);
String userInput;
while (true)
{
System.out.print("Type in " + correct1 + " or " + correct2);
userInput = in.next();
if ( userInput.equals(correct1) )
{
return true;
}
else if ( userInput.equals(correct2) )
{
return false;
}
else
{
System.out.println("Try again!");
}
}
return false; // Doesn't really matter, loop will never reach here
}
A return true; or return false statement is missing before the end of the function, in case the loop exits.

Boolean bug (FibonacciNumbers)

First of all I am not asking anyone to do anything just need a little help to fix this bug with boolean. I put false but the program stops. I got two parts to the program.
First part where i did the calculations:
class FibonacciNumbers {
FibonacciNumbers() {} //default constructor
public int fOf(int n) {
if (n == 0) //the base case
{
return 0;
} else if (n == 1) {
return 1;
} else {
return fOf(n - 1) + fOf(n - 2);
}
}
}
Second where the main method is:
import java.util.*;
public class FibonacciNumbersTesters {
public static void main(String[] args) {
FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object
Scanner in = new Scanner(System.in);
String again;
String test;
boolean IsRepeat = true;
boolean isQuit;
try {
isQuit = false;
while (!isQuit) {
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
int n = in.nextInt();
System.out.print("The Fibanocci number for " + n + " is: ");
n = fNumbers.fOf(n);
System.out.println(n);
System.out.print("Do you want to run again? (Y or N): ");
again = in.next();
if (again.equalsIgnoreCase("N")) {
System.out.println("Thank you! Please terminate the program by entering 'Q' or 'q' OR you can cotinue by entering anything else: ");
String toQuit = in.next();
if ((toQuit.charAt(0) == 'q') || (toQuit.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
}
} else {
IsRepeat = true;
}
}
} catch (InputMismatchException ex) {
test = in.nextLine();
if ((test.charAt(0) == 'q') || (test.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
} else {
System.out.println("Invalid input!");
System.out.println("Try again! ");
isQuit = false;
}
}
}
}
This part where i put isQuit = false; at the end it just stops. I want it to continue.
Try putting your try catch statement inside of your while loop.

Categories