Parameter Help for Multiple Methods - java

So I have an assignment to do the following two parameters (there were four in total but the first two were beyond easy)
Parameter 1: coinToss
This method simulates tossing a coin and prints out "Head" or "Tail"
For example, when this method is called, it will randomly print out either "Head" or "Tail"
Parameter 2: dayOfWeek
Given a number (1-7), this method returns the appropiate day of the week.
For example, Given 1 this method returns "Sunday".
I was actually able to do these two parameters my OWN method and worked perfectly fine. But he recently uploaded how he wanted us to do it and now need help!
How he wants us to do it:
Parameter 3:
m.coinToss();
Parameter 4:
System.out.print("Type any number (1-7): ");
int day = in.nextInt();
String dayOfWeek = m.dayOfWeek(day);
System.out.printf("%s is the %d day of the week.\n", dayOfWeek, day);
How I did it:
public void coinToss (int r) {
boolean headOrTail = (r % 2 == 0);
if (headOrTail) {
System.out.println("Heads");
} else {
System.out.println("Tails.");
}
}
public void dayOfWeek (int whichDay) {
Scanner in = new Scanner (System.in);
Homework2 m = new Homework2();
if (whichDay == 1) {
System.out.println("Sunday.");
}
if (whichDay == 2) {
System.out.println("Monday.");
}
if (whichDay == 3) {
System.out.println("Tuesday.");
}
if (whichDay == 4) {
System.out.println("Wednesday.");
}
if (whichDay == 5) {
System.out.println("Thursday.");
}
if (whichDay == 6) {
System.out.println("Friday.");
}
if (whichDay == 7) {
System.out.println("Saturday.");
}
if (whichDay > 7) {
int day;
System.out.print("Please enter a number from 1 and 7. ");
day = in.nextInt();
m.dayOfWeek(day);
}
}
public static void main(String[] args) {
int headOrTail = random.nextInt(100) + 1;
m.coinToss(headOrTail);
System.out.println();
System.out.print("Type any number (1-7): ");
int day = in.nextInt();
m.dayOfWeek(day);
}

Your implementation of coinToss is mostly fine, what you're missing is basically a way to generate a random number. In Java you have the java.util.Random class which does just that:
Random random = new Random();
int randomInteger = random.nextInt();
And now that you have your random integer, I'll leave you to plug that into your coin toss :)
Reference for Random: http://docs.oracle.com/javase/8/docs/api/java/util/Random.html
Edit: bonus points: since you only have two possible values, heads and tails, you can use the nextBoolean() method and simplify your coin toss condition. Good luck!

You can print both dayOfWeek and day.. So You try this one.
You need to change the return type of dayOfWeek method from void to String.
import java.util.Random;
import java.util.Scanner;
public class WeekDay {
static WeekDay m = new WeekDay();
static Scanner in = new Scanner (System.in);
static Random rand = new Random();
String day;
public void coinToss () {
int headOrTail = rand.nextInt(100) + 1;
boolean check = (headOrTail % 2 == 0);
if (check) {
System.out.println("Heads");
}else {
System.out.println("Tails.");
}
}
public String dayOfWeek (int whichDay) {
if (whichDay == 1) {
day = "Sunday.";
}
if (whichDay == 2){
day = "Monday.";
}
if (whichDay == 3){
day = "Tuesday.";
}
if (whichDay == 4){
day = "Wednesday.";
}
if (whichDay == 5){
day = "Thursday.";
}
if (whichDay == 6){
day = "Friday.";
}
if (whichDay == 7){
day = "Saturday.";
}
if (whichDay > 7) {
int dayCount;
System.out.print("Please enter a number from 1 and 7. ");
dayCount = in.nextInt();
m.dayOfWeek(dayCount);
}
return day;
}
public static void main(String[]args){
m.coinToss();
System.out.println("\n");
System.out.print("Type any number (1-7): ");
int dayCount = in.nextInt();
m.dayOfWeek(dayCount);
String dayOfWeek = m.dayOfWeek(dayCount);
System.out.printf("%s is the %d day of the week.\n", dayOfWeek, dayCount);
}
}

