how to use Java 8 for long function definitions? - java-8

I have a an object Product,
and code as below , hashSetProducts is LinkedHashSet of Products. How can I write all below using Java 8 stream function ? I understand that value of remianing will be replaced each time. I want the final value after the for loop exits.
int getRemaining(int remaining){
for(Product P : hashSetProducts){
remaining = calculate(p.qty(), p.price(), remaining, location); //
use Java 8 stream here
}
return remaining
}
private int calculate(int qty, double price, int rem, Location location){
if(rem== 0){
return 0;
}
int avail = location.get(qty, rem);
if(avail > 0){
rem = avail - rem;
}
return rem;
}

mapToLong will execute arbitrary code that returns a long. Here is an MCVE that uses your calculation verbatim:
import java.util.LinkedHashSet;
public class HelloWorld{
public static class Product {
private int qty;
private double price;
private int used;
public Product(int qty, double price, int used) {
this.qty = qty;
this.price =price;
this.used = used;
}
public int qty() {return qty;}
public double price() {return price;}
public int used() {return used;}
};
public static class Location {
public long get(int qty, int used) { return 0; };
};
public static void main(String []args) {
LinkedHashSet<Product> hashSetProducts = new LinkedHashSet();
hashSetProducts.add(new Product(1,1.0,1));
hashSetProducts.add(new Product(2,2.0,2));
hashSetProducts.add(new Product(3,3.0,3));
Location location = new Location();
long remaining = hashSetProducts.stream().mapToLong(p -> {
int qty = p.qty();
int used = p.used();
if( used == 0 )
return 0;
long rem = location.get(qty, used);
if( qty > 0)
rem = used - rem;
return rem;
}).sum();
System.out.println(remaining);
}
}

Related

how to make a loop of the amount of space in a train

I want to make a train and at every stop is says how many people are coming in and going out, and if the maximum is reached, then it declines the rest. I also have seated spots and standing spots and if there are any seated spots left, the standing people go sit instead of stand.
so here is what I have
public class Train {
private int declinedPassengers; // instance variables
private int passengerInTrain;
private int numberOfSeats;
private int numberOfStandingSpots;
private int numberOfBoardingPassengers;
private int numberOfAlightingPassengers;
private int numberOfSeatedPassengers;
private int numberOfStandingPassengers;
private int numberOfDeclinedPassengers;
public static void main(String[] args){
Train train = new Train(150, 100);
train.stopAtStation(100, 0);
train.stopAtStation(75, 10);
System.out.println("After two stops:");
System.out.println(train.getNumberOfSeatedPassengers());
System.out.println(train.getNumberOfStandingPassengers());
train.stopAtStation(100, 0);
train.stopAtStation(100, 10);
System.out.println("After four stops:");
System.out.println(train.isFull());
System.out.println(train.getNumberOfSeatedPassengers());
System.out.println(train.getNumberOfStandingPassengers());
System.out.println(train.getNumberOfDeclinedPassengers());
train.stopAtStation(10, 50);
System.out.println("After five stops:");
System.out.println(train.isFull());
System.out.println(train.getNumberOfSeatedPassengers());
System.out.println(train.getNumberOfStandingPassengers());
System.out.println(train.getNumberOfDeclinedPassengers());
}
public Train(int numberOfSeats, int numberOfStandingSpots) {
for(int i = 0; i <= numberOfSeats; i++){
}
}
public void stopAtStation(int numberOfBoardingPassengers, int numberOfAlightingPassengers) {
}
public int getNumberOfSeatedPassengers() {
return numberOfSeatedPassengers;
}
public int getNumberOfStandingPassengers() {
return numberOfStandingPassengers;
}
public int getNumberOfDeclinedPassengers(){
return numberOfDeclinedPassengers;
}
public boolean isFull(){
int seated = getNumberOfSeatedPassengers();
int standing = getNumberOfStandingPassengers();
if(seated == 150 && standing == 100){
return true;
}
else{
return false;
}
}
}
and I am stuck at the for loop on how to make a loop such that it counts down the amount of seats, or up the amount of seated/ standing people

