Beginning Java: Utilizing user's input - java

I am new to learning Java and in my class i have an assignment ive been struggling with:
You need to create three classes: Duck, Dog, and DuckDogApp. DuckDogApp would use Duck and Dog objects. You may use three separate different files or just one file to contain three classes. Your program:
1.Prompt a user to input “duck” or “dog” from keyboard (ask a question)
The output should display “Quack! Quack!” if the user’s input is “duck”, and followed by a new question “dog or duck?” and give a program to end the program
If the user chooses to end the program, then game is over. If the user’s input is “dog”, next prompt should be: “what size is your dog?”
if the user’s input is negative or 0, the program would tell the user to enter a correct number:
once the user typed in a number and hit enter:
-the output should be “Yip! Yip! Yip!” if the number is between 1 and 14;
-the output should be “Ruff! Ruff! Ruff!” if the number is between 15 and 59;
-the output should be “Woof! Woof! Woof!” if the number is more than 60.
End of the program
If the user input is “dog”, output should follow the step 2.
I am having difficulties understanding what to do next or if what i have is even right. I dont know how to go about utilizing the users input from "what size is your dog" to the bark. This is my first Java class so again, im new- any tips would be greatly appreciated- im having difficulties getting the hang of it. So far this is my code:
import java.util.*;
class Duck{
}
class Dog{
private int size;
public int getSize(){
return size;
}
public void setSize(int n){
size=n;
}
public void bark(){
if (size>60){
System.out.println("Woof! Woof!");
}
else if (size>14){
System.out.println("Ruff! Ruff!");
}
else{
System.out.println("Yip! Yip!");
}
}
}
class DogDuckApp{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Dog or Duck?");
String userinput = input.nextLine();
/*If user inputs dog (disregarding case) it will ask what size the dog is*/
if("Dog".equalsIgnoreCase(userinput))
{
System.out.println("what size is your dog?")
}
}
/*If user inputs duck (disregarding case) it will display Quack! Quack!*/
if("Duck".equalsIgnoreCase(userinput))
{
System.out.println("Quack! Quack!");
}
}
}

Related

Java Shooting targets