Related

Infinite Loop: My Mastermind program creates a infinite loop if you input the numbers 1, 3 ,5

I get an infinite loop every time I input the numbers 1, 3, 5 and I don't know how to fix it. This is a mastermind program using arrays in which pegs are used instead of numbers. The problem is most likely in the while loop in which was changed to make the program more condensed. Any help would be amazing.
package New;
import java.util.Random;
import New.ArrayMethod2;
import TurtleGraphics.KeyboardReader;
public class Mastermind2 {
public static void main(String[] args) {
Mastermind2 object = new Mastermind2();KeyboardReader reader = new KeyboardReader();
int[] V = new int [3];
do {
System.out.println("Please choose your first number (1-5)");
V[0]=reader.readInt();
System.out.println("Please choose your second number (1-5)");
V[1]=reader.readInt();
System.out.println("Please choose your third number (1-5)");
V[2]=reader.readInt();
}while((V[0]>5)&&(V[1]>5)&&(V[2]>5));
object.CorrectVariables(V[0], V[1], V[2]);
}
public void CorrectVariables(int num1, int num2, int num3) {
Mastermind1 object = new Mastermind1();
int Cornum1, Cornum2, Cornum3;
Random generator = new Random();
Cornum1 = generator.nextInt(5)+1;
Cornum2 = generator.nextInt(5)+1;
Cornum3 = generator.nextInt(5)+1;
IFstatements(Cornum1, Cornum2, Cornum3, num1, num2, num3);
}
public void IFstatements(int Cornum1, int Cornum2, int Cornum3, int num1, int num2, int num3) {
Mastermind1 object = new Mastermind1();
do{
int Number=0, Color=0;
if(Cornum1==num1)
{
Number++;
Color++;
}
if(Cornum1==num2)
{
Color++;
}
if(Cornum1==num3)
{
Color++;
}
if(Cornum2==num2)
{
Number++;
Color++;
}
if(Cornum2==num1)
{
Color++;
}
if(Cornum2==num3)
{
Color++;
}
if(Cornum3==num3)
{
Number++;
Color++;
}
if(Cornum3==num1)
{
Color++;
}
if(Cornum3==num2)
{
Color++;
}
System.out.println("You have "+Number+" numbers correct and "+Color+" colors correct");
if((Cornum1!=num1)||(Cornum2!=num2)||(Cornum3!=num3));
{
Number=0;
Color=0;
}
}while((Cornum1!=num1)&&(Cornum2!=num2)&&(Cornum3!=num3));
System.out.println("Congrats you guessed the correct numbers");
}
}
Print out:
It looks like the exit condition for your IFStatements function is that the user's input matches the correct pattern. However, the user does not get a chance to update his input and you never change the num or Cornum variables to match the correct output. Therefore, the loop is going to continue to execute forever. What you need to do is have that code run once and then give the user a chance to update their answers.
public static void main(String[] args) {
Mastermind2 object = new Mastermind2();
Scanner scan = new Scanner(System.in);
int one = getNumber("first", scan);
int two = getNumber("second", scan);
int three = getNumber("third", scan);
object.correctVariables(one, two, three);
}
private static int getNumber(String str, Scanner scan) {
while (true) {
System.out.print("Please choose your " + str + " number (1-5): ");
int num = scan.nextInt();
if (num >= 1 && num <= 5)
return num;
}
}
public void correctVariables(int one, int two, int three) {
Random random = new Random();
int expectedOne = random.nextInt(5) + 1;
int expectedTwo = random.nextInt(5) + 1;
int expectedThree = random.nextInt(5) + 1;
ifStatements(expectedOne, expectedTwo, expectedThree, one, two, three);
}
public void ifStatements(int expectedOne, int expectedTwo, int expectedThree, int one, int two, int three) {
int num = expectedOne == one ? 1 : 0;
num += expectedTwo == two ? 1 : 0;
num += expectedThree == three ? 1 : 0;
int color = expectedOne == one ? 1 : 0;
color += expectedOne == two ? 1 : 0;
color += expectedOne == three ? 1 : 0;
color += expectedTwo == one ? 1 : 0;
color += expectedTwo == two ? 1 : 0;
color += expectedTwo == three ? 1 : 0;
color += expectedThree == one ? 1 : 0;
color += expectedThree == two ? 1 : 0;
color += expectedThree == three ? 1 : 0;
System.out.println("You have " + num + " numbers correct and " + color + " colors correct");
if (num == 3)
System.out.println("Congrats you guessed the correct numbers");
}