Java 8 Stream , convert List<File> to Map<Integer, List<FIle>>

I have below code in traditional java loop. Would like to use Java 8 Stream instead.
I have a sorted list of files(Sorted by file size). I group these files together in a way that the total size of all files does not exceed the given max size and put them in a Map with the key 1,2,3,... so on. Here is the code.
List<File> allFilesSortedBySize = getListOfFiles();
Map<Integer, List<File>> filesGroupedByMaxSizeMap = new HashMap<Integer, List<File>>();
double totalLength = 0L;
int count = 0;
List<File> filesWithSizeTotalMaxSize = Lists.newArrayList();
//group the files to be zipped together as per maximum allowable size in a map
for (File file : allFilesSortedBySize) {
long sizeInBytes = file.length();
double sizeInMb = (double)sizeInBytes / (1024 * 1024);
totalLength = totalLength + sizeInMb;
if(totalLength <= maxSize) {
filesWithSizeTotalMaxSize.add(file);
} else {
count = count + 1;
filesGroupedByMaxSizeMap.put(count, filesWithSizeTotalMaxSize);
filesWithSizeTotalMaxSize = Lists.newArrayList();
filesWithSizeTotalMaxSize.add(file);
totalLength = sizeInMb;
}
}
filesGroupedByMaxSizeMap.put(count+1, filesWithSizeTotalMaxSize);
return filesGroupedByMaxSizeMap;
after reading,I found the solution using Collectors.groupBy instead.
Code using java8 lambda expression
private final long MB = 1024 * 1024;
private Map<Integer, List<File>> grouping(List<File> files, long maxSize) {
AtomicInteger group = new AtomicInteger(0);
AtomicLong groupSize = new AtomicLong();
return files.stream().collect(groupingBy((file) -> {
if (groupSize.addAndGet(file.length()) <= maxSize * MB) {
return group.get() == 0 ? group.incrementAndGet() : group.get();
}
groupSize.set(file.length());
return group.incrementAndGet();
}));
}
Code provided by #Holger then you are free to checking group whether equals 0
private static final long MB = 1024 * 1024;
private Map<Integer, List<File>> grouping(List<File> files, long maxSize) {
AtomicInteger group = new AtomicInteger(0);
//force initializing group starts with 1 even if the first file is empty.
AtomicLong groupSize = new AtomicLong(maxSize * MB + 1);
return files.stream().collect(groupingBy((file) -> {
if (groupSize.addAndGet(file.length()) <= maxSize * MB) {
return group.get();
}
groupSize.set(file.length());
return group.incrementAndGet();
}));
}
Code using anonymous class
inspired by #Holger, All “solutions” using a grouping function that modifies external state are hacks abusing the API,so you can use anonymous class to manage the grouping logic state in class.
private static final long MB = 1024 * 1024;
private Map<Integer, List<File>> grouping(List<File> files, long maxSize) {
return files.stream().collect(groupingBy(groupSize(maxSize)));
}
private Function<File, Integer> groupSize(final long maxSize) {
long maxBytesSize = maxSize * MB;
return new Function<File, Integer>() {
private int group;
private long groupSize = maxBytesSize + 1;
#Override
public Integer apply(File file) {
return hasRemainingFor(file) ? current(file) : next(file);
}
private boolean hasRemainingFor(File file) {
return (groupSize += file.length()) <= maxBytesSize;
}
private int next(File file) {
groupSize = file.length();
return ++group;
}
private int current(File file) {
return group;
}
};
}
Test
import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.groupingBy;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
/**
* Created by holi on 3/24/17.
*/
public class StreamGroupingTest {
private final File FILE_1MB = file(1);
private final File FILE_2MB = file(2);
private final File FILE_3MB = file(3);
#Test
void eachFileInIndividualGroupIfEachFileSizeGreaterThanMaxSize() {
Map<Integer, List<File>> groups = grouping(asList(FILE_2MB, FILE_3MB), 1);
assertThat(groups.size(), equalTo(2));
assertThat(groups.get(1), equalTo(singletonList(FILE_2MB)));
assertThat(groups.get(2), equalTo(singletonList(FILE_3MB)));
}
#Test
void allFilesInAGroupIfTotalSizeOfFilesLessThanOrEqualMaxSize() {
Map<Integer, List<File>> groups = grouping(asList(FILE_2MB, FILE_3MB), 5);
assertThat(groups.size(), equalTo(1));
assertThat(groups.get(1), equalTo(asList(FILE_2MB, FILE_3MB)));
}
#Test
void allNeighboringFilesInAGroupThatTotalOfTheirSizeLessThanOrEqualMaxSize() {
Map<Integer, List<File>> groups = grouping(asList(FILE_1MB, FILE_2MB, FILE_3MB), 3);
assertThat(groups.size(), equalTo(2));
assertThat(groups.get(1), equalTo(asList(FILE_1MB, FILE_2MB)));
assertThat(groups.get(2), equalTo(singletonList(FILE_3MB)));
}
#Test
void eachFileInIndividualGroupIfTheFirstFileAndTotalOfEachNeighboringFilesSizeGreaterThanMaxSize() {
Map<Integer, List<File>> groups = grouping(asList(FILE_2MB, FILE_1MB, FILE_3MB), 2);
assertThat(groups.size(), equalTo(3));
assertThat(groups.get(1), equalTo(singletonList(FILE_2MB)));
assertThat(groups.get(2), equalTo(singletonList(FILE_1MB)));
assertThat(groups.get(3), equalTo(singletonList(FILE_3MB)));
}
#Test
void theFirstEmptyFileInGroup1() throws Throwable {
File emptyFile = file(0);
Map<Integer, List<File>> groups = grouping(singletonList(emptyFile), 2);
assertThat(groups.get(1), equalTo(singletonList(emptyFile)));
}
private static final long MB = 1024 * 1024;
private Map<Integer, List<File>> grouping(List<File> files, long maxSize) {
AtomicInteger group = new AtomicInteger(0);
AtomicLong groupSize = new AtomicLong(maxSize * MB + 1);
return files.stream().collect(groupingBy((file) -> {
if (groupSize.addAndGet(file.length()) <= maxSize * MB) {
return group.get();
}
groupSize.set(file.length());
return group.incrementAndGet();
}));
}
private Function<File, Integer> groupSize(final long maxSize) {
long maxBytesSize = maxSize * MB;
return new Function<File, Integer>() {
private int group;
private long groupSize = maxBytesSize + 1;
#Override
public Integer apply(File file) {
return hasRemainingFor(file) ? current(file) : next(file);
}
private boolean hasRemainingFor(File file) {
return (groupSize += file.length()) <= maxBytesSize;
}
private int next(File file) {
groupSize = file.length();
return ++group;
}
private int current(File file) {
return group;
}
};
}
private File file(int sizeOfMB) {
return new File(String.format("%dMB file", sizeOfMB)) {
#Override
public long length() {
return sizeOfMB * MB;
}
#Override
public boolean equals(Object obj) {
File that = (File) obj;
return length() == that.length();
}
};
}
}
Since the processing of each element highly depends on the previous’ processing, this task is not suitable for streams. You still can achieve it using a custom collector, but the implementation would be much more complicated than the loop solution.
In other words, there is no improvement when you rewrite this as a stream operation. Stay with the loop.
However, there are still some things you can improve.
List<File> allFilesSortedBySize = getListOfFiles();
// get maxSize in bytes ONCE, instead of converting EACH size to MiB
long maxSizeBytes = (long)(maxSize * 1024 * 1024);
// use "diamond operator"
Map<Integer, List<File>> filesGroupedByMaxSizeMap = new HashMap<>();
// start with "create new list" condition to avoid code duplication
long totalLength = maxSizeBytes;
// count is obsolete, the map maintains a size
// the initial "totalLength = maxSizeBytes" forces creating a new list within the loop
List<File> filesWithSizeTotalMaxSize = null;
for(File file: allFilesSortedBySize) {
long length = file.length();
if(maxSizeBytes-totalLength <= length) {
filesWithSizeTotalMaxSize = new ArrayList<>(); // no utility method needed
// store each list immediately, so no action after the loop needed
filesGroupedByMaxSizeMap.put(filesGroupedByMaxSizeMap.size()+1,
filesWithSizeTotalMaxSize);
totalLength = 0;
}
totalLength += length;
filesWithSizeTotalMaxSize.add(file);
}
return filesGroupedByMaxSizeMap;
You may further replace
filesWithSizeTotalMaxSize = new ArrayList<>();
filesGroupedByMaxSizeMap.put(filesGroupedByMaxSizeMap.size()+1,
filesWithSizeTotalMaxSize);
with
filesWithSizeTotalMaxSize = filesGroupedByMaxSizeMap.computeIfAbsent(
filesGroupedByMaxSizeMap.size()+1, x -> new ArrayList<>());
but there might be different opinions whether this is an improvement.
The simplest solution to the problem I could think of is to use an AtomicLong wrapper for the size and a AtomicInteger wrapper for length. These have some useful methods for performing basic arithmetic operations on them which are very useful in this particular case.
List<File> files = getListOfFiles();
AtomicLong length = new AtomicLong();
AtomicInteger index = new AtomicInteger(1);
long maxLength = SOME_ARBITRARY_NUMBER;
Map<Integer, List<File>> collect = files.stream().collect(Collectors.groupingBy(
file -> {
if (length.addAndGet(file.length()) <= maxLength) {
return index.get();
}
length.set(file.length());
return index.incrementAndGet();
}
));
return collect;
Basically what Collectors.groupingBy does the work which you Intended.

