I'm trying to convert an ArrayList that contains "cards", or objects that store two numbers, a rank and a suit. Normally to get a single instance of the card, I use:
dealer.dealerhand.get(1).showstats();
Where showstats returns a string and is:
public String showstats()
{
String realsuit = "";
if(this.suit == 0)
{
realsuit = "Diamonds";
}
else if(this.suit == 1)
{
realsuit ="Hearts";
}
else if(this.suit == 2)
{
realsuit = "Clubs";
}
else if(this.suit == 3)
{
realsuit = "Spades";
}
String str = "My rank is: " + this.rank + " My Suit is: " + realsuit;
return str;
}
What I've tried so far is:
public String[] getStats()
{
String[] dealerstats = this.dealerhand.toArray(new String[this.dealerhand.size()]);
return dealerstats;
}
and
public String[] getStats()
{
String[] dealerstats = {""};
for(int i = 0; i < this.dealerhand.size(); i++)
{
dealerstats[i] = (dealerhand.get(i).showstats());
}
return dealerstats;
}
But they both don't work. The end goal would be a string array of the cards in the dealerhand ArrayList, that I will print out using JList. Thanks!
For this:
public String[] getStats() {
for(int i = 0; i < this.dealerhand.size(); i++) {
dealerstats[i] = (dealerhand.get(i).showstats());
}
return dealerstats;
}
make sure to initialize your String array, such as below:
public String[] getStats(Dealer dealer) { // Input a dealer
String[] dealerstats = new String[dealer.dealerhand.size()]; // Initialize String array
for(int i = 0; i < this.dealerhand.size(); i++) {
dealerstats[i] = dealerhand.get(i).showstats();
}
return dealerstats;
}
I am also assuming you have a Dealer object, as you seem to reference one in your question.
Your second attempt is almost correct. You created the array but without giving it the correct size. The String[] dealerstats size should be the size of the ArrayList dealerhand:
public String[] getStats()
{
String[] dealerstats = new String[ dealerhand.size() ];
for( int i = 0; i < dealerstats.length; ++i )
dealerstats[i] = dealerhand.get(i).showstats();
return dealerstats;
}
If you define a toString() method in your Card class you can print the ArrayList out without any conversion (Live Ideone Example here):
public class Card{
...
#Override public String toString(){
return "My rank is: " + this.rank + " My Suit is: " + this.suit;
}
}
Then you can just use:
List<Card> dealerCards = new ArrayList<Card>();
dealerCards.add(new Card(5, "Hearts"));
dealerCards.add(new Card(10, "Diamonds"));
System.out.println(dealerCards);
Output: ["My rank is: 5 My Suit is: Hearts", "My rank is: 10 My Suit is: Diamonds"]
Related
I made a helper method to sort an array with numbers in it.
Then i call the method in my "main" method and have it return a using string.format.
This code works when the string.format portion is outside of the for loop and if statement but when its inside the i doesn't return anything when i tell it to.
I know the issue might have to do with my if statement but i'm having trouble finding a solution.
public static String getSmallestSalaryString(String[] names, int[] ages, double[] salaries) {
String str= "";
String str2="";
String str3="";
double[] sal= smallestSal(salaries);
for(int i= 0; i < sal.length; i++) {
if(sal[i]== 0) {
str= String.format("Smallest salary:$%,.2f, Name:%s, age:%d" , sal[0], names[0], ages[0]);
return str;
}
else if(sal[i]== 1) {
str2= String.format("Smallest salary:$%,.2f, Name:%s, age:%d" , sal[1], names[1], ages[1]);
return str2;
}
else if(sal[i] == 2) {
str3= String.format("Smallest salary:$%,.2f, Name:%s, age:%d" , sal[2], names[2], ages[2]);
return str3;
}
}
return str;
}
public static double[] smallestSal(double[] salaries) {
Arrays.sort(salaries);
return salaries;
}
The solution requires you to find an "address" and not the "content".
I am assuming here that salaries contains the salary of all the employees, names is their name and ages their age. I am also assuming that ages, names and salaries have the same size and correlates per index. Then with these information, you construct a string to indicate the employee with the lowest salary in the company.
Since none of these information are structured within a single object, you need to find the lowest salary INDEX only. With that information, you can give his/her name and age by accessing ages[INDEX] and names[INDEX].
What you are currently doing is finding the lowest salary and then guess its INDEX in the loop, which would be more complex. Instead, in your method "smallestSal", get the INDEX in the array of the smallest salary. Then with that, your loop becomes simple. See below what I mean.
public static String getSmallestSalaryString(String[] names, int[] ages, double[] salaries) {
int lowestSalaryIdx= getLowestSalaryIndex(salaries);
return String.format("Smallest salary:$%,.2f, Name:%s, age:%d" , salaries[lowestSalaryIdx], names[lowestSalaryIdx], ages[lowestSalaryIdx]);
}
public static int getLowestSalaryIndex(double[] salaries) {
int lowestSalaryIndex = 0;
double lowestSalary = Double.MAX_VALUE;
for(int i=0; i<salaries.length; ++i) {
if (salaries[i] < lowestSalary) {
lowestSalaryIndex = i;
lowestSalary = salaries[i];
}
}
return lowestSalaryIndex;
}
After sorting you get the smallest salary in 1st element(index 0). Then you should find the actual index of that value in original array and get the details from that index. So your code should be modified as follows.
public static String getSmallestSalaryString(String[] names, int[] ages, double[] salaries) {
String str = "";
String str2 = "";
String str3 = "";
ArrayList sal = smallestSal(salaries);
double smallestSalary = (double) sal.get(0);
int salIndex = 0;
for (int i = 0; i < salaries.length; i++) {
if (salaries[i] == smallestSalary) {
salIndex = i;
break;
}
}
str = String.format("Smallest salary:$%,.2f, Name:%s, age:%d", salaries[salIndex], names[salIndex], ages[salIndex]);
return str;
}
public static ArrayList smallestSal(double[] salaries) {
ArrayList salaryList = new ArrayList();
for (int i = 0; i < salaries.length; i++) {
salaryList.add(salaries[i]);
}
Collections.sort(salaryList);
return salaryList;
}
Since you are iterating through your array you should change sal[0], names[0], ages[0] to sal[i], names[i], ages[i] .
for(int i= 0; i < sal.length; i++) {
if(sal[i]== 0) {
str= String.format("Smallest salary:$%,.2f, Name:%s, age:%d" , sal[i], names[i], ages[i]);
return str;
}
So I have a Card class that looks like this:
public class Card
{
//instance variables
private String faceValue; //the face value of the card
private String suit; //the suit of the card
String[] ranks = {"Ace", "2", "3", "4", "5", "6","7", "8", "9", "10", "Jack", "Queen", "King"};
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
/**
* Constructor
*/
public Card(int aValue, int aSuit)
{
faceValue = ranks[aValue];
suit = suits[aSuit];
}
//getters
/**
* Getter for faceValue.
*/
public String getFaceValue()
{
return faceValue;
}
/**
* Getter for suit.
*/
public String getSuit()
{
return suit;
}
//end of getters
//methods
/**
* This method returns a String representation of a Card object.
*
* #param none
* #return String
*/
public String toString()
{
return "A card: " + faceValue + " of " + suit;
}
}
And a Deck class that looks like this:
public class Deck
{
//instance variables
private Card[] deck;
/**
* Constructor for objects of class Deck
*/
public Deck()
{
deck = new Card[52];
int cardCount = 0; //number of cards created so far.
for (int aSuit = 0; aSuit < 4; aSuit++ )
{
for ( int aValue = 0; aValue < 13; aValue++ ) {
deck[cardCount] = new Test(aValue, aSuit);
cardCount++;
}
}
}
/**
* String representation.
*/
public String toString()
{
for (int i = 0; i < 52; i++)
{
String v = deck[i].getFaceValue();
String s = deck[i].getSuit();
return "Dealt a card: " + v + " of " + s + ".";
}
}
}
My toString method in the deck shows an error "missing return statement". How do change the return statement while still allowing it to print the card details after every loop?
Code you wrote will only return 0th element from deck array. it should be like:
public String toString()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 52; i++)
{
String v = deck[i].getFaceValue();
String s = deck[i].getSuit();
sb.append("Dealt a card: ").append(v).append(" of ").append(s).append(".\n");
}
return sb.toString();
}
The error is because your toString method has the return type String.
Java checks for execution paths. What if the for loop ends and never returns anything?
Although you may have hardcoded that logic, but Java compiler does not do a statistical analysis of that. Hence it must return a type String which is sure to execute if nothing else works.
This will work:
public String toString()
{
for (int i = 0; i < 52; i++)
{
String v = deck[i].getFaceValue();
String s = deck[i].getSuit();
return "Dealt a card: " + v + " of " + s + ".";
}
return "";
}
But I guess what you want is this:
public String toString()
{
StringBuilder returnValue = new StringBuilder("");
for (int i = 0; i < 52; i++)
{
String v = deck[i].getFaceValue();
String s = deck[i].getSuit();
returnValue.append("Dealt a card: " + v + " of " + s + ".");
}
return returnValue.toString();
}
if u just want to print all the cards infos, u can use
public String toString(){
for (int i = 0; i < 52; i++)
{
String v = deck[i].getFaceValue();
String s = deck[i].getSuit();
System.out.println( "Dealt a card: " + v + " of " + s + ".");
}
return null;
}
I'm creating a very simple encoder that will shuffle the characters in a string. I've written it to split this string in half, forming two new variables. The user chooses the number of shuffles they want and that is passed as a parameter in the new class constructor -- which should then use that shuffle value throughout the class. Mine is not. The shuffleEncryption method is using the class variable, 0, instead. I know this must be something very obvious, but I am not catching it. :/
//From Main Class
System.out.println("Enter message to encrypt: ");
String message = input.next();
System.out.print("Number of shuffles: " );
int numShuffles = input.nextInt();
ShuffleCipher shuffle = new ShuffleCipher(numShuffles);
System.out.println(shuffle.encode(message));
//The shuffle class
public class ShuffleCipher implements MessageEncoder {
int shuffle;
public ShuffleCipher(int shuffle) {
shuffle = this.shuffle;
}
private String shuffleEncryption(String str) {
int middle = str.length()/2;
int loop = 1;
System.out.println("shift" + shuffle);
StringBuilder sb = new StringBuilder();
do {
String firstHalf = str.substring(0, middle);
System.out.println("first:" + firstHalf);
String secondHalf = str.substring(middle);
System.out.println("second:" + secondHalf);
for(int i = 0, j = 0; i < firstHalf.length(); i++, j++) {
sb = sb.append(secondHalf.charAt(i));
if(j < secondHalf.length()) {
sb = sb.append(firstHalf.charAt(i));
}
str = sb.toString();
}
loop++;
} while (loop <= shuffle);
return str;
}
#Override
public String encode(String plainText) {
String shuffled;
shuffled = shuffleEncryption(plainText);
return shuffled;
}
}
You are not setting the shuffle member variable in the constructor.
Change this:-
public ShuffleCipher(int shuffle) {
shuffle = this.shuffle;
}
to this:-
public ShuffleCipher(int shuffle) {
this.shuffle = shuffle;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Can someone help me check ?
error:
java.lang.NullPointerException
How do I remove this error ?
my main Class:
public class deck {
public static void main(String[] args) {
Deck app = new Deck();
app.Deck();
}
}
my Deck class:
public class Deck {
public int TOTALCARDS;
Card[] d;
public int nH;
public void createDeck() {
String[] suitsArray = new String[4];
for(int i=0; i<numArray.length; i++) {
numArray[i] = i+1;
}
for (int i=0; i<13; i++) {
if (i!=11){
deck[i+25] = new Card(suitsArray[2], i+1);
}
else if(i > 10){
deck[i+25] = new Card(suitsArray[2], i+1);
}
}
for (int i=0; i<13; i++) {
deck[i+25].display();
}
}
This is the Card Class.
public class Card {
public String suit;
public int number;
public Card(String s, int n){
this.suit = s;
this.number = n;
}
public String words;
public String getTitle(){
String
if (number == 1){
words = " Ace";
}
else if (number ==3){
words = " Three";
}
else if (number ==4){
words = " Four";
}
else if (number ==5){
words = " Five";
}
else if (number ==6){
words = " Six";
}
else if (number ==7){
words = " Seven";
}
else if (number ==8){
words = " Eight";
}
else if (number ==9){
words = " Nine";
}
else if (number ==10){
words = " Ten";
}
else if (number ==11){
words = " Jack";
}
else if (number ==12){
words = " Queen";
}
else if (number ==13){
words = " King";
}
displayTitle = suit + words;
if (displayTitle.equalsIgnoreCase("Diamond Queen")){
displayTitle= "DIAMOND QUEEN";
}
return (displayTitle);
}
public void display(){
System.out.println("< " + get() + " >");
}
}
When I run the code I got
Hearts Ace
Hearts Two
Hearts Three
Hearts Four
Hearts Five
Hearts Six
Hearts Seven
Hearts Eight
Hearts Nine
Hearts Ten
Hearts Jack
Exception in thread "main" java.lang.NullPointerException
at Deck.createDeck(Deck.java:57)
at Deck.<init>(Deck.java:9)
at deckMain.main(deckMain.java:5)
EDIT: See the comment by Kick Buttowski below, this is at best a partial answer.
You're calling Card.display()
for (int i=0; i<13; i++) {
deck[i+25].display();
}
Which in turn calls Card.getTitle()
public void display(){
System.out.println("< " + getTitle() + " >");
}
The problem lies there:
public String getTitle(){
String displayTitle = suit + words; // <-- Problem
if (number == 1){
words = " Ace";
}
// ...
At the marked line, words is not set yet, so it's null. Accessing its value will raise a NullPointerException.
As Takendarkk pointed out, you can overcome this with minimal changes to your code by initialising it either in your constructor or in the declaration:
public class Card {
// ...
String words = "";
Or, since (as far as we know) words is only used within display(), move it there:
public void display() {
String words = ""; // Still need to be initialised
// ...
EDIT: Your card size is 51 ... it should be 52
if (i!=11){
deck[i+25] = new Card(suitsArray[2], i+1);
}
else if(i > 11){
deck[i+25] = new Card(suitsArray[2], i+1);
}
This doesn't add up, what if i = 11?? You do nothing as
i!=11 = false and i > 11 == false;
this means the else if (i > 11) will never execute.
also your code does the exact same thing??
if you are trying to initalise all 52 cards you can do something like:
for (int i=0;i<deck.size;i++) {
deck[i] = new Card(suitsArray[i/13], numArray[i % 13]);
EDIT: after more of an explanation of what you are doing .....
for (int i=0, j=0;j<deck.length;i++) {
if ((i/13) == 2 && (i%13) == 11)
continue;
deck[j++] = new Card( suitsArray[i/13], (i % 13));
}
also in card have (much clearer)
static String[] titles = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
and
public String getTitle() {
return suit + " " + titles[number];
}
It is because your value at deck[11] is null because you skipped putting an instance of Card at that index.
edit: [should be deck[i + 25]], where i = 11;
Regarding the answers pointing to the variable word being null as reason of NPE. I doubt this. I have tried the code in my machine and it is not giving me NPE. (see also Concatenating null strings in Java)
I want to create a class that would return an array of pairs that have the same length as the input array of strings.
In addition, the pair should have the first letter of the string and length of the string.
for example;
create(new String[] {"clue", "yay", "neon", "halala"})
should return the array of Pairs
{[’c’,4],[’y’,3],[’n’,4],['h',6]}
So, my input and output would both be arrays. But the output has to be in the form of a pair. Here's what i tried:
import java.util.Arrays;
public class Couple {
public static Couple[] create(String[] source){
for (int i = 0; i < source.length; i++) {
System.out.print("["+","+source.length+"]") ;
}
return null;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(create(new String[] {"clue", "yay", "neon", "halala"})));
}
}
as it's obvious there are a few errors+ i dont want it to return null. But just for the sake of testing this code, i had to do it.
Any ideas?
public class Couple {
private char firstChar;
private int length;
public Couple(char firstChar, int length) {
this.length = length;
this.firstChar = firstChar;
}
public static Couple[] create(String[] source) {
Couple[] couples = new Couple[source.length]; // create the array to hold the return pairs
for (int i = 0; i < source.length; i++) {
String entry = source[i];
if (entry != null) {
couples[i] = new Couple(entry.charAt(0), entry.length());
} else {
// What do you want to do if there's a null value?
// Until you answer this we'll just leave the corresponding Couple null aswell
}
}
return couples;
}
#Override
public String toString() {
return "Couple{" +
"firstChar=" + firstChar +
", length=" + length +
'}';
}
}
You are on the right track:
Rather than returning null, you should create an array of pairs, and populate it in the loop. You know the length of the result, because you have the length of the source
To look at an individual word, use source[i]
To chop off the initial letter of the word use source[i].charAt(0)
To get the length of the word use source[i].length()
The Couple class needs two data members - a char and an int; they should be set in the constructor
The data members should have getters - public char getChar() and public int getLength() returning their respective members
Printing should be done in the main, in a loop that walks the returned array of pairs
You should be able to complete the rest.
The hint you probably need it this:
Couple[] result = new Couple[source.length];
and code a loop to create the Couple instances and put them into the result array.
Use this code:
import java.util.Arrays;
public class Couple {
public static String[] create(String[] source) {
String[] temp = new String[source.length];
for (int i = 0; i < source.length; i++) {
if (source[i].length() > 0) {
String newString = "[" + source[i].charAt(0) + ","
+ source.length + "]";
//System.out.print(newString);
temp[i] = newString;
} else {
String newString = "[" + " " + "," + 0 + "]";
//System.out.print(newString);
temp[i] = newString;
}
}
return temp;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(create(new String[] { "clue", "yay",
"neon", "halala"})));
}
}