Not sure how to do a while loop in this situation

I am writing a program to take the input for a sequence
import java.util.Scanner;
public class FibonacciCode {
public static void main(String[] args) {
System.out.println("Enter a number");
int count, number0 = 0, number1 = 1, loop = 0;
Scanner userInput = new Scanner(System.in);
count = userInput.nextInt();
while(loop > count)
{
System.out.print(number0 + ", ");
int sum = number0 + number1;
number0 = number1;
number1 = sum;
loop++;
}
}
}
This should be a usable implementation:
public class Menu {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
boolean orderCompleted = false;
while(!orderCompleted) {
printMenu();
String orderString = a.nextLine();
int order = Integer.parseInt(orderString);
int total = 0;
if(order == 1) {
} else if(order == 2) {
} else if(order == 3) {
} else if(order == 4) {
} else if(order == 5) {
}
System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
orderString = a.nextLine();
if(orderString.equals("n")){
orderCompleted = true;
}
}
}
private static void printMenu() {
System.out.println("Welcome to Hess Burgers");
System.out.println("1- Cheeseburger.............$7");
System.out.println("2- Barbeque Burger..........$8");
System.out.println("3- Southwestern Burger......$9");
System.out.println("4- Bacon Cheeseburger.......$10");
System.out.println("5- Double Stack Burger......$11");
System.out.println("");
System.out.print("Please enter your order selection:");
}
}
I pulled the menu printing to a separate method, and re-used scanner a as well as re-using the orderString. The while loop checks a completedOrder boolean flag, so that it can be used to do completion tasks prior to exiting the order loop if need be.
import java.util.Scanner;
public class FibonacciCode {
public static void main(String[] args) {
System.out.println("Enter a number");
int count, number0 = 0, number1 = 1, loop = 0;
Scanner userInput = new Scanner(System.in);
count = userInput.nextInt();
while(loop > count)
{
System.out.print(number0 + ", ");
int sum = number0 + number1;
number0 = number1;
number1 = sum;
loop++;
}
}
}
A while loop does whatever is in the block as long as the condition is true, in your case, you are simply repeating order = b.nextInt() until something other than 'y' is given as input
while (continuePlay= b.nextLine().equalsIgnoreCase ("y")) {
order = b.nextInt(); // This is inside the block
}
you should use a do while loop instead, like so:
do{
System.out.println("Welcome to Hess Burgers");
System.out.println("1- Cheeseburger.............$7");
System.out.println("2- Barbeque Burger..........$8");
System.out.println("3- Southwestern Burger......$9");
System.out.println("4- Bacon Cheeseburger.......$10");
System.out.println("5- Double Stack Burger......$11");
System.out.println(" ");
System.out.print("Please enter your order selection:");
Scanner a = new Scanner(System.in);
int order = a.nextInt();
int total = 0;
boolean continuePlay = true;
if (order == 1 ) {
} else if (order == 2) {
} else if (order == 3) {
} else if (order == 4) {
} else if (order == 5) {
}
Scanner b = new Scanner(System.in);
System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
} while (continuePlay= b.nextLine().equalsIgnoreCase ("y"));
Also I'd recommend reading some basic programming books or tutorials instead of going directly to Stack Overflow.