use an int Variable for range to get random number

I am still fairly new to java. I want to make a game with 3 character types that have different stats. I am using int values for each type so that their attack value is a range instead of just being a constant value. Since each character has a different range, I want to substitute an int value instead of an actual number for the method to get a random number. Here is my code.
package battleme;
import java.util.Random;
/**
*
* #author Kitten
*/
class Character {
String name;
int life;
int playerAttacklow;
int playerAttackhigh;
int playerDefense;
int playerLevel;
int currentXP;
int currentGold;
public Character(String name, int life, int playerAttacklow,
int playerAttachhigh, int playerDefense,
int playerLevel, int currentXP, int currentGold) {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLife() {
return life;
}
public void setLife(int life) {
this.life = life;
}
public int getPlayerAttacklow() {
return playerAttacklow;
}
public void setPlayerAttacklow(int playerAttacklow) {
this.playerAttacklow = playerAttacklow;
}
public int getPlayerAttackhigh() {
return playerAttackhigh;
}
public void setPlayerAttackhigh(int playerAttackhigh) {
this.playerAttackhigh = playerAttackhigh;
}
public int getPlayerDefense() {
return playerDefense;
}
public void setPlayerDefense(int playerDefense) {
this.playerDefense = playerDefense;
}
public int getPlayerLevel() {
return playerLevel;
}
public void setPlayerLevel(int playerLevel) {
this.playerLevel = playerLevel;
}
public int getCurrentXP() {
return currentXP;
}
public void setCurrentXP(int currentXP) {
this.currentXP = currentXP;
}
public int getCurrentGold() {
return currentGold;
}
public void setCurrentGold(int currentGold) {
this.currentGold = currentGold;
}
//the problem child
int ActualAttackGen(int playerAttackhigh, int playerAttacklow) {
Random rn = new Random();
int randomNum;
randomNum= rn.nextInt((playerAttackhigh-playerAttacklow) + 1)+ playerAttacklow ;
return randomNum ;
}
package battleme;
public class BattleMe {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Character Warrior = new Character("Warrior", 30, 2, 10, 3, 1, 1, 15);
Character Rouge = new Character("Rouge", 25, 3, 6, 2, 1, 1, 15);
Character Mage = new Character("Mage", 18, 2, 8, 1, 1, 1, 15);
// trying to run the problem child
System.out.println(Warrior.ActualAttackGen(Warrior.playerAttackhigh,Warrior.playerAttacklow));
}
}
Whenever I try to run this, I always get an value of 0. Please help!
In your constructor you have to assign the passed values to the respective member of your Character class:
public Character(String name, int life, int playerAttacklow,
int playerAttachhigh, int playerDefense,
int playerLevel, int currentXP, int currentGold) {
this.name = name;
....
}
BTW: It would be good coding practice to distinguish member and parameter names. Usually one prefixes one of them (or both). E.g. member myName, parameter aName. So you do not have to reference the member with "this.":
myName = aName;

get average value from a tree of nodes

I have to implement this method:
public int GetAverage(Node root){
//TODO implement
}
this method should get average value of all nodes of root tree. where :
public interface Node {
int getValue();
List<Node> getNodes();
}
do you have any ideas how to implement this method?
thank you
my attempt:
public static double value;
public static int count;
public static double getAverage(Node root) {
count++;
value += root.getValue();
for (Node node : root.getNodes()) {
getAverage(node);
}
return value / count;
}
but how to do it without the static fields outside of the method?
Simply traverse through all nodes and remember the count and the overall sum of all values. Then calculate the average. This is an example written in Java.
public interface INode {
int getValue();
List<INode> getNodes();
}
public class Node implements INode {
private List<INode> children = new ArrayList<INode>();
private int value;
#Override
public int getValue() {
return value;
}
#Override
public List<INode> getNodes() {
return children;
}
public static int getAverage(INode root) {
if (root == null)
return 0;
Counter c = new Counter();
calculateAverage(root, c);
return c.sum / c.count;
}
class Counter {
public int sum;
public int count;
}
private static void calculateAverage(INode root, Counter counter) {
if (root == null)
return;
counter.sum += root.getValue();
counter.count++;
// recursively through all children
for (INode child : root.getNodes())
calculateAverage(child, counter);
}
}
public static double getAverage(Node root) {
Pair p = new Pair(0,0);
algo(root, p);
return ((double) p.element1) / ((double) p.element2);
}
private static void algo(Node root, Pair acc) {
for(Node child : root.getNodes()) {
algo(child, acc);
}
acc.sum += root.getValue();
acc.nbNodes++;
}
With Pair defined as follows:
public class Pair {
public int sum;
public int nbNodes;
public Pair(int elt1, int elt2) {
this.sum = elt1;
this.nbNodes = elt2;
}
}

Playing Logic about Card Game Bridge

i have have design a class whos constructor produce 52 Cards object each orject has its own color, value, isTrump(boolean) and imageIcon which store image of each card. now there is another class called Que who stores all the objects of cards into a que and shuffle them. there is a method which deals the cards object among 4 players into array of object(Cards). now i used LayeredPane and Jlabels to show them and a mouse-listener also attached with each.
Now i only want a tip how can i start each trick. means i place one card then three other robots placed there cards automatically after analysing my card on the bases of some predefined rules.
please any suggestions
public class Cards {
public Cards(int a, int b){
this.cardvalue = a;
this.color = b;
this.isTrump = false;
switch(a){
case 11: this.facevalue = 1;
break;
case 12: this.facevalue = 2;
break;
case 13: this.facevalue = 3;
break;
case 14: this.facevalue = 4;
break;
default : this.facevalue = 0;
}
switch(b){
case 1: this.colorName = "Spade";
this.CardImage= new ImageIcon(getClass().getResource("/testing/Cards/Spade/Spade ("+a+").jpg"));
break;
case 2: this.colorName = "Heart";
this.CardImage= new ImageIcon(getClass().getResource("/testing/Cards/Heart/Heart ("+a+").jpg"));
break;
case 3: this.colorName = "Diamond";
this.CardImage= new ImageIcon(getClass().getResource("/testing/Cards/Diamond/Diamond ("+a+").jpg"));
break;
default : this.colorName = "Club";
this.CardImage= new ImageIcon(getClass().getResource("/testing/Cards/Club/Club ("+a+").jpg"));
}
}
public void isTrump(){
this.isTrump = true;
}
public int getCardValue(){
return this.cardvalue;
}
public int getColor(){
return this.color;
}
public int getFaceValue(){
return this.facevalue;
}
public boolean getisTrump(){
return this.isTrump;
}
public String getColorName(){
return this.colorName;
}
public ImageIcon getCardImage(){
return this.CardImage;
}
public ImageIcon getBackSide(){
return backSide;
}
private String colorName;
private int cardvalue;
private int color; // 1 For Spade 2 For Heart 3 For Diamond 4 For Club
private int facevalue;
private boolean isTrump;
private ImageIcon CardImage;
private ImageIcon backSide = new
ImageIcon(getClass().getResource("/testing/Cards/Backside.jpg"));
}
Class which deal the card is
public class CardsInHand {
public CardsInHand(){
totalCards = new Que(52);
int a =1; int b=2;
for (int j = 0;j<52;j++){
if(j==13||j==26||j==39) a++;
if(b==15) b=2;
totalCards.put(new Cards(b,a));
b++;
}
totalCards.QueShuffle();
}
public static void Deal(){
card = new CardsInHand();
setPlayers();
}
private static void setPlayers(){
for(int i =0;i<13;i++){
Hands[0][i] = totalCards.get();
Hands[1][i] = totalCards.get();
Hands[2][i] = totalCards.get();
Hands[3][i] = totalCards.get();
}
sortingarr();
}
private static void Sorting(Cards arr[]){
//here some Sorting algorithm i used
}
private static void sortingarr(){
Sorting(Hands[0]);
Sorting(Hands[1]);
Sorting(Hands[2]);
Sorting(Hands[3]);
NumberSorting(Hands[0]);
NumberSorting(Hands[1]);
NumberSorting(Hands[2]);
NumberSorting(Hands[3]);
}
private static void NumberSorting(Cards arr[]){
//some algorith i used for number sorting
}
public static Cards[] getPlayer1(){
return Hands[0];
}
public static Cards[] getPlayer2(){
return Hands[1];
}
public static Cards[] getPlayer3(){
return Hands[2];
}
public static Cards[] getPlayer4(){
return Hands[3];
}
public static Cards[][] getAllHands(){
return Hands;
}
private final static Cards[] Player1 = new Cards[13];
private final static Cards[] Player2 = new Cards[13];
private final static Cards[] Player3 = new Cards[13];
private final static Cards[] Player4 = new Cards[13];
private final static Cards[][] Hands = {Player1,Player2,Player3,Player4};
private static Que totalCards;
private static CardsInHand card;
}
the class which is showing the cards after dealing is
public class ShowCards {
private JFrame frame = new JFrame();
private static JLayeredPane lpane = new JLayeredPane();
private static JLabel[] Player1 = new JLabel[13];
private static JLabel[] Player2 = new JLabel[13];
private static JLabel[] Player3 = new JLabel[13];
private static JLabel[] Player4 = new JLabel[13];
private static JButton button = new JButton("Deal Again");
public ShowCards()
{
CardsInHand.Deal();
frame.setPreferredSize(new Dimension(800, 640));
frame.setLayout(new BorderLayout());
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.LINE_AXIS));
frame.add(lpane, BorderLayout.CENTER);
frame.add(button);
lpane.add(button, new Integer(14), 0);
button.setBounds(200, 250, 100, 70);
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonActionPerformed(evt);
}
});
lpane.setBounds(30, 30, 270, 270);
cardDeal();
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
static void cardDeal(){
loadJLabels1();
loadJLabels2();
loadJLabels3();
loadJLabels4();
}
static void loadJLabels1(){
int k = 30;
for(int i=0;i<13;i++){
Player1[i] = new JLabel();
Player1[i].setIcon(CardsInHand.getPlayer1()[i].getCardImage());
Player1[i].setBounds(k, 20, 170, 100);
Player1[i].setOpaque(true);
Player1[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
int count = evt.getClickCount();
if (count == 1){
int Index = getIndex(Player1, (JLabel)evt.getSource());
Player1[Index].setIcon(CardsInHand.getPlayer1()[Index].getBackSide());
}
}
});
lpane.add(Player1[i], new Integer(i), 0);
k = k+30;
}
}
static void loadJLabels2(){
int k = 140;
for(int i=0;i<13;i++){
Player2[i] = new JLabel();
Player2[i].setIcon(CardsInHand.getPlayer2()[i].getCardImage());
Player2[i].setBounds(30, k, 170, 100);
Player2[i].setOpaque(true);
Player2[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
int count = evt.getClickCount();
if (count == 1){
int Index = getIndex(Player2, (JLabel)evt.getSource());
Player2[Index].setIcon(CardsInHand.getPlayer2()[Index].getBackSide());
}
}
});
lpane.add(Player2[i], new Integer(i), 0);
k = k+20;
}
}
static void loadJLabels3(){
int k = 140;
for(int i=0;i<13;i++){
Player3[i] = new JLabel();
Player3[i].setIcon(CardsInHand.getPlayer3()[i].getCardImage());
Player3[i].setBounds(400, k, 170, 100);
Player3[i].setOpaque(true);
Player3[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
int count = evt.getClickCount();
if (count == 1){
int Index = getIndex(Player3, (JLabel)evt.getSource());
Player3[Index].setIcon(CardsInHand.getPlayer2()[Index].getBackSide());
}
}
});
lpane.add(Player3[i], new Integer(i), 0);
k = k+20;
}
}
static void loadJLabels4(){
int k = 30;
for(int i=0;i<13;i++){
Player4[i] = new JLabel();
Player4[i].setIcon(CardsInHand.getPlayer4()[i].getCardImage());
Player4[i].setBounds(k, 500, 170, 100);
Player4[i].setOpaque(true);
Player4[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
int count = evt.getClickCount();
if (count == 1){
int Index = getIndex(Player4, (JLabel)evt.getSource());
Player4[Index].setIcon(CardsInHand.getPlayer2()[Index].getBackSide());
}
}
});
lpane.add(Player4[i], new Integer(i), 0);
k = k+30;
}
}
private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
CardsInHand.Deal();
cardDeal();
}
static int getIndex(JLabel[] arr, JLabel obj){
int index=0;
for(JLabel cmp: arr){
if(cmp == obj) break;
index++;
}
return index;
}
}
Now i also creat a player class which creat three Bots to play and one will be the human. the class is as
public class Players {
public Players(Cards[] arr){
this.scoreInHand = getScoreInHand(arr);
getCardOfEachSuit(arr, this.cardsOfEachSuit);
this.isBalanceHand = getIsBalanceHand(arr);
this.longestSuit = getLongestSuit(arr);
this.numberOfTrump = getNumberOfTrump(arr);
this.smallestSuit = getSmallestSuit(arr);
this.strongestSuit = getStrongestSuit(arr);
this.weakestSuit = getWeakestSuit(arr);
for(int i=0;i<13;i++){
this.remainingSpade[i] = true;
this.remainingHeart[i] = true;
this.remainingClub[i] = true;
this.remainingDiamond[i] = true;
}
for(int i=0;i<4;i++){
this.rightOpCutSuit[i]= false;
this.leftOpCutSuit[i] = false;
this.frontOpCutSuit[i] = false;
}
this.coatCaution = false;
this.gcCaution = false;
this.numberOfTrumpExist = 13;
this.openingBet =0;
this.respondingBet =0;
this.trickStarter = false;
}
public static void createRobot(){
CardsInHand.Deal();
for(int i=0; i<3;i++){
Robots[i] = new Players(CardsInHand.getAllHands()[i+1]);
}
}
private int getScoreInHand(Cards[] arr){
int temp = 0;
for(Cards x: arr){
temp = temp + x.getFaceValue();
}
return temp;
}
private int getStrongestSuit(Cards[] arr){
int strong=0;
int S=0;int C=0;int D=0;int H=0;
for(Cards x: arr){
if(x.getColorName()=="Spade") S = S + x.getFaceValue();
else if(x.getColorName()=="Heart") H = H + x.getFaceValue();
else if(x.getColorName()=="Club") C = C + x.getFaceValue();
else D = D + x.getFaceValue();
}
int[] temp = {S,H,D,C};
int max = temp[0];
for(int i=0;i<4;i++){
if(max<temp[i]){
max=temp[i];
strong = i;
}
}
return strong+1;
}
private int getWeakestSuit(Cards[] arr){
int weak=0;
int S=0;int C=0;int D=0;int H=0;
for(Cards x: arr){
if(x.getColorName()=="Spade") S = S + x.getFaceValue();
else if(x.getColorName()=="Heart") H = H + x.getFaceValue();
else if(x.getColorName()=="Club") C = C + x.getFaceValue();
else D = D + x.getFaceValue();
}
int[] temp = {S,H,D,C};
int min = temp[0];
for(int i=0;i<4;i++){
if(min>temp[i]){
min=temp[i];
weak = i;
}
}
return weak+1;
}
private int getLongestSuit(Cards[] arr){
int Longest = 0;
int[] temp = new int[4];
getCardOfEachSuit(arr, temp);
int max = temp[0];
for(int i=0;i<4;i++){
if(max<temp[i]){
max=temp[i];
Longest = i;
}
}
return Longest+1;
}
private int getSmallestSuit(Cards[] arr){
int Smallest = 0;
int[] temp = new int[4];
getCardOfEachSuit(arr, temp);
int max = temp[0];
for(int i=0;i<4;i++){
if(max>temp[i]){
max=temp[i];
Smallest = i;
}
}
return Smallest+1;
}
private boolean getIsBalanceHand(Cards[] arr){
int S=0;int C=0;int D=0;int H=0;
for(Cards x: arr){
if(x.getColorName()=="Spade") S++;
else if(x.getColorName()=="Heart") H++;
else if(x.getColorName()=="Club") C++;
else D++;
}
if((S<=4&&S>=3)&&(H<=4&&H>=3)&&(D<=4&&D>=3)&&(C<=4&&C>=3)) return true;
else return false;
}
private void getCardOfEachSuit(Cards[] arr, int[] array){
int S=0;int C=0;int D=0;int H=0;
for(Cards x: arr){
if(x.getColorName()=="Spade") S++;
else if(x.getColorName()=="Heart") H++;
else if(x.getColorName()=="Club") C++;
else D++;
}
array[0] = S;
array[1] = H;
array[2] = D;
array[3] = C;
}
private int getNumberOfTrump(Cards[] arr){
int temp = 0;
for(Cards x: arr){
if(x.getisTrump() == true) temp = temp+1;
}
return temp;
}
public void setTrickStarter(boolean a){
this.trickStarter = a;
}
public boolean getTrickStarter(){
return this.trickStarter;
}
private static Players[] Robots = new Players[3]; //
private int[] cardsOfEachSuit = new int[4]; // ok
private boolean[] remainingSpade = new boolean[13]; //
private boolean[] remainingHeart = new boolean[13]; //
private boolean[] remainingDiamond = new boolean[13]; //
private boolean[] remainingClub = new boolean[13]; //
private int scoreInHand; // ok
private int longestSuit; // ok
private int smallestSuit; // ok
private int strongestSuit; // ok
private int weakestSuit; // ok
private boolean isBalanceHand; // ok
private int numberOfTrump; // ok
private int numberOfTrumpExist; //
private boolean[] rightOpCutSuit = new boolean[4]; //
private boolean[] frontOpCutSuit = new boolean[4]; //
private boolean[] leftOpCutSuit = new boolean[4]; //
private int openingBet; //
private int respondingBet; //
private boolean gcCaution; //
private boolean coatCaution; //
private boolean trickStarter;
}
Now please guide me little forward what is can do to start playing.

Resources