loops in switch statements

how do you do a loop within a switch statement, can it be done?

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 5015 Views - Last Post: 17 April 2008 - 08:18 PM Rate Topic: -----

#1 scholio  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 11-February 08

loops in switch statements

Post icon  Posted 15 April 2008 - 06:35 PM

hi all

i am working on a project that involves asking the user for a player's name, and then prompts them yes or no if they have more names to enter, i used a switch statement to handle the yes/no input from the user.

i would like to have loop within the switch statement that would allow me to ask for the next name, ask again if there are more names and then repeat the cycle until the user chooses no.

how would i do so?


  

switch (names)
			{
				case 'Y':case 'y': //yes
						 
						System.out.println("Next player's name?... " + scan.nextLine());
						System.out.println("New player is: " + scan.next());
						System.out.println("");
						System.out.println("More players? Y/N... ");  //* i would like the loop here *//
						
						break;
				case 'N':case 'n':  //no
						System.out.println("You chose NO, program terminated.");
						break;
				default:			//exit program
						System.out.println("Not a choice, program terminated.");





if what i want to do can't be done using a switch statement what would be the best approach? tips greatly appreciated.


thanks all

Is This A Good Question/Topic? 0
  • +

Replies To: loops in switch statements

#2 capty99  Icon User is offline

  • i am colt mccoy
  • member icon

Reputation: 98
  • View blog
  • Posts: 10,081
  • Joined: 26-April 01

Re: loops in switch statements

Posted 15 April 2008 - 07:14 PM

i'm sure it can be done but i would just do a simple if

if yes then ....
else ...

This post has been edited by capty99: 15 April 2008 - 07:14 PM

Was This Post Helpful? 0
  • +
  • -

#3 spullen  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 10
  • View blog
  • Posts: 356
  • Joined: 22-March 07

Re: loops in switch statements

Posted 15 April 2008 - 07:15 PM

you could just do a while loop that checks the case.
while(str != "n" || str != "n"){
  //get more names
}


Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8342
  • View blog
  • Posts: 31,880
  • Joined: 06-March 08

Re: loops in switch statements

Posted 15 April 2008 - 07:29 PM

View Postscholio, on 15 Apr, 2008 - 06:35 PM, said:

hi all

i am working on a project that involves asking the user for a player's name, and then prompts them yes or no if they have more names to enter, i used a switch statement to handle the yes/no input from the user.

i would like to have loop within the switch statement that would allow me to ask for the next name, ask again if there are more names and then repeat the cycle until the user chooses no.

how would i do so?


No problem of having a loop inside of a switch statement... but even without the loop you have a logic problem here...

  

switch (names)
{



I presume "names" is a char. Better to call it "answer" will be less confusing.

   case 'Y':case 'y': //yes
						 
	System.out.println("Next player's name?... " + scan.nextLine());
	System.out.println("New player is: " + scan.next());
	System.out.println("");
	System.out.println("More players? Y/N... ");  //* i would like the loop here *//
	break;



Now
You display the name of the new player got by scan.next() but you don't store this new player name's now where.... you will have to build an array to get all the new players name.

then you can do
String ans = scan.next();
while(ans.equalsIgnoreCase("Y")) {
// get other players name
}

as your switch is useless... or you get "Y" and you prompt for players or whatever else you have
"N" or anything else you exit there is no point of having a switch statement

just

String answer = scan.next();
while(answer.equalsIgnoreCase("Y") {
... get
... players
answer = scan.next();
}

This post has been edited by pbl: 15 April 2008 - 07:32 PM

Was This Post Helpful? 0
  • +
  • -

#5 scholio  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 11-February 08

Re: loops in switch statements

Posted 16 April 2008 - 09:21 AM

thanks pbl

could you explain by what you mean by my switch statement being of no use.

also, how would i store the names into an ArrayList within the while loop?

cheers
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8342
  • View blog
  • Posts: 31,880
  • Joined: 06-March 08

Re: loops in switch statements

Posted 16 April 2008 - 09:58 AM

Quote

could you explain by what you mean by my switch statement being of no use.


switch statement if when you have multiple choices.
here you have only 2 choices:
- "Y" (or "y") enter a new name
- "N" (or "n") or anything else you exit

[/quote]
also, how would i store the names into an ArrayList within the while loop?
[/quote]

ArrayList<String> list = new ArrayList<String>();
do {
   System.out.print("Enter player name (empty line to exit)";
   String name = scan.next().trim();
   if(name.length > 0)
	  list.add(name);
   while(name.length() > 0);


Was This Post Helpful? 0
  • +
  • -

#7 scholio  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 11-February 08

Re: loops in switch statements

Posted 16 April 2008 - 10:40 AM

thanks pbl, i will look into that when i get to that step, i am having some issues with the while loop


System.out.println("More players? Y/N ...");
		String reply = scan.next();
	//	while (reply.equalsIgnoreCase("Y")); 
		
		do
		{
			System.out.println("Please enter next name: " );
			scan.nextLine();
			String name = scan.nextLine();
			
			System.out.println("");
			System.out.println("More players? Y/N...");
		}
			while(reply.equalsIgnoreCase("Y")); 



in the current state of the loop, it seems the while statement is not being run, what i think i need to do is just have infinite loop that would ask whether there are any more names and exist once the exit conditions are entered.

what is wrong with my loop? pbl, i tried your suggestion of justing using the while statement to handle to 'y'
but it wasn't doing what i wanted, so i tried a do-while which isnt working either.

thanks
Was This Post Helpful? 0
  • +
  • -

#8 gl3thr0  Icon User is offline

  • D.I.C Regular

Reputation: 19
  • View blog
  • Posts: 319
  • Joined: 27-October 07

Re: loops in switch statements

Posted 16 April 2008 - 11:07 AM

hehe ur going to haaate this u jus put the line String reply = scan.next(); in the wrong place. move it inside the loop and then ur code will be run..

but ull find that after the user says no it will still run 1 more time. this is because of the do-while. so jus use a while loop again.
Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8342
  • View blog
  • Posts: 31,880
  • Joined: 06-March 08

Re: loops in switch statements

Posted 16 April 2008 - 11:56 AM

2 problems:
- your scan.nextLine() does not store the name read
- you have to read back the reply before while

   System.out.println("More players? Y/N ...");
   String reply = scan.next();
   while (reply.equalsIgnoreCase("Y")); 		
   {
		System.out.print("Please enter next name: " );
		String name = scan.next();
			
		System.out.println("");
		System.out.print("More players? Y/N...");
		reply = scan.next();
   }



in the current state of the loop, it seems the while statement is not being run, what i think i need to do is just have infinite loop that would ask whether there are any more names and exist once the exit conditions are entered.

what is wrong with my loop? pbl, i tried your suggestion of justing using the while statement to handle to 'y'
but it wasn't doing what i wanted, so i tried a do-while which isnt working either.

thanks
[/quote]
Was This Post Helpful? 0
  • +
  • -

#10 scholio  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 11-February 08

Re: loops in switch statements

Posted 16 April 2008 - 04:25 PM

pbl, you said i need to read back 'reply' before the while. what do you mean by that, i thought the reply.equalsIgnoreCase("Y") was reading in reply. (see code)

i made an arraylist call players which you said i needed , it is supposed to store 'name,' but i don't think that its doing that, probably because the while loop still does not work. (see code)

 

				List<String> players;	
		players = new ArrayList<String>();
	
		Scanner scan = new Scanner(System.in);
		System.out.println("Please enter player's name :");
		String names =scan.nextLine();
		System.out.println("");
	
		
		System.out.println("More players? Y/N ...");
		String reply = scan.next();
		while (reply.equalsIgnoreCase("Y"));
		**//is this where i need to read back reply?// how do i?//**	
		{
			System.out.println("Please enter next name: " );
			scan.nextLine();
			String name = scan.nextLine();
			players.add(name); //here name is supposed to store in arraylist players//
													 // is it done correctly?//
			
			System.out.println("");			
			System.out.println("More players? Y/N...");
		}





trial runs to show errors

trial run using 'n'


 ----jGRASP exec: 

Please enter player's name :
y

More players? Y/N ...
n							   //exit condition i assume, then program enters 'while' loop
Please enter next name: 
y

More players? Y/N...   //program exits




trial run entering 'y' (yes)

 ----jGRASP exec: 

Please enter player's name :
eggo

More players? Y/N ...
y		  //entered y (yes)
hf
fjj		 //infinite loop, program never completes





thanks

This post has been edited by scholio: 16 April 2008 - 04:38 PM

Was This Post Helpful? 0
  • +
  • -

#11 m2s87  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 21
  • View blog
  • Posts: 390
  • Joined: 28-November 06

Re: loops in switch statements

Posted 16 April 2008 - 05:01 PM

I would fix it to something like:
import java.util.ArrayList;
import java.util.Scanner;


	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		ArrayList<String> players = new ArrayList<String>();

		getName(scan,players);
		while(getContinue(scan)){
			getName(scan,players);
		}

		//print out player names
		System.out.println("there are names like:");
		for(String aName:players){
			System.out.print(aName+";");
		}

	}
	private static void getName(Scanner scan,ArrayList<String> players){
		System.out.println("Please enter player's name :");
		players.add(scan.next());
	}
	private static boolean getContinue(Scanner scan){
		System.out.println("\nMore players? Y/N ...");
		if(scan.next().toLowerCase().equals("y")){
			return true;
		}else{
			return false;
		}
	}


Was This Post Helpful? 0
  • +
  • -

#12 scholio  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 11-February 08

Re: loops in switch statements

Posted 16 April 2008 - 05:32 PM

thanks so much m2s87, thats exactly what i was looking for.

i can't tell my looking at the code, by does each time a new name is entered, is the new name added to the arraylist called players?

how can i call each name so that each name can associated with something say a bank account, sequentially, one after the other? i'm not looking you to show me how to create an account number class or anything, just how to call each name in the arraylist and be able to do the same thing for each of them, one after the other

lets say these names were entered: bill, rambo, ta, co
and each name was stored in the arraylist players.

i would like to know how to output something like:

bill
account number : 11111

rambo
account number : 22222

ta
account number : 33333

co
acount number : 44444



thanks
Was This Post Helpful? 0
  • +
  • -

#13 m2s87  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 21
  • View blog
  • Posts: 390
  • Joined: 28-November 06

Re: loops in switch statements

Posted 16 April 2008 - 07:23 PM

At this point you should start to think of creating a documentation like javadoc. But code what you might have been looking for would probably look like:
 import java.util.ArrayList;
import java.util.Scanner;

public class hooray {
	public static class somedata {
		private static Integer counter = new Integer(0);
		private String _dataStr = "";
		private String _dataID = "";
		
		public somedata(String value) {
			somedata.counter++;
			this._dataStr = value;
			this._dataID = somedata.counter.toString()
					+ somedata.counter.toString() + somedata.counter.toString()
					+ somedata.counter.toString() + somedata.counter.toString();
		}

		public static boolean getContinue(Scanner scan) {
			System.out.println("\nMore players? Y/N ...");
			if (scan.next().toLowerCase().equals("y")) {
				return true;
			} else {
				return false;
			}
		}
		public static void getName(Scanner scan, ArrayList<somedata> players) {
			System.out.println("Please enter player's name :");
			players.add(new somedata(scan.next()));
		}

		public String toString() {
			return "\n" + this._dataStr + "\nacount number : " + this._dataID;
		}
	}

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		ArrayList<somedata> players = new ArrayList<somedata>();

		somedata.getName(scan, players);
		while (somedata.getContinue(scan)) {
			somedata.getName(scan, players);
		}

		// print out player names
		for (somedata aName : players) {
			System.out.println(aName);
		}
	}
}


Was This Post Helpful? 0
  • +
  • -

#14 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8342
  • View blog
  • Posts: 31,880
  • Joined: 06-March 08

Re: loops in switch statements

Posted 16 April 2008 - 08:54 PM

That will display a list of all your players

for(String name : players) {
   System.out.println(name);
}



Now if you want to display their account....
String do not have account

So you will have to have a class Players

class Player {
   int account;
   String name;
   // constructor
   Player(String name, int account) {
	  this.name = name;
	  this.account = account;
   }
}



Then you ArrayList will have to become an ArrayList of Players not an ArrayList of String

then your loop will be

for(Player p : arrayList) {
   System.out.println("Name: " + p.name + " Account: " + p.account);
}



but your code is not structured (yet) to prompt for a name, then an account
then to create a Player object that you will insert in the ArrayList
Was This Post Helpful? 0
  • +
  • -

#15 scholio  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 11-February 08

Re: loops in switch statements

Posted 17 April 2008 - 05:25 PM

thanx pbl and m2s87, i was able to call data from my arraylist successfully. i have another quick question.

i am trying to do a do-while loop. i want the loop to run the method b.gameon() as many times as the size of the arraylist players, so if players.size() equaled 5 for instance, i want the loop to run b.gameon() five times. how do i do that, i think its just how i set up the while portion of the do-while, could someone tell me what is wrong.


				 System.out.println("Player(s) list: ");
		 System.out.println(""); 
		 players.size();
		 System.out.println("Number of players entered: " + players.size());
	   
		 for(String aName:players)
		 {  
 				 System.out.print(aName + "\n");
			  System.out.println("");
				  }  
	 	  
		 b.hustle();   
		 do	   //**********************here**********
		 {
			 b.gameon();
			 
		 }
			 while(int i = 0; i > players.size(); i--); //********here******
						 



another question, in my println statement that returns players score(below), i would like to increment the address number for each time the do/while loop runs, in the sample code the address was 0. for example, lets say the program returns player.size() equals 5, for the first run of the do.while it would display

Player 0's turn

second run

Player 1's turn ...etc

up to

Player 4's turn

how can i do that?

do
{

  System.out.println("");
  System.out.println("Player " + players.get(0) + "'s turn..."); //***here********//
  System.out.println("");
  b.gameon();
}
while(......)





thanks all again

***************EDIT****************

i figured it out now, basically i did a for loop instead of a do while, so now my program does exactly what i want now, thanks pbl and m2s87 for the help earlier


for(int i = 0; i < players.size(); i++)
{
   System.out.println(" player " + players.get(i) + "'s turn...");
   b.gameon//
}



This post has been edited by scholio: 17 April 2008 - 06:22 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2