Type mismatch: cannot convert from double to int

Need to write a program to calculate sum of all digits and then give results when the total sum vaue ends with 5 or 8.Please help correct this code!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int customerID = in.nextInt();
while(customerID > 0)
{
int Reminder = customerID % 10;
int sum = sum+ Reminder;
customerID = customerID / 10;
}
if(sum%5||sum%8)
{
System.out.println("Lucky Customer");
}else
{
System.out.println("Unlucky Customer");
}
if(sum <0)
{
System.out.println("Invalid Input");
}
}
}
instead of doing
if(sum%5||sum%8)
{
System.out.println("Lucky Customer");
}
where sum%8 will be true for the value 16 so you can try this
int rem=sum%10;
if(rem==5||rem==8)
{
System.out.println("Lucky Customer");
}
Apart from the fact that this code doesn't produce the error you've mentioned, there are other issues with the code. I've tried to address them instead.
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int customerID = in.nextInt();
int sum = 0;
// sum needs to be initialized outside the while loop
// or else you wouldn't be able to use it outside it
while(customerID > 0) {
int Reminder = customerID % 10;
sum = sum+ Reminder;
customerID = customerID / 10;
}
if(sum%5 == 0 || sum%8 == 0) {
//You cannot use int as a condition in if
System.out.println("Lucky Customer");
} else {
System.out.println("Unlucky Customer");
}
if(sum <0) {
System.out.println("Invalid Input");
}
}
This code throws this exception only if your input would contain a dot (e.g.: "3.0"). So either pass the int value (e.g.: "3") or use scanner.nextDouble() and then convert it to int.
Also look into Yash's answer, because your code has other problems too.
+never write variable names with capital letter ("Reminder")!!!!
Please correct your code to remove some compilation errors...
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int customerID = in.nextInt();
int sum = 0;
while(customerID > 0) {
int Reminder = customerID % 10;
sum = sum + Reminder;
customerID = customerID / 10;
}
if(sum % 5 == 0 || sum % 8 == 0) {
System.out.println("Lucky Customer");
} else {
System.out.println("Unlucky Customer");
}
if(sum <0) {
System.out.println("Invalid Input");
}
}
}

How to give input array[] using scanner without space?

