This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 2 years ago.
in my public class card, if I do not declare this class as static the program will not run, and all my new card objects will return the following error:
non-static variable this cannot be referenced from a static context
card card1 = new card();
Firstly, my professor has told me that the class should not be static, but has not explained why.
Secondly, I do not understand why the main method (I know it's static) cannot reference a non-static variable.
I think I'm not understanding something fundamental here, but I need to understand what's going on here before moving on.
I've found this definition:
the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.
I have really no clue what that means. A particular member, is that referring to an object? an instance of that type? also sounds like its referring to an object that belongs to a specific class. To me something that declared static is private, and only other classes that are declared static can operate with each other - is that right? If so, why not just use the word 'private'.
The code:
import java.util.Random;
public class playing_cards {
public class card // sets up class
{
int face = 0;
int suit = 0;
String faceText;
String faceValue;
String suitValue;
String suitText;
public card() // card constructor, initially generates card number and suit
{
int face = 0;
int suit = 0;
Random generator = new Random();
face = generator.nextInt(13) + 1;
suit = generator.nextInt(4) + 1;
}
public int getFace() // sets up card face value
{
Random generator = new Random();
face = generator.nextInt(13) + 1;
return face;
}
public int getSuit() // sets up card suit value
{
Random generator = new Random();
suit = generator.nextInt(4) + 1;
return suit;
}
public String getFacetext() // gets card numeric value textually
{
switch(face)
{
case 1:
faceText = "one";
break;
case 2:
faceText = "two";
break;
case 3:
faceText = "three";
break;
case 4:
faceText = "four";
break;
case 5:
faceText = "five";
break;
case 6:
faceText = "six";
break;
case 7:
faceText = "seven";
break;
case 8:
faceText = "eight";
break;
case 9:
faceText = "nine";
break;
case 10:
faceText = "ten";
break;
case 11:
faceText = "eleven";
break;
case 12:
faceText = "twelve";
break;
case 13:
faceText = "thirtee";
break;
}
return faceText;
}
public String getSuittext() // gets card's suit value
{
switch (suit)
{ case 1:
suitText = "hearts";
break;
case 2:
suitText = "spades";
break;
case 3:
suitText = "diamonds";
break;
case 4:
suitText = "clubs";
break;
}
return suitText;
}
public String setCard(int face, int suit) // sets the card to passed through toString
{
switch (face)
{
case 1:
faceValue = "ace";
break;
case 2:
faceValue = "two";
break;
case 3:
faceValue = "three";
break;
case 4:
faceValue = "four";
break;
case 5:
faceValue = "five";
break;
case 6:
faceValue = "six";
break;
case 7:
faceValue = "seven";
break;
case 8:
faceValue = "eight";
break;
case 9:
faceValue = "nine";
break;
case 10:
faceValue = "ten";
break;
case 11:
faceValue = "jack";
break;
case 12:
faceValue = "queen";
break;
case 13:
faceValue = "king";
break;
}
switch (suit)
{
case 1:
suitValue = "hearts";
break;
case 2:
suitValue = "spades";
break;
case 3:
suitValue = "diamonds";
break;
case 4:
suitValue = "clubs";
break;
}
return suitValue;
}
public String toString()
{
String result = faceValue + " of " + suitValue;
return result;
}
}
public static void main(String[] args) {
card card1 = new card();
card card2 = new card();
card card3 = new card();
card card4 = new card();
card card5 = new card();
card card6 = new card();
card card7 = new card();
card card8 = new card();
card card9 = new card();
card card0= new card();
card1.setCard(card1.getFace(), card1.getSuit()); // sets each cards numeric value and suit and passes through toString
System.out.println(card1.toString());
card2.setCard(card2.getFace(), card2.getSuit());
System.out.println(card2.toString());
card3.setCard(card3.getFace(), card3.getSuit());
System.out.println(card3.toString());
card4.setCard(card4.getFace(), card4.getSuit());
System.out.println(card4.toString());
card5.setCard(card5.getFace(), card5.getSuit());
System.out.println(card5.toString());
System.out.println("");
card6.setCard(1, 1);
System.out.println(card6.toString());
card7.setCard(13,4);
System.out.println(card7.toString());
card8.setCard(15,5);
System.out.println(card8.toString());
card9.setCard(2,2);
System.out.println(card9.toString());
card0.setCard(3,2);
System.out.println(card0.toString());
System.out.println("");
System.out.println("Card one's suit is " + card1.getSuittext());
System.out.println("Card one's textual face value is " + card1.getFacetext());
}
}
You have to separate Card in a new class.
Create a class named Card.java:
import java.util.Random;
public class Card {
int face = 0;
int suit = 0;
String faceText;
String faceValue;
String suitValue;
String suitText;
public Card() // card constructor, initially generates card number and suit
{
int face = 0;
int suit = 0;
Random generator = new Random();
face = generator.nextInt(13) + 1;
suit = generator.nextInt(4) + 1;
}
public int getFace() // sets up card face value
{
Random generator = new Random();
face = generator.nextInt(13) + 1;
return face;
}
public int getSuit() // sets up card suit value
{
Random generator = new Random();
suit = generator.nextInt(4) + 1;
return suit;
}
public String getFacetext() // gets card numeric value textually
{
switch(face)
{
case 1:
faceText = "one";
break;
case 2:
faceText = "two";
break;
case 3:
faceText = "three";
break;
case 4:
faceText = "four";
break;
case 5:
faceText = "five";
break;
case 6:
faceText = "six";
break;
case 7:
faceText = "seven";
break;
case 8:
faceText = "eight";
break;
case 9:
faceText = "nine";
break;
case 10:
faceText = "ten";
break;
case 11:
faceText = "eleven";
break;
case 12:
faceText = "twelve";
break;
case 13:
faceText = "thirtee";
break;
}
return faceText;
}
public String getSuittext() // gets card's suit value
{
switch (suit)
{ case 1:
suitText = "hearts";
break;
case 2:
suitText = "spades";
break;
case 3:
suitText = "diamonds";
break;
case 4:
suitText = "clubs";
break;
}
return suitText;
}
public String setCard(int face, int suit) // sets the card to passed through toString
{
switch (face)
{
case 1:
faceValue = "ace";
break;
case 2:
faceValue = "two";
break;
case 3:
faceValue = "three";
break;
case 4:
faceValue = "four";
break;
case 5:
faceValue = "five";
break;
case 6:
faceValue = "six";
break;
case 7:
faceValue = "seven";
break;
case 8:
faceValue = "eight";
break;
case 9:
faceValue = "nine";
break;
case 10:
faceValue = "ten";
break;
case 11:
faceValue = "jack";
break;
case 12:
faceValue = "queen";
break;
case 13:
faceValue = "king";
break;
}
switch (suit)
{
case 1:
suitValue = "hearts";
break;
case 2:
suitValue = "spades";
break;
case 3:
suitValue = "diamonds";
break;
case 4:
suitValue = "clubs";
break;
}
return suitValue;
}
public String toString()
{
String result = faceValue + " of " + suitValue;
return result;
}
}
Then,create (or use) the Main.java class and write:
public class Main {
public static void main(String[] args) {
Card card1 = new Card();
Card card2 = new Card();
Card card3 = new Card();
Card card4 = new Card();
Card card5 = new Card();
Card card6 = new Card();
Card card7 = new Card();
Card card8 = new Card();
Card card9 = new Card();
Card card0= new Card();
card1.setCard(card1.getFace(), card1.getSuit()); // sets each cards numeric value and suit and passes through toString
System.out.println(card1.toString());
card2.setCard(card2.getFace(), card2.getSuit());
System.out.println(card2.toString());
card3.setCard(card3.getFace(), card3.getSuit());
System.out.println(card3.toString());
card4.setCard(card4.getFace(), card4.getSuit());
System.out.println(card4.toString());
card5.setCard(card5.getFace(), card5.getSuit());
System.out.println(card5.toString());
System.out.println("");
card6.setCard(1, 1);
System.out.println(card6.toString());
card7.setCard(13,4);
System.out.println(card7.toString());
card8.setCard(15,5);
System.out.println(card8.toString());
card9.setCard(2,2);
System.out.println(card9.toString());
card0.setCard(3,2);
System.out.println(card0.toString());
System.out.println("");
System.out.println("Card one's suit is " + card1.getSuittext());
System.out.println("Card one's textual face value is " + card1.getFacetext());
}
}
Your Card class has some strange methods that I didn't understand why you did like this. In general, I corrected some syntax conventions that you didn't respect (like the Camel Case). So, I will not criticize because you are still a student. Good lucky!
As the error says: You cannot refer to non-static variable in static method.
The easiest solution for you would be making another class in different file to which you will move your main method. You can also extract the card class. For example:
PlayingCards class:
public class PlayingCards {
public static void main(String[] args) {
card card1 = new card();
card card2 = new card();
card card3 = new card();
card card4 = new card();
card card5 = new card();
card card6 = new card();
card card7 = new card();
card card8 = new card();
card card9 = new card();
card card0= new card();
card1.setCard(card1.getFace(), card1.getSuit()); // sets each cards numeric value and suit and passes through toString
System.out.println(card1.toString());
card2.setCard(card2.getFace(), card2.getSuit());
System.out.println(card2.toString());
card3.setCard(card3.getFace(), card3.getSuit());
System.out.println(card3.toString());
card4.setCard(card4.getFace(), card4.getSuit());
System.out.println(card4.toString());
card5.setCard(card5.getFace(), card5.getSuit());
System.out.println(card5.toString());
System.out.println("");
card6.setCard(1, 1);
System.out.println(card6.toString());
card7.setCard(13,4);
System.out.println(card7.toString());
card8.setCard(15,5);
System.out.println(card8.toString());
card9.setCard(2,2);
System.out.println(card9.toString());
card0.setCard(3,2);
System.out.println(card0.toString());
System.out.println("");
System.out.println("Card one's suit is " + card1.getSuittext());
System.out.println("Card one's textual face value is " + card1.getFacetext());
}
}
Card class:
public class card // sets up class
{
int face = 0;
int suit = 0;
String faceText;
String faceValue;
String suitValue;
String suitText;
public card() // card constructor, initially generates card number and suit
{
int face = 0;
int suit = 0;
Random generator = new Random();
face = generator.nextInt(13) + 1;
suit = generator.nextInt(4) + 1;
}
public int getFace() // sets up card face value
{
Random generator = new Random();
face = generator.nextInt(13) + 1;
return face;
}
public int getSuit() // sets up card suit value
{
Random generator = new Random();
suit = generator.nextInt(4) + 1;
return suit;
}
public String getFacetext() // gets card numeric value textually
{
switch(face)
{
case 1:
faceText = "one";
break;
case 2:
faceText = "two";
break;
case 3:
faceText = "three";
break;
case 4:
faceText = "four";
break;
case 5:
faceText = "five";
break;
case 6:
faceText = "six";
break;
case 7:
faceText = "seven";
break;
case 8:
faceText = "eight";
break;
case 9:
faceText = "nine";
break;
case 10:
faceText = "ten";
break;
case 11:
faceText = "eleven";
break;
case 12:
faceText = "twelve";
break;
case 13:
faceText = "thirtee";
break;
}
return faceText;
}
public String getSuittext() // gets card's suit value
{
switch (suit)
{ case 1:
suitText = "hearts";
break;
case 2:
suitText = "spades";
break;
case 3:
suitText = "diamonds";
break;
case 4:
suitText = "clubs";
break;
}
return suitText;
}
public String setCard(int face, int suit) // sets the card to passed through toString
{
switch (face)
{
case 1:
faceValue = "ace";
break;
case 2:
faceValue = "two";
break;
case 3:
faceValue = "three";
break;
case 4:
faceValue = "four";
break;
case 5:
faceValue = "five";
break;
case 6:
faceValue = "six";
break;
case 7:
faceValue = "seven";
break;
case 8:
faceValue = "eight";
break;
case 9:
faceValue = "nine";
break;
case 10:
faceValue = "ten";
break;
case 11:
faceValue = "jack";
break;
case 12:
faceValue = "queen";
break;
case 13:
faceValue = "king";
break;
}
switch (suit)
{
case 1:
suitValue = "hearts";
break;
case 2:
suitValue = "spades";
break;
case 3:
suitValue = "diamonds";
break;
case 4:
suitValue = "clubs";
break;
}
return suitValue;
}
public String toString()
{
String result = faceValue + " of " + suitValue;
return result;
}
Related
it's Java Starter here, so i was Coding my program which makes a Password, i used the Random Object to have a random Number that will choose what Letter comes or What number comes.
I keep getting the Numbers and the Symbols Only.. what i get is something Like this:
"9=9null=99" I don't understand Why there's a null. Java doesn't show me any problems with my code (Doesn't show Null Pointer exception.)
Here's My code:
package project.Secureword.com;
import java.awt.*;
import java.awt.event.*;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.Random;
import javax.swing.*;
public class Main {
private static JFrame start;
private static TextField field;
private static String password;
private static String lastpass;
public static Settings passsettings;
public static Random r;
public static void main(String[] args) {
passsettings = new Settings();
passsettings.setIfDots(true);
passsettings.setIfLowercase(true);
passsettings.setIfNum(true);
passsettings.setIfUpprcase(true);
Settings.changerun();
start();
}
public static void start() {
Font a = new Font(null, Font.BOLD, 0);
Font size = a.deriveFont(20f);
JButton createPass = new JButton();
createPass.setText("<html> Click me to <br> Generate a Password! <html>");
createPass.setPreferredSize(new Dimension(100,100));
JLabel text = new JLabel();
text.setText("<html> Welcome to SECUREPASS! <br> An Extreme Strong Password Generator <br> Developed by OfficialCode");
text.setPreferredSize(new Dimension(150,150));
text.setFont(size);
field = new TextField(20);
field.setSize(new Dimension(50,50));
start = new JFrame("Secureword | Strong password Generator | Coded by OfficialCode");
start.setPreferredSize(new Dimension(390,390));
start.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
start.setLocationRelativeTo(null);
start.setLayout(new BorderLayout());
start.getContentPane().add(createPass, BorderLayout.WEST);
start.getContentPane().add(text, BorderLayout.PAGE_START);
start.getContentPane().add(field, BorderLayout.CENTER);
start.pack();
start.setVisible(true);
password = "";
createPass.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
field.setText(null);
field.selectAll();
allrandom();
}});
}
public static void allrandom() {
String[] pass = new String[8];
Random r = new Random();
for(int i = 0 ; i < pass.length ; i++) {
int ch = 0;
ch = r.nextInt(3);
switch(ch) {
case 1:
if(passsettings.isIfDots()) {
String newchar = "";
newchar = dotpass();
pass[i] = newchar;
break;
}
case 2:
if(passsettings.isIfNum()) {
String newchar2 = "";
newchar2 = Numpass();
pass[i] = newchar2;
break;
}
case 3:
String newchar3 = "";
newchar3 = charchose();
pass[i] = newchar3;
break;
}
}
for(int i = 0 ; i < pass.length ; i++) {
String newpasschar = "";
newpasschar = pass[i];
password = password + newpasschar;
}
field.setText(password);
// random() end
}
public static String uppercasepass() {
Random r = new Random();
String passletter = "";
int rN3 = 0;
rN3 = r.nextInt(26);
switch(rN3) {
case 1:
passletter = "A";
case 2:
passletter = "B";
case 3:
passletter = "C";
case 4:
passletter = "D";
case 5:
passletter = "E";
case 6:
passletter = "F";
case 7:
passletter = "G";
case 8:
passletter = "H";
case 9:
passletter = "I";
case 10:
passletter = "J";
case 11:
passletter = "K";
case 12:
passletter = "L";
case 13:
passletter = "M";
case 14:
passletter = "N";
case 15:
passletter = "O";
case 16:
passletter = "P";
case 17:
passletter = "Q";
case 18:
passletter = "R";
case 19:
passletter = "S";
case 20:
passletter = "T";
case 21:
passletter = "U";
case 22:
passletter = "V";
case 23:
passletter = "W";
case 24:
passletter = "X";
case 25:
passletter = "Y";
case 26:
passletter = "Z";
}
return passletter;
// uppercase() end
}
public static String lowercasepass() {
Random r = new Random();
String passletter = "";
int rN3 = 0;
rN3 = r.nextInt(26);
switch(rN3) {
case 1:
passletter = "a";
case 2:
passletter = "b";
case 3:
passletter = "c";
case 4:
passletter = "d";
case 5:
passletter = "e";
case 6:
passletter = "f";
case 7:
passletter = "g";
case 8:
passletter = "h";
case 9:
passletter = "i";
case 10:
passletter = "j";
case 11:
passletter = "k";
case 12:
passletter = "l";
case 13:
passletter = "m";
case 14:
passletter = "n";
case 15:
passletter = "o";
case 16:
passletter = "p";
case 17:
passletter = "q";
case 18:
passletter = "r";
case 19:
passletter = "s";
case 20:
passletter = "t";
case 21:
passletter = "u";
case 22:
passletter = "v";
case 23:
passletter = "w";
case 24:
passletter = "x";
case 25:
passletter = "y";
case 26:
passletter = "z";
}
return passletter;
}
public static String Numpass() {
Random r = new Random();
String passletter = "";
int rN = 0;
rN = r.nextInt(9);
switch(rN) {
case 1:
passletter = "1";
case 2:
passletter = "2";
case 3:
passletter = "3";
case 4:
passletter = "4";
case 5:
passletter = "5";
case 6:
passletter = "6";
case 7:
passletter = "7";
case 8:
passletter = "8";
case 9:
passletter = "9";
}
return passletter;
}
public static String dotpass() {
Random r = new Random();
String passletter = "";
int rN5 = 0;
rN5 = r.nextInt(5);
switch(rN5) {
case 1:
passletter = "_";
case 2:
passletter = "]";
case 3:
passletter = "$";
case 4:
passletter = "#";
case 5:
passletter = "=";
}
return passletter;
}
public static String charchose() {
Random r = new Random();
String line = "";
int rN = 0;
rN = r.nextInt(20);
switch(rN) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
if(passsettings.isIfLowercase()) {
line = lowercasepass();
}
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
if(passsettings.isIfUpprcase()) {
line = uppercasepass();
}
}
return line;
}
}
The problem comes from the fact that Random.nextInt(n) return a value between 0-n (exclusive). Your switch case are all wrong by one.
This explain your null since you don't do anything for ch = 0, the String stays at null:
switch(ch){
case 1: ... //symbol
case 2 ... //number
case 3: ... //letter
}
This should be
switch(ch){
case 0: ... //symbol
case 1: ... //number
case 2: ... //letter
}
Some other issues or improvments :
You don't break after a case so you always get the last case executed (well all following case). Resulting in a possibilities of 4 character zZ9= (easy to bruteforce !)
You should use a char[] instead of String[], there is no need of using String to store one character like you do.
Instead of
String s = "a";
you can
char c = 'a';
Reducing the length of the code if you read the next point.
You can reduce your switch by doing some addition like 'a' + r.nextInt(26) to get a value between 'a' to 'z'
For a random symbol, instead of a switch, create a static array of char[] with every character, then get a random value using the size of this array.
Like :
final static char[] symbol = {'#', '#', '-', '\\', '/', '*'};
static getRadomSymbol(){
Random r = new Random();
return symbol[r.nextInt(symbol.length)];
}
Allowing the add of character easily (and reducing again the number of line ;) )
I fixed my setMonthnum method, but now my input will set the month number to 0, 13, etc. based off of my input. I need to know how to go and ask again for input and not to set my Monthnum to the incorrect input. If you have any suggestions to simply better my code, please feel free to state them! My code is as follows:
import java.util.Scanner;
public class whichMonth {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter the month name or number: ");
int monthNumber = input.nextInt();
//set up variable access to the class
AnyMonth inputMonthNumber = new AnyMonth();
// set the month number from user input
inputMonthNumber.setMonthnum.input.nextInt(monthNumber);
// get the month name from user input number
String monthName = inputMonthNumber.getMonthName(monthNumber);
}
}
class AnyMonth {
int Monthnum;
String monthName;
public AnyMonth() {
Monthnum = 1;
}
public AnyMonth(int currentMonthNumber) {
Monthnum = currentMonthNumber;
switch(currentMonthNumber) {
case 1:
Monthnum = 1;
monthName = "January";
System.out.println("January");
break;
case 2:
Monthnum = 2;
monthName = "February";
System.out.println("February");
break;
case 3:
Monthnum = 3;
monthName = "March";
System.out.println("March");
break;
case 4:
Monthnum = 4;
monthName = "April";
System.out.println("April");
break;
case 5:
Monthnum = 5;
monthName = "May";
System.out.println("May");
break;
case 6:
Monthnum = 6;
monthName = "June";
System.out.println("June");
break;
case 7:
Monthnum = 7;
monthName = "July";
System.out.println("July");
break;
case 8:
Monthnum = 8;
monthName = "August";
System.out.println("August");
break;
case 9:
Monthnum = 9;
monthName = "September";
System.out.println("September");
break;
case 10:
Monthnum = 10;
monthName = "October";
System.out.println("October");
break;
case 11:
Monthnum = 11;
monthName = "November";
System.out.println("November");
break;
case 12:
Monthnum = 12;
monthName = "December";
System.out.println("December");
break;
default:
Monthnum = 1;
monthName = "January";
}
}
public AnyMonth(String userMonthName) {
switch(userMonthName) {
case "January":
Monthnum = 1;
monthName = "January";
System.out.println("January");
break;
case "February":
Monthnum = 2;
monthName = "February";
System.out.println("February");
break;
case "March":
Monthnum = 3;
monthName = "March";
System.out.println("March");
break;
case "April":
Monthnum = 4;
monthName = "April";
System.out.println("April");
break;
case "May":
Monthnum = 5;
monthName = "May";
System.out.println("May");
break;
case "June":
Monthnum = 6;
monthName = "June";
System.out.println("June");
break;
case "July":
Monthnum = 7;
monthName = "July";
System.out.println("July");
break;
case "August":
Monthnum = 8;
monthName = "August";
System.out.println("August");
break;
case "September":
Monthnum = 9;
monthName = "September";
System.out.println("September");
break;
case "October":
Monthnum = 10;
monthName = "October";
System.out.println("October");
break;
case "November":
Monthnum = 11;
monthName = "November";
System.out.println("November");
break;
case "December":
Monthnum = 12;
monthName = "December";
System.out.println("December");
break;
default:
Monthnum = 1;
monthName = "January";
}
}
public void setMonthnum (int userMonth) {
Monthnum = userMonth;
if (userMonth < 1 || userMonth > 12){
System.out.println("Invalid input");
this.Monthnum = userMonth;
}
}
public int getMonthnum(int currentMonthNumber) {
Monthnum = currentMonthNumber;
return currentMonthNumber;
}
public String getMonthName(int currentMonthName) {
Monthnum = currentMonthName;
// use swtich-case here instead, default case should return 1/Jan
switch(currentMonthName) {
case 1:
monthName = "January";
break;
case 2:
monthName = "February";;
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
default:
monthName = "January";
}
return monthName;
}
public String toString(String monthNameToString){
monthName = monthNameToString;
return monthNameToString;
}
public boolean equals(int month) {
if (Monthnum == month) {
return true;
}
else {
return false;
}
}
public boolean greaterThan(int month) {
if (Monthnum > month) {
return true;
}
else {
return false;
}
}
public boolean lessThan(int month) {
if (Monthnum < month) {
return true;
}
else {
return false;
}
}
}
change
inputMonthNumber.setMonthnum.input.nextInt(monthNumber);
to
inputMonthNumber.setMonthnum(monthNumber);
Also, in all the getXXX methods, remove the below statement:
Monthnum = currentMonthName;
Getters are desiged to return the value. Setting the values via getter methods is not a good practice. This article explains why getters and setters are needed any how to write them :)
I'm quite new to java and have created a Java class that creates a deck of cards, and assigns them a suite, a name, a value and an ID. The problem is, there are 52 different cards that require an ID, and I've been using switch statements to assign the name, value and suite. However, if I were to do this for the card ID, I would need 52 lines of case statements, which is far too many.
public class Deck {
private Card[] cards;
public Deck() {
String suit = null;
String name = null;
int cardID=0;
int value = 0;
cards = new Card[52];
int arrayID=0;
for (int i=1; i<=4; i++){ //number of suites
for (int j=1; j <= 13; j++){ //number of card types
for (int k=1; k==52; k++){ //number of cards
switch (i){
case 1: suit = "Clubs"; break;
case 2: suit = "Diamonds"; break;
case 3: suit = "Hearts"; break;
case 4: suit = "Spades"; break;
}
switch (j){
case 1: name = "Ace"; value = 11; break;
case 2: name = "Two"; value = 2; break;
case 3: name = "Three"; value = 3; break;
case 4: name = "Four"; value =4; break;
case 5: name = "Five"; value = 5; break;
case 6: name = "Six"; value = 6; break;
case 7: name = "Seven"; value = 7; break;
case 8: name = "Eight"; value = 8; break;
case 9: name = "Nine"; value = 9; break;
case 10: name = "Ten"; value = 10; break;
case 11: name = "Jack"; value = 10; break;
case 12: name = "Queen"; value = 10; break;
case 13: name = "King"; value = 10; break;
}
switch (k){
case k: cardID=k; break; //"Case expressions must be constant expressions"
}
Card card = new Card (cardID, name, suit, value);
cards[arrayID] = card;
arrayID++;
}
}
}
}
public void printDeck(){
System.out.println(Arrays.toString(cards));
}
}
I may be doing this whole thing wrong, so are there any other ways I could assign a unique ID to the card without using a switch statement?
There's no point in this switch statement :
switch (k){
case k: cardID=k; break; //"Case expressions must be constant expressions"
}
Just write :
cardID = k;
You could use enum and you could use ordinal value to get each count automatically and you could have property like value in your case and you could do it like:
public enum Cards {
ACE(11), TWO(..), .. JACK(....;
int value;
public int getValue() {return value;}
}
System.out.println(CARDS.ACE.ordinal() + 1);
System.out.println(CARDS.ACE.getValue());
Output:
1
11
You don't need the loop or the switch statement for the cardID. You can synthesize it from i and j
for (int i=1; i<=4; i++){ //number of suites
for (int j=1; j <= 13; j++){ //number of card types
cardId = (i - 1) * 13 + j; // <<< synthesize cardID like this
switch (i){
case 1: suit = "Clubs"; break;
case 2: suit = "Diamonds"; break;
case 3: suit = "Hearts"; break;
case 4: suit = "Spades"; break;
}
switch (j){
case 1: name = "Ace"; value = 11; break;
case 2: name = "Two"; value = 2; break;
case 3: name = "Three"; value = 3; break;
case 4: name = "Four"; value =4; break;
case 5: name = "Five"; value = 5; break;
case 6: name = "Six"; value = 6; break;
case 7: name = "Seven"; value = 7; break;
case 8: name = "Eight"; value = 8; break;
case 9: name = "Nine"; value = 9; break;
case 10: name = "Ten"; value = 10; break;
case 11: name = "Jack"; value = 10; break;
case 12: name = "Queen"; value = 10; break;
case 13: name = "King"; value = 10; break;
}
Card card = new Card (cardID, name, suit, value);
cards[arrayID] = card;
arrayID++;
}
}
What I would do is instead:
Create a class card:
class Card {
private String suit;
private String name;
private int ID;
public Card(String suit, String name, int ID) {
this.suit = suit
(same for name & ID)}}
Then, in your Deck class, you can just have a ArrayList that contains all your card, with some method to add the cards in your deck:
s
class Deck {
private ArrayList<Cards> myDeck = new ArrayList<Cards>();
public void addCards(Card myCard) {
this.myDeck.add(myCard); } }
EDIT: Forgot the variable type in addCards
I am doing a POC on Java 7 new features. I have code to use String in switch statement and it works. I want to make it work in case insensitive also. Is there a way to check out with ignoreCase on String?
package com.java.j7;
public class Test {
final private String _NEW ="NEW";
final private String _PENDING = "PENDING";
final private String _CLOSED = "CLOSED";
final private String _REJECTED ="REJECTED";
public static void main(String... strings){
Test j = new Test();
j.processItem("new");
j.processItem("pending");
j.processItem("closed");
j.processItem("rejected");
}
void processItem(String s){
switch (s) {
case _NEW:
System.out.println("Matched to new");
break;
case _PENDING:
System.out.println("Matched to pending");
break;
case _CLOSED:
System.out.println("Matched to closed");
break;
case _REJECTED:
System.out.println("Matched to rejected");
break;
default:
System.out.println("Not matching any more");
break;
}
}
}
no, but you could switch on s.toUpperCase(). so:
switch (s.toUpperCase()) {
//same as before
}
and while we're nitpicking, you better upper-case things in the english locale to avoid issues with turkish
using String in switch Example from oracle docs Using Strings in switch Statements
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
public static void main(String[] args) {
String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
From oracle docs switch with string
The String in the switch expression is compared with the expressions associated with each case label as if the String#equals method were being used.
You can use
switch(s.toUpperCase()){
...
.....
}
See also
String#toUpperCase
I have a double split up into an int array, however the problem I am facing, is that I need it to fill in from the back, like this:
int[] arrayA = new int[5];
int[] arrayB = new int[5];
x = 23456.08;
//code here
//what im left with:
arrayA [0,2,3,4,5,6];
arrayB [0,8];
Heres how im cutting up the double:
public static void main(System args[])
{
Scanner input = new Scanner(System.in);
String answer = "";
int count = 0;
int thatone = 0;
int[] splitD = new int[5]; //main num
int[] splitDec = new int[1]; //decimal
//Enter the Number
System.out.print("Enter a number to convert: ");
double num = input.nextDouble();
// convert number to String
String convert = num + "";
// split the number
String[] split = convert.split("\\.");
String firstPart = split[0];
char[] charArray1 = firstPart.toCharArray();
// recreate the array with size equals firstPart length
splitD = new int[charArray1.length];
for (int i = 0; i < charArray1.length; i++)
{
// convert char to int
splitD[i] = Character.getNumericValue(charArray1[i]);
count++;
}
// the decimal part
if (split.length > 1)
{
String secondPart = split[1];
char[] charArray2 = secondPart.toCharArray();
splitDec = new int[charArray2.length];
for (int i = 0; i < charArray2.length; i++)
{
// convert char to int
splitDec[i] = Character.getNumericValue(charArray2[i]);
}
}
for(int i =0; i<count;i++)
{
if(i ==0) // x00000.00 or 000x00.00
{
if(splitD[0] != "0")
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
answer+= " Hundred ";
}
else
{
answer+= "";
}
}
else if(i ==1)//this goes with i =2 //0x0000
{
if(splitD[i] == 1)
{
switch (splitD[i+1])
{
case 9: answer+="Nineteen"; break;
case 8: answer+="Eighteen"; break;
case 7: answer+="Seventeen"; break;
case 6: answer+="Sixteen"; break;
case 5: answer+="Fifteen"; break;
case 4: answer+="Fourteen"; break;
case 3: answer+="Thirteen"; break;
case 2: answer+="Twelve"; break;
case 1: answer+="ten"; break;
default: answer+=""; break;
}
answer+= " Thousand ";
thatone = 1;
}
else
{
switch (splitD[i])
{
case 9: answer+="Ninety"; break;
case 8: answer+="Eighty"; break;
case 7: answer+="Seventy"; break;
case 6: answer+="Sixty"; break;
case 5: answer+="Fifty"; break;
case 4: answer+="Fourty"; break;
case 3: answer+="Thirty"; break;
case 2: answer+="Twenty"; break;
case 1: answer+=""; break;
default: answer+=""; break;
}
}
}
else if(i == 2) //00x000
{
if(thatone ==0)
{
switch (splitD[i])
{
case 9: answer+=" Nine"; break;
case 8: answer+=" Eight"; break;
case 7: answer+=" Seven"; break;
case 6: answer+=" Six"; break;
case 5: answer+=" Five"; break;
case 4: answer+=" Four"; break;
case 3: answer+=" Three"; break;
case 2: answer+=" Two"; break;
case 1: answer+=" One"; break;
default: answer+=""; break;
}
answer+= " Thousand ";
}
else
{
}
}
else if(i ==3)
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
answer+= " Hundred ";
}
else if(i ==4) //0000x0
{
switch (splitD[i])
{
case 9: answer+="Ninety"; break;
case 8: answer+="Eighty"; break;
case 7: answer+="Seventy"; break;
case 6: answer+="Sixty"; break;
case 5: answer+="Fifty"; break;
case 4: answer+="Fourty"; break;
case 3: answer+="Thirdy"; break;
case 2: answer+="Twenty"; break;
case 1: answer+=""; break;
default: answer+=""; break;
}
answer+= " ";
}
else if(i ==5) //00000x
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
}
}
if(splitDec[0] == 0)
{
answer += " and 00/100 Dollars";
}
else if(splitDec[1] == 0)
{
answer += " and " +splitDec[0] + "0/100 Dollars";
}
else
{
answer += " and " +splitDec[0] +splitDec[1] +" /100 Dollars";
}
System.out.println(answer);
}
}
What should I do to make the array add 0 in the appropriate places?
such as if I typed in 54.00 I would get:
int[] SplitD = {0,0,0,0,5,4};
Thanks!
Instead of re-initializing the array:
// recreate the array with size equals firstPart length
splitD = new int[charArray1.length];
for (int i = 0; i < charArray1.length; i++)
{
// convert char to int
splitD[i] = Character.getNumericValue(charArray1[i]);
count++;
}
Use the existing (with length = 5), iterating from the back:
if(charArray1.length > 5) // heavy hard-code, would prefer something better
throw new IllegalArgumentException("Maximum 5 digits, on both decimal sides.");
// watch out of ArrayIndexOutOfBoundsException
for (int i = charArray1.length - 1, j = splitD.length -1 ;
i >=0 && j >=0; i--, j--)
{
// convert char to int
splitD[j] = Character.getNumericValue(charArray1[i]);
count++;
}
Recall, int arrays are filled with zeros, at initialization.
Think creating an array of String, one String for each character (including the decimal point), would be a better approach:
String[] chars = String.valueOf(num).split("(?<=.)");
Job done.
Edit:
To use a switch, don't even split:
for (byte b : String.valueOf(num).getBytes()) {
switch(b) {
case '.':
case '1':
}
}