I have been working on this for almost one week. The question is mainly about shooting the target. So we ask the user to input v0, degree, x0, and y0. We will be setting two targets(500,0)&(1000,0).
I think I did all the methods correctly except for the main methos.
The question I am having now is I have no idea about how to put the "return"s back to the main method.(For example, I got the time and I returned it, but how can I output "The time it took to get to the groud is +time+".
It is my first time working with method questions, I would be happy to see some advice!!
Also I've been told to give the user 4 chances to play this game and give the user to choose whether they are going to start again or exit. I saw many people useing boolean to work this part, but I have no idea about how to use it.
The following is what I got so far:
import java.io.*;
public class AngryBirdGame{
public static void main(String[] args) throws IOException{
int vo,degree = 0,xo = 0,yo = 0;
System.out.println("This game is the Angry Bird Game. You will be trying to hit the target.");
System.out.println("One of the targets of the game is (500,0)");
System.out.println("The other target of the game is (1000,0)");
System.out.println("Please enter the initial velocity");
vo=velocity();
System.out.println("Please enter the angle of elevation(0-90 degrees)");
degree=degree(degree);
System.out.println("Please enter the horizontal starting point(50-500)");
xo=horizontal(xo);
System.out.println("Please enter the vertical starting point");
yo=vertical(yo);
result(0);
}
In order to allow the user to play multiple games, you need a loop in your main() method. Also, as a matter of organization, it would be convenient to define a class that encapsulated all the data the user needs to provide to get a game started. (The class AngryBirdGame probably works just fine for that.) You can then extract all the logic for obtaining the user's input into a separate method that returns an instance of the game data class, or null if the user doesn't want to play any more. Similarly, you should define a method that returns the result of the game so you can report the result to the user each time through the loop.
Finally, my guess is that your input variables should be floating point numbers (or maybe even double) rather than int values. It's hard to do trajectory calculations accurately using integer values only.
Putting all that together, here's an outline of what it might look like:
public class AngryBirdGame {
float vo, degree, xo, yo;
public static void main(String[] args) {
printOneTimeIntro();
Scanner in = new Scanner(System.in);
for (int i = 0, AngryBirdGame game = getGameInfo(in);
i < 4 && game != null;
i++, game = getGameInfo()) {
float time = game.play();
System.out.format("The time it took to get to the ground is %f%n", time);
}
}
/**
* A static method to print a one-time introduction to the program.
*/
private static void printOneTimeIntro() {
System.out.println("This game is the Angry Bird Game. You will be trying to hit the target.");
}
/**
* A static method to check whether the user wants to play and, if so,
* to collect all the game info.
*
* #return a game object, or {#code null} if the user no longer wants to play.
*/
private static AngryBirdGame getGameInfo(Scanner in) {
// first check if the user wants to play
System.out.println("Do you want to play (y/n)? ");
String input = in.next();
if (input.toLowerCase().startsWith("n")) {
return null;
}
// if so, create a game object and get all the input
AngryBirdGame game = new AngryBirdGame();
System.out.println("One of the targets of the game is (500,0)");
System.out.println("The other target of the game is (1000,0)");
System.out.println("Please enter the initial velocity");
game.v0 = in.nextFloat();
// TODO: get rest of input
return game;
}
/**
* An instance method that plays the game once everything is initialized.
*
* #return the time it takes for the trajectory to complete
*/
private float play() {
float time;
// TODO: calculate the game time to reach the ground
return time;
}
}
Note that if you want to return more information than just the trajectory time, you might want to define a second class to contain everything you want returned and use that as the return value from play().

Making a program repeat within itself, but you can't make a method(?): Java

I have a project for my computer science class and we're making battleship. Part of the program is that we have make sure that the piece the player puts down does not go off of the board.
I've made a method to check to see whether it goes off the board:
private static boolean test(String s, int row, int column,int spaces)
{
if(s.equals("right")&&column+5<=10)
{
return true;
}
if(s.equals("up")&&row-spaces>=0)
{
return true;
}
if(s.equals("left")&&column-spaces>=0)
{
return true;
}
if(s.equals("Down")&&row+spaces<=10)
{
return true;
}
return false;
}
But once I've gotten it to print out an error message, I'm not sure how to make it so that the program can re-recieve the new position for the piece, without putting an if statement in and if statement in an if statement (and on and on), because you need to check the new position to make sure it doesn't go off of the board.
Here is the part where I get the position of the playing piece (although I don't think you need it)
Scanner sonic= new Scanner(System.in);
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
int beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
int begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
String direction = sonic.next();
And here's one of the if statements that I use to check/place the pieces
if(direction.equals("left")&&test("left",beginrow,begincolumn,5))
{
for(int i = beginrow; i>beginrow-5; i--)
{
battleship[begincolumn-1][i-1] = ('a');
}
}
else if(!test("left",beginrow,begincolumn,5))
{
System.out.println(" ");
System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****");
}
This may be a duplicate, but I didn't know how to reword my search to find what I wanted. (So if anyone could direct me to the right article, that'd be nice as well)
What you should do is split your code appropriately into methods and call that methods repeatedly until your program is satisfied with the outcome.
For example:
create a method startGame() which has the job call methods getting user input until satisfied
make a method to request the user to input all the different ships and other required data
That might look something like
public void startGame() {
// do some setup
while(!requestShipInput()) { // request ship data until the data is valid
System.out.println(" ");
System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****");
}
// do some more ship setup
// get the actual playing started
}
public boolean requestShipInput() {
Scanner sonic= new Scanner(System.in);
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
int beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
int begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
String direction = sonic.next();
if(direction.equals("left")&&test("left",beginrow,begincolumn,5)) {
for(int i = beginrow; i>beginrow-5; i--) {
battleship[begincolumn-1][i-1] = ('a');
}
return true; // valid ship data
}
return false; // invalid ship data
}
As a first step, separate input validation from taking the action based on that input - you already have the validation logic in a separate function, so this is easy. Then figure out what needs to be done in case of invalid input - in your case, you need to ask for new input until you get a valid position:
do {
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
direction = sonic.next();
} while (!test(direction, beginrow, begincolumn, 5))
After that, you know you've got a valid position.
My next step would probably be to group the information required to describe a ship on the board (i.e. beginrow,begincolumn,direction, probably also size) in a separate Object - possibly named Ship.
I think you could pretty naturally use recursion here:
public void getInput() {
// scanner code to get input
if (!test("left",beginrow,begincolumn,5)) { // test failed
getInput()
return
}
// test succeeded, continue
}
You already have something to the limits of you board? If you execute the check first, you don't need to execute a cascade of if-else
if(!test(direction,beginrow,begincolumn,size))
{
System.out.println(" ");
System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****");
} else {
// check for collision with already placed ships
}
Keep in mind that there is a chance to combine up/down and left/right. The calculation rules are nearly the same and you only have to decide if you have to look to the one or the other direction.

Looping through Arrays in Java

I am trying to write a program to simulate an airline reservation system. I an supposed to use an array of type boolean to represent the number of seats. First five seats represent first class and last five represent economy. Initially the program must allow the user to make a choice between first class and economy and then his choice is processed as follows:
A user can only be assigned an empty seat in the class he chooses.
Once a class is full, the user is offered the option to move to the next class
If the user agrees to move to the next class a simple boarding pass is printed.
If the user refuses to move to the next class. The time for the next flight is displayed. i would appreciate help on how to loop through the elements of the array to determine whether its true of false. Also i am trying to display the number of seats available in each class before the user makes a selection this is what i've written so far.. My code is far from complete, i acknowledge that, i am a novice programmer please help. Thank you.
import java.util.Scanner;
public class AirlineReservation
{
private boolean[] seats =; // array to hold seating capacity
private String AirlineName; // name of airline
private int[] counter = new int[5]
// constructor to initialize name and seats
public Airline(String name, boolean[] capacity )
{
AirlineName = name;
seats = capacity;
} // end constructor
// method to set the Airline name
public void setName( String name )
{
AirlineName = name; // store the course name
} // end method setCourseName
// method to retreive the course name
public String getName()
{
return AirlineName;
} // end method getName
// display a welcome message to the Airline user
public void displayMessage()
{
// display welcome message to the user
System.out.printf("Welcome to the Self-Service menu for\n%s!\n\n",
getName() );
} // end method displayMessage
// processUserRequest
public void processUserRequest()
{
// output welcome message
displayMessage();
// call methods statusA and StatusB
System.out.printf("\n%s %d:\n%s %d:\n\n",
"Number of available seats in First class category is:", statusA(),
"Number of available seats in Economy is", statusB() );
// call method choice
choice();
// call method determine availability
availability();
// call method boarding pass
boardingPass();
} // end method processUserRequest
public int statusA()
{
for ( int counter = 0; counter <= (seats.length)/2; counter++ )
} // revisit method
// method to ask users choice
public String choice()
{
System.out.printf(" Enter 0 to select First Class or 1 to select Economy:")
Scanner input = new Scanner( System.in );
boolean choice = input.nextBoolean();
} // end method choice
// method to check availability of user request
public String availability()
{
if ( input == 0)
System.out.printf("You have been assigned seat number \t%d", seats[ counter ]);
else
System.out.printf("You have been assigned seat number \t%d", seats[ counter ]);
}
}
#Anthony : As you are novice, hence please look at following comments :
1. Be specific while asking your question. In this case the question was "how to loop through array!". You posted complete problem statement.
2. Please google it or research it properly on internet if similar question has been asked by anybody before. In this case, similar question can be find here :
Iterate through string array in Java
Because of these reasons people are giving your query downvote!
Now just want to provide answer to your question as you look quite new to programming :
boolean flag[] = {true,false,true,false};
for(int i=0;i<flag.length;i++){
System.out.println(flag[i]);
}
I hope it helps!

Writing a loop that will repeat itself "N" times as decided by the user

I need to write a program for Java that "rolls" two 6-sided die and that keeps track of how many tries it took to roll a 7. The program also needs to run this process N number of times, determined by the user. After the Nth trial, the program needs to compute the average amount of trials it takes to roll a 7.
I'm pretty confident that I should use a while loop inside of a for loop but I'm unsure of exactly how to do it. I already have written the code to a program that "rolls the dice," and is shown below.
import java.util.*;
public class RollDice {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
String input = "";
do {
System.out.println("Rolling the dice...");
System.out.println("You rolled a"+((rand.nextInt(6)+1)+(rand.nextInt(6)+1)));
System.out.println("Roll again? (y/n)");
input = keyboard.next();
} while (input.equalsIgnoreCase("y"));
}
}
Yes, I know it's a do-while loop, but it's all I have so far.
https://codereview.stackexchange.com/questions/31980/a-simple-dice-roll-game
This would be a great place for you to start. Then just add a second die, and a variable for the average. But please do not copy this code directly. Use it as a template/guideline. I want no part in plagiarism.

In Cannot be resolved and MasterMind

Ok, I am having a problem receiving a value... I have been researching for several days, but nothing has hit the topic I need. It is a mastermind game. I am creating this for a Final project in my High School programming class. The Eclipse Compiler is telling me that in cannot be resolved. How do I fix this and Accomplish my goal. This is not being run in an applet.
package masterMind;
import java.util.Scanner;
public class MasterMind {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Change this value to change the game
int m1=2;
int m2 =3;
int m3=2;
int m4=1;
//Create Board
System.out.println("__ __ __ __");
Scanner UserGuess = new Scanner(System.in);
int num = in.nextInt();
I have very limited Coding knowledge, so please keep it simple and explain
System.in is the InputStream of the system (like the cmd for windows) , in order to read from that you use the Scanner or InputStreamReader just like you are trying to do ... so instead of
in.nextInt();
you need
userGuess.nextInt();
and btw learn to use capital letters properly as it will help you later , like userGuess should not start with a capital since its an instance not a class.
anyways , for your game you have to guess 10 times which means you have to repeat the same guessing action 10 times or till the user guesses all the numbers , thats when you should use a while loop like so ....
boolean guessedAll = false;
int guessedCount=0;
int tryCounter=0;
while(tryCounter<9 || !guessedAll){
//read the number from the user and test it ...
//if number equals one of the numbers above then guessedCount++ ...
//if guessedCount==4 then guessedAll=true
tryCounter++;
}
now i almost gave you all of the algorithm needed to do that homework , but i ain't going to solve it for you till you try , else you will learn nothing ;)
you could ofcourse ask for help as comment after you've tried some ... good luck
for nextInt method you should call it from Scanner object
Change this
int num = in.nextInt();
To
int num = UserGuess.nextInt();
You never closed the brackets when you started the class nor when you started the main method. Match every { with a }.
package masterMind;
import java.util.Scanner;
public class MasterMind {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Change this value to change the game
int m1=2;
int m2 =3;
int m3=2;
int m4=1;
//Create Board By randomly generating the number
//After generating the code, print the blank board to start the game
System.out.println("__ __ __ __");
//Take in the user's guess (limit is 10)
int limit = 10
for(int i = 0; i < limit; ++i) {
Scanner UserGuess = new Scanner(System.in);
int num = in.nextInt();
//Other logic..Leaving it for you to attempt
}
}
You want to make a program which the user must guess where each number is in a 4 digit code.. Well how do you do this?
We need the user to be able to input a number, typically the rules of this game are:
There are 6 possible numbers or colors
The code is 4 numbers or colors long
The user has ten tries to guess the code correctly
That means we have to start by doing something like this.
Generate the 4-digit code somehow (with the possible combinations from 0000-6666) and the split the random number put it in an array
Ask the user to enter a number guess along with a position for that number
Keep checking the user guess against the code, each time display the current guesses and which ones they have correct

Categories