In this below program, I'm trying to check whether the number is ISBN or not. I'm giving input with spaces (eg: 0 3 0 6 4 0 6 1 5 2) because array only accepts it like this. I don't know how to give input without space to read. Can anyone help me how to read the number eg: 0306406152 and also it will read 10 numbers only like if(i==10) else it says it's not ISBN number to give output.
public class ISBN {
int digits[];
int dig = 11;
int sum;
int isbn1;
public void CheckISBN() {
for (int digit : digits) {
// System.out.println(digit);
if (dig >= 1) {
dig--;
digit = digit * dig;
// System.out.println(dig);
}
sum = sum + digit;
isbn1 = sum % 11;
}
if (isbn1 == 0) {
System.out.println(isbn1);
System.out.println("it's valid ISBN number");
} else {
System.out.println("sorry it's not valid ISBN");
}
}
public static void main(String[] args) {
ISBN aa = new ISBN();
aa.digits = new int[10];
Scanner scan = new Scanner(System.in);
int i = 0;
while (scan.hasNextInt()) {
aa.digits[i] = scan.nextInt();
i++;
if (i == 10) // aa.CheckISBN();
{
break;
}
for (int j = 0; j < aa.digits.length; j++) {
// System.out.print(aa.digits[j]);
}
//System.out.println();
}
aa.CheckISBN();
}
}
SAMPLE OUTPUT: 0 3 0 6 4 0 6 1 5 2
it's valid ISBN number
When the number is given without spaces,
import java.io.*;
import java.util.*;
public class ISBN {
int digits[];
int dig = 11;
int sum;
int isbn1;
public void CheckISBN() {
if(this.digits.length != 10)
{
System.out.println("sorry it's not valid ISBN");
return;
}
for (int digit : digits) {
// System.out.println(digit);
if (dig >= 1) {
dig--;
digit = digit * dig;
// System.out.println(dig);
}
sum = sum + digit;
isbn1 = sum % 11;
}
if (isbn1 == 0) {
//System.out.println(isbn1);
System.out.println("it's valid ISBN number");
} else {
System.out.println("sorry it's not valid ISBN");
}
}
public static void main(String[] args) {
ISBN aa = new ISBN();
Scanner scan = new Scanner(System.in);
String num = scan.next(); //take input as a string
int[] digits = new int[num.length()];
for(int i = 0; i<digits.length; i++)
digits[i] = num.charAt(i) - '0';
aa.digits = digits;
aa.CheckISBN();
}
}
Or scan it as int to get number format validation for free:
public class ISBN {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
if (scan.hasNextInt()) {
checkISBN(scan.nextInt());
}
}
public static void checkISBN(int isbn) {
int sum = sum(digits(isbn));
int isbn1 = sum % 11;
if (isbn1 == 0) {
System.out.println(isbn1);
System.out.println("it's valid ISBN number");
} else {
System.out.println("sorry it's not valid ISBN");
}
}
private static int sum(int[] digits) {
return IntStream.rangeClosed(1, digits.length)
.map(i -> i * digits[digits.length - i])
.sum();
}
private static int[] digits(int isbn) {
return Integer.toString(isbn)
.chars()
.map(c -> c - '0')
.toArray();
}
}
N.B.: It works for ISBN both with or without leading zeros.

Rock Paper Scissors Compiler Error

