Java - if statement keeps looping - java

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 ;-)

Related

Can I call the loop methods from outside main function?

import java.util.Scanner; // needed for Scanner Class
public class MyClass
{
public static void main(String[] args)
{
boolean running = true;
GAME:
{
// Create a Scanner object for choice input.
Scanner console = new Scanner(System.in);
String gameName = "The Path";
PATHCHOICES:
while (running)
{
System.out.println("Enter your choice: Left, Right, or Run Away");
String choice = console.nextLine();
//make the do-while statement
do
{
if (choice.equals("Left"))
{
System.out.println("You choose to take the left fork in the road.");
break PATHCHOICES;
}
else if (choice.equals("Right"))
{
System.out.println("You choose to take the right fork in the road.");
break PATHCHOICES;
}
else if (choice.equals("Run Away"))
{
System.out.println("You choose to turn back and return the way you came.");
break PATHCHOICES;
}
else
{
System.out.println("please choose Left, Right, or Run Away");
choice = console.nextLine();
}
} while (choice != "Left" && choice != "Right" && choice != "Run Away");
}
DOORCHOICES:
while (running)
{
System.out.println("Enter your choice: Open The Door, Walk Away From The Door");
String choice = console.nextLine();
do
{
if (choice.equals("Open The Door"))
{
System.out.println("You open the door and walk into the next room.");
break DOORCHOICES;
}
else if (choice.equals("Walk Away From The Door"))
{
System.out.println("You walk away from the door and head back the way you came.");
break DOORCHOICES;
}
else
{
System.out.println("Open the door or Walk Away From The Door");
choice = console.nextLine();
}
} while (choice != "Open The Door" && choice != "Walk Away From The Door");
}
}
System.out.println("tacos");
}
}
Is it possible for me to call these loops methods into play without having to repeatedly type them out (copy paste)? I would like to be able to call the loops from outside the main GAME function if that’s possible. That way I don’t have to copy paste, copy paste, copy paste every time I want to use that same loop. I have both loops named PATHCHOICES AND DOORCHOICES, so if it is possible what syntax would I use?
Yes, it's possible to create methods, in addition to many other improvements you could make. Here's a solution with methods and some improvements.
To start, here's a new method named "promptForDoor" which:
Lines 2-3: define a few strings that you're going to re-use
Line 5: start a loop here, simple "while", repeat forever
Line 6: print the input options (using strings defined from 2-3); also, use "print()" instead of "println()"
Line 9: check if their input matches with the string from Line 2, and use "equalsIgnoreCase()" since it doesn't matter what the user types in ("OPEN THE DOOR" or "open the door" should both work)
Line 10-11: print something informative, then eject from the method altogether by returning "choice"; this also ends the loop
Line 13-15: same logic as 9-11
Line 17: if you make it here, it's because you didn't match on Lines 9 or 13, so just repeat the whole loop again (including the prompt to the user, and reading input)
1 private static String promptForDoor(Scanner scanner) {
2 String openTheDoor = "Open the door";
3 String walkAwayFromTheDoor = "walk away from the door";
4
5 while (true) {
6 System.out.print(openTheDoor + ", or " + walkAwayFromTheDoor + "? ");
7 String choice = scanner.nextLine();
8
9 if (choice.equalsIgnoreCase(openTheDoor)) {
10 System.out.println("You open the door and walk into the next room.");
11 return choice;
12
13 } else if (choice.equalsIgnoreCase(walkAwayFromTheDoor)) {
14 System.out.println("You walk away from the door and head back the way you came.");
15 return choice;
16 }
17 }
18 }
Here's another method to prompt for path, it's the same structure as the other method.
1 private static String promptForPath(Scanner scanner) {
2 String left = "left";
3 String right = "right";
4 String runAway = "run away";
5
6 while (true) {
7 System.out.print(left + ", " + right + ", or " + runAway + "? ");
8 String choice = scanner.nextLine();
9
10 if (choice.equalsIgnoreCase(left)) {
11 System.out.println("You choose to take the left fork in the road.");
12 return choice;
13
14 } else if (choice.equalsIgnoreCase(right)) {
15 System.out.println("You choose to take the right fork in the road.");
16 return choice;
17
18 } else if (choice.equalsIgnoreCase(runAway)) {
19 System.out.println("You choose to turn back and return the way you came.");
20 return choice;
21 }
22 }
23 }
Here's an example to run it:
Scanner scanner = new Scanner(System.in);
String path = promptForPath(scanner);
String door = promptForDoor(scanner);
System.out.println("path: " + path);
System.out.println("door: " + door);
Along with sample input+output – including an uppercase input ("LEFT") which works fine, and an unexpected input ("jjjjj") which resulted in re-prompting the user to enter something valid. Finally, it printed out each of the inputs captured from the user ("LEFT" and "walk away from the door").
left, right, or run away? LEFT
You choose to take the left fork in the road.
Open the door, or walk away from the door? jjjjj
Open the door, or walk away from the door? walk away from the door
You walk away from the door and head back the way you came.
path: LEFT
door: walk away from the door

Stuck While Loop (Java)

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.

Java ArrayList loop issues

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.

Matching user input against a string array in java?

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.

User input from scanner method to array of 5 indexes also gives user ability to delete any index

User input from scanner method to array of 5 indexes also gives user ability to delete any index matching with string from one of the index.
ALL I want to achieve in this is in this while loop I would like to settle city (option 1), which means creating one as you can probably see from my code. This is where user will type any name they like no restrictions. once they settle the city loops starts again. However it does remember that user created a city earlier. I can have upto 5 cities. There is cost associate with settling new city. I know how to do those conditionals. I am just not sure about this string array.
ArrayList or Array class is not allowed.
where as, option 2 I can demolish any of the city i have created by giving user lists of city they have made earlier. I have to keep minimum of at least one city.
IF you are wondering then this is based on Civilization game.
Please ask for clarification as this may not be
straight forward. thanks
while (playing) {
System.out.println("\nPlease make your selection!");
System.out.println("\n1. Settle a City"
+ "\n2. Demolish a City"
+ "\n3. Build Militia"
+ "\n4. Research Technology"
+ "\n5. Attack Enemy City"
+ "\n6. End Turn\n");
String gameChoice = userinput.nextLine();
if (gameChoice.equals("1")) {
System.out.println("\nWhat would you like to"
+ " name your city?");
String cityname = userinput.nextLine();
cityname = cityNames[0];
} else if (gameChoice.equals("2")) {
System.out.println("What city would you like to demolish?");
for (int i = 0; i < 5 ; i++) {
System.out.print(cityNames[i]);
System.out.print("");
}
} else if (gameChoice.equals("3")) {
System.out.println("You have military points");
} else if (gameChoice.equals("4")) {
System.out.println("You have Research Technology points");
} else if (gameChoice.equals("5")) {
System.out.println("You have zero points");
} else {
System.out.println(" Thanks for playing ");
}
playing = false;
}
First, here:
String cityname = userinput.nextLine();
cityname = cityNames[0];
You are assigning cityname to user input and then you are assigning it to something in cityNames array, that doesn't make sense, maybe you pasted wrong or something, but just in case, this should be the other way around, like this:
cityNames[0] = cityname;
You have playing = false at the end so the loop is gonna just end when user types the city name, you need to either remove this playing = false or use continue; after cityNames[0] = cityName;, that's gonna go to the next iteration of a loop, without going all the way down to playing = false.

Categories

Resources