Here in main method I want to call num value from number() and result from finger()
So I can use them in main method by adding:
if (the sum was even) {
print out even if (the user chose evens) { the user wins }
else { the computer wins }
Here is my Game class:
import java.util.*;
public class Game {
public static void main(String[] args) {
number();
finger();
/*
if (the sum was even) {
print out even if (the user chose evens) { the user wins }
else { the computer wins }
*/
}
public static void number() {
Scanner input = new Scanner(System.in);
System.out.print("Lets's play a Game \"Odd and Even\" " +
"\nWhat is your name?\t ");
String name = input.nextLine();
System.out.print("Hi " + name +" Welcome to the Game, Please
choose (O)dds or (E)vens ?");
String num = input.next();
if (num.equalsIgnoreCase("O") || num.equalsIgnoreCase("E")) {
if (num.equalsIgnoreCase("E")) {
System.out.println(name + " has choosen Evens! The computer will be Odds");
} else {
System.out.println(name + " has choosen Odds ! The Computer will be Even");
}
} else {
System.out.println("Please choose the correct one");
}
}
public static void finger() {
Scanner input = new Scanner(System.in);
System.out.print("How many fingers do you put out?\t");
int fing = input.nextInt();
Random ran = new Random();
int computer = ran.nextInt(9);
System.out.println("The Computer plays " + computer);
int result = fing + computer;
System.out.println(fing + " + " + computer + " = " + result);
if (result % 2 == 0) {
System.out.print(" .........is Even!");
} else {
System.out.print("........ is Odd!");
}
}
}
Related
I can't figure out to implement -1 as a sentinel value using a while loop. Note that the program needs to be running all times except when the users enter the value -1 it should stop. Technically the program should stop at any time when the user enters the sentinal value(-1).
import java.util.Scanner;
import java.util.Random;
public class Multi {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int randomOne, randomTwo, product, userInput;
while(true) {
randomOne = Math.abs(rand.nextInt()%10);
randomTwo = Math.abs(rand.nextInt()%10);
product = randomOne * randomTwo;
System.out.println("How much is " + randomOne + " times " + randomTwo
+ "?");
userInput = scan.nextInt();
if (product == userInput) {
System.out.println("Very Good!");
}
else {
while (product != userInput) {
System.out.println("No. Please try again.");
System.out.println("How much is " + randomOne + " times " +
randomTwo + "?");
userInput = scan.nextInt();
if (product == userInput) {
System.out.println("Very Good!");
}
}}
}
}
}
So at all times when we ask input from the user, if they enter -1 the program should stop.
You could check if the value is -1 upon every iteration and then write a break statement, but below is a slightly cleaner implementation.
import java.util.Scanner;
import java.util.Random;
public class Multi {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int randomOne, randomTwo, product, userInput;
boolean playingGame = true;
while (playingGame) {
randomOne = Math.abs(rand.nextInt() % 10);
randomTwo = Math.abs(rand.nextInt() % 10);
product = randomOne * randomTwo;
System.out.println("How much is " + randomOne + " times " + randomTwo + "?");
userInput = scan.nextInt();
while (userInput != -1 && product != userInput) {
System.out.println("No. Please try again.");
System.out.println("How much is " + randomOne + " times " +
randomTwo + "?");
userInput = scan.nextInt();
}
if (product == userInput) {
System.out.println("Very Good!");
} else {
playingGame = false;
}
}
scan.close();
}
}
My only question is in the overview part how can I print out the trailers rental name correctly? like this:
sample
But my overview code not exactly working as I want. What is the problem?
(I understand the counting in an array starting from zero)
import java.util.Scanner;
public class TrailerRental {
Scanner kb=new Scanner(System.in);
int weightSmall=750;
int weightLarge=3000;
int smallTrailerCounter =0;
int largeTrailerCounter =0;
String smallClientName;
String largeClientName;
String [] smallTrailersClients=new String[5];
String [] largeTrailersClients= new String[3];
public static void main(String[] args) {
new TrailerRental().run();
}
public void run(){
menu();
int menu=kb.nextInt();
while (menu==1 || menu==2|| menu==3){
if(menu==1){
smallTrailer();
}
if (menu==2){
largeTrailer();
}
if (menu==3){
overView();
}
}
if (menu==9){
System.out.println("Goodbye!");
}
else {
System.out.println("Error, incorrect input try again!");
System.out.println();
run();
}
}
public void overView() {
System.out.println("Overview");
System.out.println();
System.out.println("Rented Small trailers");
int notUsedSmallTrailer=5-smallTrailerCounter;
for (int i=0;i<smallTrailerCounter;i++){
System.out.println("Small trailer " +(i+1) + " :" +smallTrailersClients[i] );
}
System.out.println("There are "+notUsedSmallTrailer+ " out of 5 small trailers still available.");
System.out.println("Rented Large trailers");
int notUsedLargeTrailer=3-largeTrailerCounter;
for(int i=0;i<smallTrailerCounter;i++){
System.out.println("Large trailer " + (i+1) +" : "+largeTrailersClients[i] );
}
System.out.println("There are "+notUsedLargeTrailer+ " out of 3 large trailer still available ");
run();
}
public void largeTrailer() {
if (largeTrailerCounter>=3){
System.out.println("Unfortunately all Small trailers are out");
System.out.println("Would you like to rent a Small trailer instead?(y/n)");
String answer=kb.next();
if (answer.equals("y")){
smallTrailer();
}
if (answer.equals("n")){
run();
}
else {
System.out.println("Incorrect input, return to main menu");
run();
}
} else {
System.out.println("What is your name?");
largeClientName=kb.next();
System.out.println("Is the driver in possession of an E-type drivers license (y/n)?");
String answer=kb.next();
if (answer.equals("n")){
System.out.println("Unfortunately, a large trailer cannot be rented without a E-type drivers license. ");
run();
}
if (answer.equals("y")){
System.out.println("What is the weight of the load (in kg)?");
int weight=kb.nextInt();
if (weight<=weightLarge){
largeTrailerCounter++;
largeTrailersClients[largeTrailerCounter]=largeClientName;
run();
}
if (weight>weightLarge){
int difference=weight-weightLarge;
System.out.println("Warning! the maximum load "+weightLarge+" kg is exceeded by " +difference+ "kg" );
System.out.println("Are you sure you want to rent a trailer?(y/n)?");
String answer2=kb.next();
if (answer2.equals("n")){
run();
}
if (answer2.equals("y")){
largeTrailerCounter++;
largeTrailersClients[largeTrailerCounter]=largeClientName;
run();
}
else {
System.out.println("incorrect input,return to menu");
run();
}
}
}
}
}
public void smallTrailer() {
if (smallTrailerCounter>=5) {
System.out.println("Unfortunately all Small trailers are out");
run();
} else {
System.out.println("What is the customer last name?");
smallClientName = kb.next();
System.out.println("What is the weight of the load (in kg) ?");
int weight = kb.nextInt();
if (weight<=weightSmall){
smallTrailerCounter++;
smallTrailersClients[smallTrailerCounter]=smallClientName;
run();
}
if (weight > weightSmall) {
int difference = weight - weightSmall;
System.out.println("Warning the maximum load " + weightSmall + " kg is exceeded by " + difference + " kg!");
System.out.print("Are you sure you want to rent the small trailer? (y/n)");
String answer = kb.next();
if (answer.equals("n")) {
run();
}
if (answer.equals("y")) {
smallTrailerCounter++;
smallTrailersClients[smallTrailerCounter]=smallClientName;
run();
}
while (answer != "y" || answer != "n") {
System.out.print("Are you sure you want to rent the small trailer? (y/n)");
answer = kb.next();
if (answer.equals("n")) {
run();
}
if (answer.equals("y")) {
run();
}
}
}
}
}
public void menu() {
System.out.println("***********************");
System.out.println("* Trailer rental ");
System.out.println("***********************");
System.out.println("* 1) Rent small trailer");
System.out.println("* 2) Rent large trailer");
System.out.println("* 3) Overview ");
System.out.println("* 9) Exit ");
System.out.println("***********************");
System.out.print("Select an option:");
}
}
You didn't add 1 to your smallTrailersClients[i] or largeTrailersClients[i]. You are referencing i + 1 in your for loop. The same will be needed to reference the correct name associated. Try this instead:
public void overView() {
System.out.println("Overview");
System.out.println();
System.out.println("Rented Small trailers");
int notUsedSmallTrailer=5-smallTrailerCounter;
for (int i=0;i<smallTrailerCounter;i++){
System.out.println("Small trailer " +(i+1) + " :" +smallTrailersClients[i+1] );
}
System.out.println("There are "+notUsedSmallTrailer+ " out of 5 small trailers still available.");
System.out.println("Rented Large trailers");
int notUsedLargeTrailer=3-largeTrailerCounter;
for(int i=0;i<smallTrailerCounter;i++){
System.out.println("Large trailer " + (i+1) +" : "+largeTrailersClients[i+1] );
}
System.out.println("There are "+notUsedLargeTrailer+ " out of 3 large trailer still available ");
run();
}
I have been asked to :
Create an EntertainmentRobot object and a HumanStudyRobot object (using the data previously
given) and store these objects in an array list.
Set the purpose of each robot in the array using the data previously outlined in this paper.
Print the details of each robot using the toString method.
I have did this and my code is below. But when I run the code, The details of each robot added to my arrayList are printed twice each. Any idea how I can fix it so that the details of each robot object in the array list only prints once? many thanks
package Program;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester04 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Robot> Robots = new ArrayList<Robot>();
HumanStudyRobot HumanStudyRobot1 = new HumanStudyRobot("HRP", 1.5, 58.0, "Kawada Industries");
HumanStudyRobot1.setPurpose("Study into human movement and perform a wide range of tasks.");
EntertainmentRobot EntertainmentRobot1 = new EntertainmentRobot("QRIO", 0.6, 7.3, "SONY");
EntertainmentRobot1.setPurpose("To live with you, make life fun and make you happy.");
Robots.add(EntertainmentRobot1);
Robots.add(HumanStudyRobot1);
for (Robot eachRobot : Robots) { //for loop to go through the array list
System.out.println(Robots.toString());
System.out.println("\n");
}
startRobot(Robots, input);
}
public static void startRobot(ArrayList<Robot> Robots, Scanner input){
for( int i = 0 ; i < Robots.size(); i++ ) {
Robots.get(i).start();
Robots.get(i).doTask();
Robots.get(i).doTask(input);
Robots.get(i).stop();
}
}
}
package Program;
import java.util.Scanner;
import org.omg.Messaging.SyncScopeHelper;
public class EntertainmentRobot extends Robot {
//constructor
public EntertainmentRobot(String name, double height, double weight, String manufacturer) {
super(name, height, weight, manufacturer);
this.energy = 10.0;
this.EnergyUnitsRequired = 0.75;
}
#Override
public void start() {
System.out.println("This is an Entertainment Robot. \nThe robot has started entertaining.");
}
#Override
public void stop() {
System.out.println("I have stopped entertaining people.");
System.out.println("--------------------------------------------------");
}
#Override
public void doTask(Scanner input) {
play();
talk();
walk();
}
#Override
public void doTask() {
// TODO Auto-generated method stub
}
public void talk() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a phrase for me to repeat");
String phrase = input.nextLine();
System.out.println("You have asked me to say the following phrase : " + phrase);
}
public void walk() {
Scanner input = new Scanner (System.in);
System.out.println("Would you like me to walk for you?");
if (input.nextLine().equalsIgnoreCase("Y")) {
System.out.println("For how many paces? ");
int steps = input.nextInt();
input.nextLine();
System.out.println("Which direction do you want me to walk? (Enter a number between 1 and 4.) ");
System.out.println("1 - " + Directions.FORWARD);
System.out.println("2 - " + Directions.BACKWARD);
System.out.println("3 - " + Directions.LEFT);
System.out.println("4 - " + Directions.RIGHT);
int selection = input.nextInt();
if (selection == 1 ) {
setDirection(Directions.FORWARD);
} else
if (selection == 2 ) {
setDirection(Directions.BACKWARD);
} else
if (selection == 3 ) {
setDirection(Directions.LEFT);
} else
if
(selection == 4 ) {
setDirection(Directions.RIGHT);
}
//output
System.out.println("I have walked " + getDirection() + " " + steps + " steps.");
}
else if (input.nextLine().equalsIgnoreCase("N")) {
System.out.println("Exitting the system.");
System.exit(0);
}
}
public void play () {
Scanner input = new Scanner(System.in);
boolean valid = false;
int selection;
do {
System.out.println("How many times would you like to play?");
while (!input.hasNextInt()) {
System.out.println("That is not a number");
input.nextLine();
}
selection = input.nextInt();
valid = true;
} while(!valid);
for (int i = 1; i < selection + 1; i ++ ) {
if (getEnergy() >= energyRequired()) {
energyConsumption();
} else if (getEnergy() < energyRequired()) {
System.out.println("------------WHOOPS--------------.");
System.out.println("I do not have enough energy to play.");
regenerate();
}
}
//input.close();
}
public String toString() {
return "---------------------------------\nI AM AN ENTERTAINMENT ROBOT \nThe details of the entertainment robot are below: \n" +
"Name : " + getName() + "\nWeight: " + getWeight() + "\nHeight: " + getHeight() + "\nManufacturer: " +
getManufacturer() + "\nPurpose: " + getPurpose() + "\n----------------------------";
}
}
package Program;
import java.util.Scanner;
public class HumanStudyRobot extends Robot {
//instance variables
public HumanStudyRobot(String name, double height, double weight, String manufacturer) {
super(name, height, weight, manufacturer);
this.energy = 30.0;
}
#Override
public void start() {
System.out.println("This is a Human Study Robot");
System.out.println("The robot has started studying.");
}
#Override
public void stop() {
System.out.println("The robot has finished studying.");
}
#Override
public void doTask() {
study();
walk();
}
#Override
public void doTask(Scanner input) {
// TODO Auto-generated method stub
}
public void study() {
if (energy >= energyRequired()) {
energyConsumption();
}
else
if (energy < energyRequired()) {
System.out.println("The robot does not have sufficient energy.");
regenerate();
System.out.println("................");
System.out.println("The robot has finished regenerating");
}
}
public String toString() {
return "I AM A HUMAN STUDY ROBOT : \nThe details of the human study robot are below:\n"
+ "Name : " + getName() + "\nWeight: " + getWeight() + "\nHeight: "
+ getHeight() + "\nManufacturer : " + getManufacturer() + "\nPurpose : "
+ getPurpose();
}
public void walk() {
int steps;
boolean valid = false;
Scanner input = new Scanner(System.in);
System.out.println("Would you like me to walk for you?");
if (input.nextLine().equalsIgnoreCase("Y")){
do {
System.out.println("I can only walk 10 paces at a time");
System.out.println("For how many paces? ( Enter a no. between 1 and 10 )");
while (!input.hasNextInt()) {
System.out.println("That is not a number");
input.nextLine();
}
steps = input.nextInt();
valid = true;
} while(steps < 0 || steps > 10);
System.out.println("Which direction do you want me to walk? ( Enter a number between 1 and 4, the options are below.");
System.out.println("1 - " + Directions.FORWARD);
System.out.println("2 - " + Directions.BACKWARD);
System.out.println("3 - " + Directions.LEFT);
System.out.println("4 - " + Directions.RIGHT);
int selection = input.nextInt();
if (selection == 1 ) {
setDirection(Directions.FORWARD);
} else if (selection == 2 ) {
setDirection(Directions.BACKWARD);
} else if (selection == 3 ) {
setDirection(Directions.LEFT);
} else if (selection == 4 ) {
setDirection(Directions.RIGHT);
}
else System.out.println("That is not a valid selection.");
System.out.println("I have walked " + getDirection() + " " + steps + " steps");
}
}
}
You did'nt write the foreach loop in a right way ...
for (Robot eachRobot : Robots) { //for loop to go through the array list
System.out.println(Robots.toString());
System.out.println("\n");
}
And this will print the whole list elements as :
ArrayList<Integer>lists=new ArrayList<Integer>();
lists.add(new Integer(50));
lists.add(new Integer(70));
for (Integer integer : lists) {
System.out.println(lists.toString());
}
will print :
[50, 70]
[50, 70]
So change the loop to print each element toString function It should written like :
for (Robot eachRobot : Robots) { //for loop to go through the array list
System.out.println(eachRobot .toString()+"\n");
// println is already print new line for you if you want to print two lines you can use that instead.
}
Rewrite the loop and test ..
I am trying to create a simple Pig game.. The problem that i have is that the program terminates.
For example, when i run it, entering two players and two names works perfectly, and so does the first round.. as soon as i enter n, and the turn goes to player 2, the program just stops.. I would like it to continue until the score is reached..
Below is my code.. I would appreciate ANY help.. I am totally lost on this one..
And yes... I am a beginner..
Thank you!!
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class PigGame {
public static void main(String[] args) {
ArrayList<Player> users = initialize();
for (Player p : users) {
System.out.println(p.getNick() + "'s turn!");
System.out.println("Your score is: " + p.getScoreTotal() + "!");
takeTurn(p);
if (p.getScoreTotal() >= 100) {
System.out.println(p.getNick() + "wins! Congratulations");
return;
}
}
}
private static ArrayList<Player> initialize() {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Pig!");
System.out.println("How many will play the game?");
int qusers = sc.nextInt();
sc.nextLine();
ArrayList<Player> users = new ArrayList();
for (int i = 1; i <= qusers; i++)
{
System.out.println("Enter the name of player " + i + ":");
users.add(new Player(sc.nextLine(), 1, 6));
}
return users;
}
private static void takeTurn(Player p) {
String input = "";
int currentScore = 0;
Scanner sc = new Scanner(System.in);
do {
p.rollDice();
currentScore += p.getDieWorth();
System.out.println(p.getNick() + "'s dice rolled " + p.getDieWorth());
if (p.getDieWorth() != 1) {
System.out.println("Your score is: " + currentScore + " for this round.");
System.out.println("Do you want to roll again? (j/n)");
input = sc.nextLine();
} else {
System.out.println("Sorry");
currentScore = 0;
}
}
while ((input.equals("j")) && (p.getDieWorth() != 1));
p.increaseScore(currentScore);
}
}
Here's your code.
for (Player p : users) {
System.out.println(p.getNick() + "'s turn!");
System.out.println("Your score is: " + p.getScoreTotal() + "!");
takeTurn(p);
if (p.getScoreTotal() >= 100) {
System.out.println(p.getNick() + "wins! Congratulations");
return;
}
}
This only goes through the users once. for goes through each user and then it's done. You need a while loop.
//this is somewhat messy, but it gets the point across
Player p = users.get(0);
int playerIndex = users.size();
while(p.getScoreTotal() < 100) {
if(playerIndex == users.size()) {
playerIndex = 0;
}
p = users.get(playerIndex);
playerIndex++;
System.out.println(p.getNick() + "'s turn!");
System.out.println("Your score is: " + p.getScoreTotal() + "!");
takeTurn(p);
}
System.out.println(p.getNick() + "wins! Congratulations");
return;
/hello, I am trying to learn how to use "break" commend in java as well as continuing loop with "y or n" choice. I am writing this game Guessing Number and I have some trouble with "y" choice. I will try to explain, to write a game of guessing number was easy so I started to add some conditions like the possibility on the and to play again or not, later I was thinking that would be more interesting if I add possibility to quit any time player wish, but that does not working correctly. Please help, thats my code
package guessinggame;
import java.util.Random;
import java.util.Scanner;
/**
*
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
}
}
Here is an alternative that achieves that same outcome
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
int guess = 0;
int number_of_tries = 0;
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
guess = input.nextInt(); //get first input
while (guess != -1)
{
int number_guess = rand.nextInt(5) + 1;
++number_of_tries;
//check if user wins and exits loop
if (isWin (number_guess,guess))
{
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? [1 yes/ -1 no]: ");
guess = input.nextInt();
if (guess == -1)
break;
else
System.out.println(" Try too guess a number between 1 and 100 -1 to close");
}
else if (number_guess < guess )
{
System.out.println(" Guess is too High " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
else if (number_guess > guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or -1 to quit ");
guess = input.nextInt();
continue;
}
}
System.out.println ("bye bye");
}
public static boolean isWin (int number,int guess)
{
return (number == guess) ? true :false;
}
}
You forgot to wait for user input after this statement:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
E.g. you could try next approach:
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (input.hasNext()) {
if (another.equalsIgnoreCase("y")) {
play_again = true;
input.next();
} else {
play_again = false;
}
}
It looks like your braces are messed up for your play again if statement
This will work.
package aa;
import java.util.Random;
import java.util.Scanner;
public class abc {
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
break;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
input.next();
if (win == true){
System.out.println(" You Win!!! ");
}
else{
System.out.println(" Good Luck Next Time!!! ");
System.out.println(" The number was " + number_guess);
}
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
another = input.next();
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
System.out.println("Thank you!!!");
}
}