I am trying to construct a rock paper scissors game that incorporates multiple classes together. I am struggling a lot with object oriented programming, and I cannot figure out how to correct my compiler error. Below is my code:
Main method:
import java.util.*;
public class RPSMain extends RPSPlayer{
RPSPlayer player = new RPSPlayer();
RPSGame gameObject = new RPSGame ();
public void main ()
{
Random generator = new Random ();
Scanner sc = new Scanner(System.in);
System.out.print ("Number of Rounds: ");
int rounds = sc.nextInt();
//Call and process all of the methods found in RPSPlayer and RPSGame
for (int i = 0; i < rounds; i++){
int playerThrow = player.makeThrow();
int compThrow = gameObject.makeCompThrow();
int winner = gameObject.announceWinner (compThrow, playerThrow );
System.out.print (gameObject.bigWinner(winner, rounds));
}
//Final Output
System.out.print (gameObject.bigWinner(winner, rounds));
}
//accessor to return round to RPSGame
public int getRound (int round){
this.round = round;
return round;
}
}
Game method:
import java.util.*;
public class RPSGame extends RPSPlayer{
RPSPlayer player = new RPSPlayer();
RPSGame game = new RPSGame ();
RPSMain mainRPS = new mainRPS();
public void main (String args[]) {
Random generator = new Random ();
Scanner sc = new Scanner(System.in);
int rounds = mainRPS.getRound(rounds);
}
//Random Throw Generator
public int makeCompThrow (){
int Max = 3;
int Min = 1;
int compThrow = Min + (int)(Math.random() * ((Max - Min) + 1));
return compThrow;
}
// Get the throw from the player in RPSPlayer
public int getPlayerThrow (){
RPSPlayer player = new RPSPlayer();
int getPThrow = player.makeThrow();
return getPThrow;
}
//Does all of the calculatoins and ouputs who threw what.
public int announceWinner (int compThrow, int getPThrow) {
int winner = 0;
if (getPThrow == 1){
System.out.println ("Player throws ROCK.");
}
else if (getPThrow == 2){
System.out.println ("Player throws PAPER.");
}
else if (getPThrow == 3){
System.out.println ("Player throws SCISSORS.");
}
if (compThrow == 1){
System.out.println ("Computer throws ROCK.");
}
else if (compThrow == 2){
System.out.println ("Computer throws PAPER.");
}
else if (compThrow == 3){
System.out.println ("Computer throws SCISSORS.");
}
if (getPThrow == compThrow){
winner = 3;
}
else if (getPThrow == 1 && compThrow == 3){
winner = 1;
}
else if (getPThrow == 1 && compThrow == 2){
winner = 2;
}
else if (getPThrow == 2 && compThrow == 1){
winner = 1;
}
else if (getPThrow == 2 && compThrow == 3){
winner = 2;
}
else if (getPThrow == 3 && compThrow == 1){
winner = 2;
}
else if (getPThrow == 3 && compThrow == 2){
winner = 1;
}
return winner;
}
//Final Output with imported values of 'rounds' and 'winner'
public int bigWinner (int winner, int rounds){
int tie = 0;
int playerWins = 0;
int compWins = 0;
if (winner == 1){
playerWins = playerWins + 1;
}
else if (winner == 0){
tie = tie + 1;
}
else if (winner == 3){
compWins = compWins + 1;
}
System.out.println ("You win " +playerWins+ ". Computer wins " +(compWins)+ ".");
if (playerWins > compWins){
System.out.print ("You win!");
}
if (playerWins < compWins){
System.out.print ("Computer wins!");
}
if (playerWins == compWins){
System.out.print ("It's a tie!");
}
return tie;
}
}
Player method:
import java.util.*;
public class RPSPlayer {
public void main (String args[]) {
Random generator = new Random ();
Scanner sc = new Scanner(System.in);
}
//This method gets the throw, and loops if throw is not within 1 and 3
public int makeThrow (){
Scanner sc = new Scanner (System.in);
int playerThrow;
do{
System.out.print ("Enter your throw (1=Rock, 2=Paper, 3=Scissors)");
playerThrow = sc.nextInt();
} while (playerThrow > 3 && playerThrow < 1);
return playerThrow;
}
//Accessor method
public int getThrow (int playerThrow){
this.playerThrow = playerThrow;
return playerThrow;
}
}
When I attempt to compile any of the classes, the error refers to code found in the RPSPlayer class:
cannot find symbol - variable playerThrow
As I said before, my knowledge of object-oriented program is very weak. I'm not really sure why I'm getting this error, as int playerThrow is defined right above it. I am also unsure if there are additional flaws or errors within my code. One thing I particularly struggle with is the concept of static vs. non-static code, and when to use which and what can be used within them.
Suggestions are greatly appreciated. Thank you in advance.
You'll need to define the member variable, before you can assign a value to it. That's mandatory (obviously) for every class and every member variable.
Please add this to your class:
private int playerThrow;
Also, the function getThrow makes no sense. Getters return an already set value; setters are the one who actually give a value to your member variables. Do this instead:
public int getThrow()
{
return playerThrow;
}
public void setThrow(int playerThrow)
{
this.playerThrow = playerThrow;
}
Please note that this.playerThrow and playerThrow are not related in any way. this.playerThrow is a member variable of your class (defined as shown above) and playerThrow is a variable given as an argument to your method.
EDIT:
I'm addressing some more of your errors.
The problem you are referring to in your comment is because you are calling a constructor mainRPS while your class is called RPSmain. That's located here RPSMain mainRPS = new mainRPS(); in the RPSGame class, in the start. Please fix this to RPSMain mainRPS = new RPSMain();.
Please define private int round in your RPSMain class. That's the same error as your first one addressed.
Also, define int winner outside the for loop because you're using it outside your loop, as well. When you define a value inside a loop, it will be local to that loop and will get destroyed when the program exits the loop.

Categories

Resources