[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Java: User Input

Posted on 2011-10-04
8
Medium Priority
?
534 Views
Last Modified: 2012-05-12
I attached the first few lines of my main class. As you can see the very first thing it does is ask for user input. Which is great when I work in Eclipse.
I provide the input: 2c 3s 6d 7s 8h Kh Jd 4d Jc Kc Qc Tc 9c Jh 9s 9h 9d Qs Ks Js
and everything works great.

However, last minute, the professor said he will be running our programs through the following command line command:
java CrazyPoker 2c 3s 6d 7s 8h Kh Jd 4d Jc Kc Qc Tc 9c Jh 9s 9h 9d Qs Ks Js

How do I change my code to accept the above command as user input.
 
public class Game 
{
   public static void main(String args[])
   {
     Scanner scanInput = new Scanner(System.in);
     String card_input = scanInput.nextLine();
		
     char [] cardsArray = new char[card_input.length()];
     cardsArray = card_input.toCharArray();

Open in new window


Here's the actual full code of the class:
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

// 2c 3s 6d 7s 8h Kh Jd 4d Jc Kc Qc Tc 9c Jh 9s 9h 9d Qs Ks Js
/**
 * Game class takes in user input, stores in an array, and sends the cards for evaluation.
 * @author
 * 
 */
public class Game 
{
	public static void main(String args[])
	{
		double amtPlayers;
		int finalPlayers;
		
		Scanner scanInput = new Scanner(System.in);
		String card_input = scanInput.nextLine();
		
		char [] cardsArray = new char[card_input.length()];
		cardsArray = card_input.toCharArray();
		
		int counter = 0;
		int community = 15;
		double playerChars = 9.0;
		int player = 9;
		
		amtPlayers = Math.ceil((card_input.length()-community)/playerChars);
		finalPlayers = (int) amtPlayers;
		
		// create array to store the results of the hand evaluation
		int handStrength[] = new int[finalPlayers+1];
		
		// Community Cards
		ArrayList<Card> communityArrayList = new ArrayList<Card>();		
		while(counter<community)
		{
			Card cardObj = new Card(cardsArray[counter], cardsArray[counter+1]);
			communityArrayList.add(cardObj);
			counter += 3;
		}
		ArrayList<PlayerStrength> obj = new ArrayList<PlayerStrength>();
		
		// For Loop[i] iterates through the players -- depending on how many cards supplied
		for(int i=1;i<=finalPlayers;i++)
		{
			ArrayList<Card> playerArrayList = new ArrayList<Card>();
			
			// For Loop [j] iterates through each (player's) or (i's) cards, adds them to a hand, evaluates.
			for(int j=counter;j<(community+(player*i));j+=3)
			{
				Card cardObj = new Card(cardsArray[j], cardsArray[j+1]);
				playerArrayList.add(cardObj);
				counter+=3;
			}
			
			/**
			 * A series of for loops that send the Hand Evaluator all possible hand combinations
			 */
			int [] initialStrength = new int[15];
			int z=0;
			for(int p1=0;p1<3;p1++)
				for(int p2=p1+1;p2<3;p2++)
				{
					for(int c1=0;c1<5;c1++)
						for(int c2=c1+1;c2<5;c2++)
							for(int c3=c2+1;c3<5;c3++)
								for(int c4=c3+1;c4<5;c4++)
								{
									ArrayList<Card> playerHand = new ArrayList<Card>();
									playerHand.add(communityArrayList.get(c1));
									playerHand.add(communityArrayList.get(c2));
									playerHand.add(communityArrayList.get(c3));
									playerHand.add(communityArrayList.get(c4));
									playerHand.add(playerArrayList.get(p1));
									playerHand.add(playerArrayList.get(p2));
									
									Hand theHand = new Hand(); // evaluation hand
									initialStrength[z] = theHand.evaluateHand(playerHand); //store hand strength here
									z++;
								}
				}
			Arrays.sort(initialStrength);
			handStrength[i]=initialStrength[initialStrength.length-1];
			
			PlayerStrength plyr = new PlayerStrength(handStrength[i],i);
			obj.add(plyr);		
		}
        Collections.sort(obj, new Comparator<PlayerStrength>()
        		{
        			public int compare(PlayerStrength o1, PlayerStrength o2)
        			{
        				return o1.compareTo(o2);
        			}            
        		});
		
        for(int i=0;i<finalPlayers;i++)
		{
		/*	Prints winning players in order + their score/strength
		 * 
		 * System.out.println("Player "+obj.get(i).accessPlayer() + 
		 * 				" -- " + obj.get(i).accessStrength());
		 */
        	System.out.println("Player "+obj.get(i).accessPlayer());
		}
	}
}

Open in new window

0
Comment
Question by:InfoTechEE
8 Comments
 
LVL 47

Accepted Solution

by:
for_yan earned 1200 total points
ID: 36914792
I think instaend of reading from keyboard you ca do it this way

public static void main(String args[]){

String card_input = "";

for(int j=0; j<args.length; j++){

card_input += args[j] + " ";


}

Open in new window

0
 
LVL 40

Expert Comment

by:Gurvinder Pal Singh
ID: 36914802
basically now the array of inputs is the 'args[]' array that appears as the parameter of the main method. So now you don't have to prepare the array (from scanner) to process the same.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36914822

I cannot test as I don't have other calsses - but if you just take one string with all cards
and then parse it and if you always have one space between the cards, I think this should work
Just be careful - do you want the space in fornt of the frist card - then you should start with
  String card_input = " "; and then add  card_input +=" " + args[j] ;
and remove this:    card_input = card_input.trim();

 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

// 2c 3s 6d 7s 8h Kh Jd 4d Jc Kc Qc Tc 9c Jh 9s 9h 9d Qs Ks Js
/**
 * Game class takes in user input, stores in an array, and sends the cards for evaluation.
 * @author
 *
 */
public class Game
{
	public static void main(String args[])
	{
		double amtPlayers;
		int finalPlayers;

		//Scanner scanInput = new Scanner(System.in);
	//	String card_input = scanInput.nextLine();
        
        String card_input = "";

for(int j=0; j<args.length; j++){

card_input += args[j] + " ";


}
        card_input = card_input.trim();

		char [] cardsArray = new char[card_input.length()];
		cardsArray = card_input.toCharArray();

		int counter = 0;
		int community = 15;
		double playerChars = 9.0;
		int player = 9;

		amtPlayers = Math.ceil((card_input.length()-community)/playerChars);
		finalPlayers = (int) amtPlayers;

		// create array to store the results of the hand evaluation
		int handStrength[] = new int[finalPlayers+1];

		// Community Cards
		ArrayList<Card> communityArrayList = new ArrayList<Card>();
		while(counter<community)
		{
			Card cardObj = new Card(cardsArray[counter], cardsArray[counter+1]);
			communityArrayList.add(cardObj);
			counter += 3;
		}
		ArrayList<PlayerStrength> obj = new ArrayList<PlayerStrength>();

		// For Loop[i] iterates through the players -- depending on how many cards supplied
		for(int i=1;i<=finalPlayers;i++)
		{
			ArrayList<Card> playerArrayList = new ArrayList<Card>();

			// For Loop [j] iterates through each (player's) or (i's) cards, adds them to a hand, evaluates.
			for(int j=counter;j<(community+(player*i));j+=3)
			{
				Card cardObj = new Card(cardsArray[j], cardsArray[j+1]);
				playerArrayList.add(cardObj);
				counter+=3;
			}

			/**
			 * A series of for loops that send the Hand Evaluator all possible hand combinations
			 */
			int [] initialStrength = new int[15];
			int z=0;
			for(int p1=0;p1<3;p1++)
				for(int p2=p1+1;p2<3;p2++)
				{
					for(int c1=0;c1<5;c1++)
						for(int c2=c1+1;c2<5;c2++)
							for(int c3=c2+1;c3<5;c3++)
								for(int c4=c3+1;c4<5;c4++)
								{
									ArrayList<Card> playerHand = new ArrayList<Card>();
									playerHand.add(communityArrayList.get(c1));
									playerHand.add(communityArrayList.get(c2));
									playerHand.add(communityArrayList.get(c3));
									playerHand.add(communityArrayList.get(c4));
									playerHand.add(playerArrayList.get(p1));
									playerHand.add(playerArrayList.get(p2));

									Hand theHand = new Hand(); // evaluation hand
									initialStrength[z] = theHand.evaluateHand(playerHand); //store hand strength here
									z++;
								}
				}
			Arrays.sort(initialStrength);
			handStrength[i]=initialStrength[initialStrength.length-1];

			PlayerStrength plyr = new PlayerStrength(handStrength[i],i);
			obj.add(plyr);
		}
        Collections.sort(obj, new Comparator<PlayerStrength>()
        		{
        			public int compare(PlayerStrength o1, PlayerStrength o2)
        			{
        				return o1.compareTo(o2);
        			}
        		});

        for(int i=0;i<finalPlayers;i++)
		{
		/*	Prints winning players in order + their score/strength
		 *
		 * System.out.println("Player "+obj.get(i).accessPlayer() +
		 * 				" -- " + obj.get(i).accessStrength());
		 */
        	System.out.println("Player "+obj.get(i).accessPlayer());
		}
	}
}

Open in new window

0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 26

Expert Comment

by:ksivananth
ID: 36914974
make it flexible so that it runs in both mode! try this,

public static char [] getInput( String args[] ){
  if( args != null && args.length > 0 )
     return args[0].toCharArray() ;
  }

  System.out.println( "Input: " ) ;
            Scanner scanInput = new Scanner(System.in);
            String card_input = scanInput.nextLine();
            
            char [] cardsArray = new char[card_input.length()];
            cardsArray = card_input.toCharArray();
  return cardsArray ;

}
      public static void main(String args[])
      {
            double amtPlayers;
            int finalPlayers;
            
            char [] cardsArray = getInput( args )
0
 
LVL 13

Assisted Solution

by:Hugh McCurdy
Hugh McCurdy earned 400 total points
ID: 36915002
Since this is for a class, for educational purposes, I'd like you to compile and run this class.  It mostly uses for_yan's code.  I think it will help educationally if you see what happens.
public class Test
{

  public static void main(String args[])
  {

    String card_input = "";

    for(int j=0; j<args.length; j++)
    {
      card_input += args[j] + " ";
    } // for

    System.out.println ( card_input );

  } // main()

} // Test class

Open in new window

0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 400 total points
ID: 36915708
You need to do two things:

a. Change the name of the main class to CrazyPoker
b. Instead of line 20 (in your full code) use the below
StringBuilder sb = new StringBuilder();
	String sep = "";
	for(int i = 0;i < args.length;i++) {	
	    sb.append(sep).append(args[i].toString());
	    sep = " ";
	}
	String card_input = sb.toString();

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36925515
The accepted answer won't meet your teacher's requirements btw
0
 

Author Comment

by:InfoTechEE
ID: 36925646
How so? Seems to be working.

Using this now....

public static void main(String args[]){

String card_input = "";

for(int j=0; j<args.length; j++){

card_input += args[j] + " ";
}
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Suggested Courses
Course of the Month19 days, 11 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question