I wrote this code that random picks two cards from a deck, but I'm having trouble trying to get it to compare, I've run into some issues and want to work that out step by step but unsure how to compare both statements with only one defined variable?
package question1;
public class HouseOfCards {
public static void main(String[] args) {
String [] SuitNames= {
"Spades","Diamonds","Clubs","Hearts"
};
String [] CardNames= {
"Ace","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"
};
String SuitName="hi",SuitName2="die";
String CardName="hi", CardName2="die";
for (int i=0; i<=1; i++){
int numCard=52;
int randNum=(int)(Math.random() * numCard);
int randNum2=(int)(Math.random() * numCard);
int suitNum = randNum / 13;
int cardNum = randNum % 13;
int suitNum2 = randNum2 / 13;
int cardNum2 = randNum2 % 13;
SuitName = SuitNames[suitNum];
CardName = CardNames[cardNum];
SuitName2 = SuitNames [suitNum2];
CardName2 = CardNames[cardNum2];
System.out.println(CardName + " of " + SuitName);
}
if (CardName.equals(CardName2)){
System.out.println("Same Rank");
}
else if (SuitName.equals(SuitName2)){
System.out.println("Same Suit");
}
}
}
i edited my code so that it displays if its the same rank between both random picked cards or same suit between random picked cards, but sometime it doesn't print the statement, why?
Try something like this:
public class HouseOfCards {
public class HouseOfCards {
public static void main(String[] args) {
int Spades=1;
String [] suitNames= {
"Spades","Diamonds","Clubs","Hearts"
};
String [] cardNames= {
"Ace","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"
};
String card1="";
String card2="";
String suitName="";
String cardName1="";
String suitName2="";
String cardName2="";
int cardPosition1 = 0;
int cardPosition2 = 0;
for (int i=0; i<=1; i++){
int numCard=52;
int randNum=(int)(Math.random() * numCard);
int suitNum = randNum / 13;
int cardNum = randNum % 13;
if(i==0) {
suitName = suitNames[suitNum];
cardName1 = cardNames[cardNum];
card1 = cardName1+" of "+suitName;
}
else {
suitName2 = suitNames[suitNum];
cardName2 = cardNames[cardNum];
card2 = cardName2+" of "+suitName2;
}
}
System.out.println(card1);
System.out.println(card2);
for (int i = 0; i < cardNames.length; i++) {
if(cardName1.equals(cardNames[i])) {
cardPosition1 = i;
}
if(cardName2.equals(cardNames[i])) {
cardPosition2 = i;
}
}
System.out.println(cardPosition1);
System.out.println(cardPosition2);
if(cardPosition1>cardPosition2) {
System.out.println("First card has bigger number");
}
else if (cardPosition1<cardPosition2) {
System.out.println("Second card has bigger number");
}
else if (cardPosition1==cardPosition2) {
System.out.println("Equal cards (probably different suites you can check it further)");
}
}
}
Related
I am working on a selection sort in Java. It will prompt a user to enter in 10 names and then sort them alphabetically. It is sorting some of them but not completely and cannot figure out why it is sorting some values and not others. I believe I have implemented the sort and swap correctly but I feel as though I am missing something. Any help is appreciated as always.
import java.util.*;
public class sortingProgram {
static String studentName[] = new String[10];
static int i;
static Scanner scnr = new Scanner(System.in);
public static void enterNames() {
for (i = 0; i < studentName.length; i++) {
System.out.println("Please enter a student name: ");
studentName[i] = scnr.nextLine();
}
}
public static void sortNames(String sortArray[]) {
int smallindex;
for (int i = 0; i < sortArray.length; i++) {
smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
if (smallindex != i)
swap(sortArray, smallindex, i);
}
}
}
System.out.println(Arrays.toString(sortArray));
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
enterNames();
sortNames(studentName);
}
}
You are doing your swap too early. You need to wait until the smallest has been determined before swapping. You are swapping whenever you detect a smaller one.
public static void sortNames(String sortArray[]) {
for (int i = 0; i < sortArray.length; i++) {
int smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
// Move this.
//if (smallindex != i)
// swap(sortArray, smallindex, i);
}
}
// To here.
if (smallindex != i)
swap(sortArray, smallindex, i);
}
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
private void test() {
String[] names = {"C", "B", "A", "9"};
System.out.println(Arrays.toString(names));
sortNames(names);
System.out.println(Arrays.toString(names));
}
use below changes in your program.
import java.util.*;
public class SortingProgram {
static String studentName[] = new String[10];
static int i;
static Scanner scnr = new Scanner(System.in);
public static void enterNames() {
for (i = 0; i < studentName.length; i++) {
System.out.println("Please enter a student name: ");
studentName[i] = scnr.nextLine();
}
}
public static void sortNames(String sortArray[]) {
int smallindex;
for (int i = 0; i < sortArray.length; i++) {
smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
//if (smallindex != i) No need here
//swap(sortArray, smallindex, i);
}
}
//place your swaping code here
if (smallindex != i)
swap(sortArray, smallindex, i);
}
System.out.println(Arrays.toString(sortArray));
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
enterNames();
sortNames(studentName);
}
}
after making these changes your program works. your code not works properly because you perform swap early.
I am trying to display the first 20 fibbonacci numbers using the model view controller method in java. However the output that I am getting is only the last number(the first 19 are not displaying) if anyone is able to look through my code and point out where im going wrong that would be awesome :)
public class FibonacciModel {
public String fibModel(int a, int b, int c, int count){
String result = "";
//int c;
while(count!=20) // if you want first 100 fibonacci numbers then change 20 to 100 accordingly
{
c=a+b;
count++;
result = c + " ";
a=b;
b=c;
}
return result;
}
}
public class FibonacciController {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 1;
int b = 1;
int count = 2;
int c = 0;
FibonacciModel Model = new FibonacciModel();
FibonacciView View = new FibonacciView();
View.say(Model.fibModel(a, b, c, count));
}
}
public class FibonacciView {
public < T > void say( T word ){
System.out.print(word);
}
}
You're overwriting your result variable. Try result = result + c + " "; or result += c + " ";
Check this out :)
public static void getFibbonacci(int n){
int total = 0;
int prev = 1;
for (int x=1; x<n; x++){
total = total + prev;
prev = total - prev;
System.out.println(total);
}
}
public class fibbo {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a;
System.out.println("Enter the number");
a = sc.nextInt();
int first = 0;
int second = 1;
int third;
System.out.print("Fibbonacci series is= ");
System.out.print("\t" + first + "\t" + second + "\t");
for (int i = 0; i < a - 2; i++) {
third = first + second;
first = second;
second = third;
System.out.print(third + "\t");
}
}
I am new to programming and don't get why the program gives me a run time error for NullPointerException when I have tried initializing n, numInt, and arrayMenu. None of which seem to work. The program's job is to gather a set of random integers to store in an array and allow the user to pick which sort to choose from. Thanks for reading.
import java.util.Scanner;
import java.util.Random;
public class VariousSortsHS
{
private static int[] arrayMenu;
private static Random generator;
/**
* Constructor for objects of class VariousSortsHS.
*/
public VariousSortsHS(int n) //The error starts here
{
arrayMenu = new int[n]; //I don't get why it says null in the array when
//i am initializing the length of the array to n
/*Assigns a random number between 0 too 100.*/
for(int i = 0; i < n; i++)
{
int temp = generator.nextInt(100);
arrayMenu[n] = temp;
}
}
/**
* Selection Sort method.
*/
public static void selection(int n)
{
for(int i = 0; i < arrayMenu.length - 1; i++)
{
int minPos = i;
for(int j = i + 1; j < arrayMenu.length; j++)
{
if(arrayMenu[j] < arrayMenu[minPos]) minPos = j;
}
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[minPos];
arrayMenu[minPos] = temp;
System.out.print(temp + " ");
}
}
/**
* Insertion Sort method.
*/
public static void insertion(int n)
{
for(int i = 1; i < arrayMenu.length; i++)
{
int next = arrayMenu[i];
int j = i;
while(j > 0 && arrayMenu[j - 1] > next)
{
arrayMenu[j] = arrayMenu[j - 1];
j--;
}
arrayMenu[j] = next;
System.out.print(next + " ");
}
}
/**
* Quick Sort method.
*/
public static void quick(int n)
{
int pivot = arrayMenu[0];
int i = 0 - 1;
int j = n + 1;
while(i < j)
{
i++; while(arrayMenu[i] < pivot) i++;
j++; while(arrayMenu[j] > pivot) j++;
if(i < j)
{
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[j];
arrayMenu[j] = temp;
System.out.print(temp + " ");
}
}
}
/**
* Main method that allows user to input data.
*/
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Do you wish to sort random integers? (Yes or No) ");
String answer = in.next();
String answer2 = answer.toLowerCase();
do
{
/*Prompts for array length.*/
System.out.println("How many random integers do you wish to sort?");
int numInt = in.nextInt();
/*Promps for sort selection choice.*/
System.out.println("Select a sort to use: \n\t1)Selection\n\t2)Insertion\n\t3)Quick");
String sort = in.next();
String sort2 = sort.toLowerCase();
if(sort2.equals("selection"))
{
selection(numInt);
}
else if(sort2.equals("insertion"))
{
insertion(numInt);
}
else if(sort2.equals("quick"))
{
quick(numInt);
}
else
{
System.out.println("You have entered the wrong input.");
}
} while(!answer2.equals("no"));
}
}
Everything in your code is static. This means the constructor you wrote is never called, and the array has never been changed from its default value, null. Consider changing your constructor code to a static initialization block instead.
generator is never set to anything, so it's null too and you can't call nextInt on it
initializing the array is setting arrayMenu[n] instead of arrayMenu[i]
When you call insertion(numInt);, method public static void insertion(int n) is called and then you are trying to do the for-loop like this for(int i = 1; i < arrayMenu.length; i++)
However, arrayMenu was not initialized, it is null. When you try to call a length, on null, you get NullPointerException.
You need to add a static constructor and initialize the size using a static int
//set parameter = n
public static int parameter;
static
{
arrayMenu = new int[parameter];
}
hi i am doing a coin toss simulator for java that must be done a certain way. it must have a string for sideup to hold the string of "heads" or "tails" made by a no arg constructor, the toss method must be void and it must have a getsideup method, then we must run the coin toss 20 times and diplay the number of heads and tails... i can do it easy with none void methods and just returning the result, but getting around this void and getsideup is driving me nuts.
this is what i have so far.
import java.util.Random;
public class coin {
public static String sideUp;
public static void toss() {
Random rand = new Random();
int sideup = rand.nextInt(2);
if (sideup == 0) {
sideUp = "heads";
} else {
sideUp = "tails";
}
}
public static String getsideup() {
System.out.println(sideUp);
return sideUp;
}
public static void main(String[] args) {
// coin coin = new coin();
int hcount = 0;
int tcount = 0;
for (int i = 1; i <= 20; i++) {
if (getsideup().equals("heads")) {
hcount++;
} else {
tcount++;
}
}
System.out.println("total heads = " + hcount + " total tails = " + tcount);
}
}
im hoping someone can tell me what im doing wrong and put me in the right direction.
You're not calling toss() at the beginning of your loop. That's required to set a value to sideUp, and required to give sideUp to change every toss.
The simple fix is put toss in your for loop before the if statement but I see a lot that can be done here. First I would add a constructor for the Coin class and add hcount and tcount to the class variables and make heads and tails constants:
private String sideUp;
private int hcount;
private int tcount;
private static final String HEADS = "Heads";
private static final String Tails = "Tails";
Coin()
{
this.sideUp = HEADS;
this.hcount = 0;
this.tcount = 0;
}
Then I would make a method to check the toss:
public void checkToss()
{
if (getsideup().equals(HEADS))
hcount++;
else
tcount++;
}
Now add the toss() and checkCoin() method to the for loop before the if statement. It should look like this:
for (int i = 1; i <= 20; i++)
{
coin.toss();
coin.checkToss();
}
I would also make a getter for the heads count and tails count:
public int getHeadsCount()
{
return this.hcount;
}
public int getTailsCount()
{
return this.tcount;
}
Everything put together looks like this:
import java.util.Random;
public class Coin
{
private String sideUp;
private int hcount;
private int tcount;
private static final String HEADS = "Heads";
private static final String TAILS = "Tails";
Coin()
{
this.sideUp = HEADS;
this.hcount = 0;
this.tcount = 0;
}
public void toss()
{
Random rand = new Random();
int sideup = rand.nextInt(2);
if (sideup == 0)
sideUp = HEADS;
else
sideUp = TAILS;
}
public String getsideup()
{
System.out.println(sideUp);
return sideUp;
}
public void checkToss()
{
if (getsideup().equals(HEADS))
this.hcount++;
else
this.tcount++;
}
public int getHeadsCount()
{
return this.hcount;
}
public int getTailsCount()
{
return this.tcount;
}
public static void main(String[] args)
{
Coin coin = new Coin();
for (int i = 1; i <= 20; i++)
{
coin.toss();
coin.checkToss();
}
System.out.println("Total Heads = " + coin.getHeadsCount() + " Total Tails = " + coin.getTailsCount());
}
}
import java.util.Random;
public class coin
{
public static String sideUp;
public int hcount=0;
public int tcount=0;
public static void toss()
{
Random rand = new Random();
int sideup = rand.nextInt(2);
if (sideup == 0)
{
sideUp = "heads";
hcount++;
}
else
{
sideUp = "tails";
tcount++;
}
}
public static void main(String[] args)
{
for(int i=0;i<20;i++)
{toss();}
System.out.println("total heads = " + hcount + " total tails = " + tcount);
}
}
for(int i = 1; i <= 20; i++)
{
toss();
if (getsideup().equals("heads"))
{
hcount++;
} else
{
tcount++;
}
}
Updated code:
import java.util.*;
public class Main {
/**
* #param args
*/
static int[] C;
static int[] D;
static String P;
public static void main(String[] args) {
C = new int[10];
D = new int[10];
getNumber();
}
private static void getNumber() {
System.out
.println("Enter your first number with spaces in between digits.");
Scanner S = new Scanner(System.in);
String O = S.nextLine();
String[] A = new String[10];
A = O.split(" ");
for (int X = 0; A.length > X; X++) {
C[X] = toNumber(A[X]);
}
String P = S.nextLine();
String[] B = new String[10];
B = P.split(" ");
for (int Y = 0; B.length > Y; Y++) {
C[Y] = toNumber(A[Y]);
}
System.out.print(C[0]);
remainders();
}
private static void remainders() {
for (int A = 0; C.length > A; A++) {
if (D[1] * C[A] >= 10) {
Integer B = new Integer(D[1] * C[A]);
Character E = B.toString().charAt(0);
P.concat(E.toString());
}
}
for (int A = 0; C.length > A; A++) {
if (D[0] * C[A] >= 10) {
Integer B = new Integer(D[1] * C[A]);
Character E = B.toString().charAt(0);
P.concat(E.toString());
}
}
System.out.print(P);
}
private static int toNumber(String string) {
if (string.equals("0")) {
return 0;
} else if (string.equals("1")) {
return 1;
} else if (string.equals("2")) {
return 2;
} else if (string.equals("3")) {
return 3;
} else if (string.equals("4")) {
return 4;
} else if (string.equals("5")) {
return 5;
} else if (string.equals("6")) {
return 6;
} else if (string.equals("7")) {
return 7;
} else if (string.equals("8")) {
return 8;
} else if (string.equals("9")) {
return 9;
} else {
return 0;
}
}
}
For some reason, the last thing it prints is null. I am pretty sure the problem is the toNumber method, but I can't figure out what's wrong. If there are other problems with the code other than this, please let me know. Please help.
Edit: Problem seems to be with remainder method, please help
Use the string.equals(n) method to test if string is n
String constants are compared this way: "0".equals(string). String literals are actual String objects and You can call any String method on them. And you should prefer to call methods on constants, because it's guaranteed they exists, whereas variables can be null.
You don't need to reinvent the wheel. Java has rich SDK.
Simply use
int x = Integer.valueOf(a[X]);
If you want only numbers 0-9, then simply test
if (0 <= x && x <= 9) {
//valid continue
} else {
//invalid state handling
}