I am programming a monopoly-esque game with java on eclipse.
I am currently working on a method that allows players to loop through their own squares and choose which one to develop.
for (int loop2 = 0; loop2 < currentPlayer.getOwnedSquares().size(); loop2++) {
count++;
System.out.println("Would you like to develop this property " + count + ". "
+ currentPlayer.getOwnedSquares().get(loop2).getName() + " (y/n)");
propertyChoice = scanner.nextLine();
if (propertyChoice.equalsIgnoreCase("Y")) {
break;
}else if (propertyChoice.equalsIgnoreCase("N")) {
continue;
}
}
System.out.println("Please choose a development option");
System.out.println("1.Buy a start-up");
System.out.println("2.Buy a global corporation");
int option = scanner.nextInt();
I am unable to get the loop to present only one owned square at a time so the player can choose to select y/n for which one the want to develop. If the player was to pick "N" The loop would then present the next owned property in the array and the player would make another decision and so on..
If the player was to pick "Y" then the loop would break and move on the development options for the chosen owned square.
Any advice on how to realise this would be hugely appreciated.
You have to move the check for user input out of the loop, so the algorithm would look like this:
Print all the owned squares in a loop.
Ask user (outside the loop) which square he wants to develop. For example, a user can simply provide a positional number of a square which you can get by
currentPlayer.getOwnedSquares().get(Integer.valueOf(userInput));
Do whatever you need with selected square.
I just modified the code to test, and it works as you want. I think there is something else problematic which you haven't shared.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int count=0;
String propertyChoice;
Scanner scanner = new Scanner(System.in);
for (int loop2 = 0; loop2 < 5; loop2++) {
count++;
System.out.println("Would you like to develop this property " + count
+ " (y/n)");
propertyChoice = scanner.nextLine();
if (propertyChoice.equalsIgnoreCase("Y")) {
break;
}else if (propertyChoice.equalsIgnoreCase("N")) {
continue;
}
}
System.out.println("Please choose a development option");
System.out.println("1.Buy a start-up");
System.out.println("2.Buy a global corporation");
}
}
Output:
Would you like to develop this property 1 (y/n)
n
Would you like to develop this property 2 (y/n)
n
Would you like to develop this property 3 (y/n)
y
Please choose a development option
1.Buy a start-up
2.Buy a global corporation
Process finished with exit code 0
Try putting scanner.nextLine(); inmediately before propertyChoice = scanner.nextLine();
Edit: if this doesn't work, notice that the else has no brackets surrounding the second if block. I don't know if this will work as I do not see the classes you are refering to and cannot say there is the error. The code you've shown doesn't seem to have any other issue.
Related
all!
I'm a university freshman computer science major taking a programming course. While doing a homework question, I got stuck on a certain part of my code. Please be kind, as this is my first semester and we've only been doing Java for 3 weeks.
For context, my assignment is:
"Create a program that will ask the user to enter their name and to enter the number of steps they walked in a day. Then ask them if they want to continue. If the answer is "yes" ask them to enter another number of steps walked. Ask them again if they want to continue. If they type anything besides "yes" you should end the program by telling them "goodbye, [NAME]" and the sum of the number of steps that they have entered."
For the life of me, I can not get the while loop to end. It's ignoring the condition that I (probably in an incorrect way) set.
Can you please help me and tell me what I'm doing wrong?
import java.util.Scanner;
public class StepCounter
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
final String SENTINEL = "No";
String userName = "";
String moreNum = "";
int numStep = 0;
int totalStep = 0;
boolean done = false;
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
// Prompt for the user's name
System.out.print("Please enter your name: ");
userName = in.nextLine();
while(!done)
{
// Prompt for the number of steps taken
System.out.print("Please enter the number of steps you have taken: ");
// Read the value for the number of steps
numStep = in.nextInt();
// Prompt the user if they want to continue
System.out.print("Would you like to continue? Type Yes/No: ");
// Read if they want to continue
moreNum = in2.nextLine();
// Check for the Sentinel
if(moreNum != SENTINEL)
{
// add the running total of steps to the new value of steps
totalStep += numStep;
}
else
{
done = true;
// display results
System.out.println("Goodbye, " + userName + ". The total number of steps you entered is + " + totalStep + ".");
}
}
}
}
To compare the contents of String objects you should use compareTo function.
moreNum.compareTo(SENTINEL) return 0 if they are equal.
== operator is used to check whether they are referring to same object or not.
one more issue with addition of steps, addition should be done in case of "No" entered also
Use
if(!moreNum.equals(SENTINEL))
Instead of
if(moreNum != SENTINEL)
Also, make sure to add: totalStep += numStep; into your else statement so your program will actually add the steps together.
I'm trying to create a bootleg pokemon game but this scanner isn't working.
JavaBattle object is instantiated inside of driver. Everything works in the driver, but this code doesn't. "Cyclone", "Tornado Spin", "Thermal" and "Huff 'n Puff" all should work but don't on the first try.
I don't really know what I should do.
import java.util.*;
public class JavaBattle{
private int opponentHealth;
public void fight(){
opponentHealth = 100;
Scanner attackchoice = new Scanner(System.in);
System.out.println("Attacks:\nCylcone\nTornado Spin\nThermal\nHuff 'n Puff");
System.out.println("Choose One:");
String ability = attackchoice.nextLine();
if(!ability.equals("Cyclone")||!ability.equals("Tornado
Spin")||!ability.equals("Thermal")||!ability.equals("Huff 'n Puff")){
System.out.println("Not available. Please Try Again.");
System.out.println("Attacks:\nCylcone\nTornado Spin\nThermal\nHuff 'n Puff");
System.out.println("Choose One: ");
ability = attackchoice.nextLine();
}
int randAttackDamage = (int)(Math.random()*16)+15;
int randOpponentAttack = (int)(Math.random()*21)+10;
System.out.println(ability + " was used." + "("+randAttackDamage+")");
opponentHealth = opponentHealth - randAttackDamage;
System.out.println("Opponents Current Health: " + opponentHealth);
}
}
You need to replace your logical OR operators || with AND operators &&. With the code you have, your if clause is only true if ability is all four of the abilities at once. You want to check if the ability is none of the available abilities.
I am incredibly new to java and have been given the following task:
Write a Java Program to prompt a user for a 3 letter body part name which has to be in the 'official' list of 3 letter body parts. (Arm, Ear, Eye, Gum, Hip, Jaw, Leg, Lip, Rib, Toe)
If a user makes a guess correctly then display the correct guess as part of a list.
Allow the user to keep guessing until they have all 10.
If a body part is incorrect then display an appropriate message.
Display the number of guesses they have made including
the correct ones.
The advice given was to use Arrays and Collections as well as Exception Handling where appropriate but I don't know where to go from what I've coded so far. Any help would be appreciated so much, thank you.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] bodyparts = new String [10];
bodyparts[0] = "Arm";
bodyparts[1] = "Ear";
bodyparts[2] = "Eye";
bodyparts[3] = "Gum";
bodyparts[4] = "Hip";
bodyparts[5] = "Jaw";
bodyparts[6] = "Leg";
bodyparts[7] = "Lip";
bodyparts[8] = "Rib";
bodyparts[9] = "Toe";
Set<String> bodypartSet = new TreeSet<>();
Collections.addAll(bodypartSet, bodyparts);
System.out.println("Please enter a 3 letter body part: ");
String bodypart = input.nextLine();
if (bodypartSet.contains(bodypart)) {
System.out.println("Correct, " + bodypart + " is on the list!");
} else {
System.out.println("Nope, try again!");
}
}
There are a lot of way to do this. The following, isn't the best or the most efficient, but it should work...
First of all, you have to put your "official" list in a structure, like an array:
private static String[] offList={Arm, Ear, Eye, Gum, Hip, Jaw, Leg, Lip, Rib, Toe};
Now you have to write a method that can find a world in that "offList", like that:
private static boolean find(String word){
for( int i=0; i<offList.length; i++){
if(word.equals(offList[i])) //if "word" is in offList
return true;
}
return false;
}
Now, let's create this guessing game GUI:
public static void main(String[] args){
LinkedList<String> guessed=new LinkedList<>();
String s;
Scanner input = new Scanner(System.in);
while(guessed.size()<offList.length){
System.out.println("Guessed= "+guessed.toString()); //you have to change it, if you want a better look
System.out.print("Try:");
s=input.nextLine();
/*Here we ask to the user the same thing, unless the guessed list
contains all the words of offList.
Every time we print the guessed worlds list*/
if(find(s)){
System.out.println("This world is in offList!");
if(!guessed.contains(s)) //the world is counted only one time!
guessed.add(s);
}else
System.out.println("Sorry...");
}
System.out.println("The complete list is "+guessed.toString());
}
If you want to show this game in a window, you should have to study some Java Swing classes.
EDIT: I post my answer before the main post editing. First of all you have to understand the Collections advantages and usage... When you know all the LinkedList methods, for example, this assignment looks like a joke! ;)
You need a loop for that, otherwise it will only ask for input once.
Something like this should do:
ArrayList<String> bodyParts = new ArrayList<String>();
bodyParts.add("Arm");
bodyParts.add("Ear");
bodyParts.add("Eye");
bodyParts.add("Gum");
bodyParts.add("Hip");
bodyParts.add("Jaw");
bodyParts.add("Leg");
bodyParts.add("Lip");
bodyParts.add("Rib");
bodyParts.add("Toe");
String input = "";
int totalGuesses = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Start guessing...");
while (!bodyParts.isEmpty()) {
totalGuesses++;
input = sc.nextLine();
if (input.length() != 3 || !bodyParts.contains(input)) {
// incorrect, do nothing
System.out.println("Nope.");
} else {
// correct, remove entry
bodyParts.remove(input);
System.out.println("Correct! " + (10 - bodyParts.size()) + " correct guess" + ((10 - bodyParts.size()) != 1 ? "es" : ""));
}
}
System.out.println("Done. You have found them all after " + totalGuesses + " guesses.");
sc.close();
Also, this is case sensitive. It will not find Arm when typing arm. And if you need the number of all guesses you can simply add an int before the loop and increase it inside.
The result of my example:
Start guessing...
arm
Nope.
Arm
Correct! 1 correct guess
Arm
Nope.
Ear
Correct! 2 correct guesses
Eye
Correct! 3 correct guesses
(...)
Rib
Correct! 9 correct guesses
Toe
Correct! 10 correct guesses
Done. You have found them all after 12 guesses.
I'm currently working on an assignment for school and I am almost done but I just have one large problem I need to fix before I can add the final bit.
I need to create a program that prompts you to enter either 1 or 2, Afterwards it asks you to enter three words/names and saves them into an array.
Then, depending on whether you picked 1 or 2, it prints them in alphabetical order or flips around the lowercase and uppercase letters. I didn't add that part yet because I'm trying to fix a problem related to the very first input.
When you input a number other than 1 or 2, I am instructed to display an error message and ask for input again. I am pretty sure what I need to do is get the entire program to go back to the beginning because copy/pasting the entire program again would be bad, lol
A big problem is probably that I'm using if/else statements with for loops inside when I might need to put the entire thing inside a loop? But I'm not sure what condition I would use to start the loop if I put the entire code in it. I must be missing something here.
With what I have now, it gets stuck saying invalid input even if you put in a 1 or 2.
import java.util.Scanner;
public class IsabellaPiantoniLab5 {
public static void main (String[]args) {
//Ask for input
Scanner input = new Scanner(System.in);
System.out.print("Please choose either a number 1 or number 2.");
int numChoice = input.nextInt();
//if choice is 1 or 2
if (numChoice == 1 || numChoice == 2) {
System.out.println("Please enter three names: ");
String nameInput[] = new String[4];
//input loop
for (int i= 0; i < nameInput.length; i++) {
nameInput[i] = input.nextLine();
}
System.out.println("Values are:");
//display values if 1
if (numChoice == 1) {
for (int i=1; i<4; i++) {
System.out.println(nameInput[i]);
}
}
//display values if 2
else if (numChoice == 2) {
for (int i=1; i<4; i++) {
System.out.println(nameInput[i]);
}
}
}
//retry if invalid------i restart from the beginning if this happens
else if (numChoice != 1 || numChoice != 2) {
System.out.println("Invalid value. Please try again.");
//continue;
}
}
}
System.exit(0);
This will terminate the app, thus you can start it again using command line ( START [your app path])
Or
RunTime.getRuntime().exec(“Your app”);
System.exit(0);
Edit I misunderstood the question, I thought you wanted to restart the whole app
After discussing the approach with #csm_dev
It is way either to ask for the user input one more time by emptying the field and showing a message “please enter a valid input” with a clarification message
I'm having a little problem with getting my if statement to work. The scenario is that the user should be able enter 1 if they want British teams or 2 if they want American teams. Once they pick a region a list of teams will appear and they enter the number of team and the information of that team should print out but for some reason it just keeps looping and asks to enter a team. I have simplified my code slightly for here otherwise it would be too big.
ArrayList<STeam> teams = rCSV.readSTeams("sports-teams.csv");
Scanner UInput = new Scanner(System.in);
System.out.println("Enter 1 for British teams or 2 for American teams");
int choice = UInput.nextInt();
for (STeams st1 : teams) {
if (choice == 1) {
System.out.println("Choose: 1. London FC");
int choice2 = UInput.nextInt();
{
if (choice2 == 1) {
if (st1.getName().equals("London FC")) {
System.out.println(st1);
}
}
}
}
else if (choice == 2) {
System.out.println("test");
}
}
Apologies if this is extremely messy.
I have a separate class that reads the file and a separate class for the sports teams and I know these work as I have done something similar like this but with only using 1 if statement within another instead of 2.
choice is never updated in your for loop.
You probably want to do:
for (STeams st1 : teams) {
int choice = UInput.nextInt();
if(choice == 1) {
// ...
}
Hey Looks like you are running loop without any condition. So it will run till there are tokens in your teams. You need to use break once you are done with your selection.
You are using this for (STeams st1: teams) which might be a left over code. Since it has no brackets the for will continuously loop over this.
EDIT: Ok, you probably want something like this:
ArrayList britishTeams = rCSV.readSTeams("sports-teams.csv");
Scanner UInput = new Scanner(System.in);
System.out.println("Enter 1 for British teams or 2 for American teams");
int choice = UInput.nextInt();
if (choice == 1)
{
for(int option = 0; option<britishTeams.size; option++)
System.out.println("Option " + option + ": " + britishTeams.get(option).name);
int choice2 = UInput.nextInt();
System.out.println("You chose: " + britishTeams.get(choice2).name);
}
To add the american team, DONT copy/paste this all over again, make the code that takes a list of teams and chooses one a method ;-)