How to use 2D arrays with other classes - java

I have an assignment, I was wondering how I could go about using 2D arrays with another class, I have a class called Die that looks like this:
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
public Die()
{
faceValue = 1;
}
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
public void setFaceValue(int value)
{
faceValue = value;
}
public int getFaceValue()
{
return faceValue;
}
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
Now in a main method i have to do the following
I have all the other parts done, I just cant seem to figure out this part.
My current code(Not started this part) is below
import java.util.Arrays;
import java.util.Scanner;
class ASgn8
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt();
scan.nextLine();
String[] playerNames = new String[playerCount];
int again = 1;
for(int i = 0; i < playerCount; i++)
{
System.out.print("What is your name: ");
playerNames[i] = scan.nextLine();
}
int randomNum = (int)(Math.random() * (30-10)) +10;
}
}
Do any of you java geniuses have any advice for me to begin?
Thanks!

Here is your main method, you just need to update your main method with this one,
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt();
scan.nextLine();
HashMap<String, ArrayList<Die>> hashMap = new HashMap<String, ArrayList<Die>>();
int again = 1;
for(int i = 0; i < playerCount; i++)
{
System.out.print("What is your name: ");
hashMap.put(scan.nextLine(),new ArrayList<Die>());
}
for(String key : hashMap.keySet()){
System.out.println(key + "'s turn....");
Die d = new Die();
System.out.println("Rolled : " + d.roll()) ;
hashMap.get(key).add(d);
System.out.println("Want More (Yes/No) ???");
String choice = scan.next();
while(choice != null && choice.equalsIgnoreCase("YES")){
if(hashMap.get(key).size()>4){System.out.println("Sorry, Maximum 5-Try you can...!!!");break;}
Die dd = new Die();
System.out.println("Rolled : " + dd.roll()) ;
hashMap.get(key).add(dd);
System.out.println("Want More (Yes/No) ???");
choice = scan.next();
}
}
for(String key : hashMap.keySet()){
System.out.println(key + " - " + hashMap.get(key));
}
}
EDITED
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt(); // get number of participant player...
scan.nextLine();
Die[] tempDie = new Die[5]; // temporary purpose
Die[][] finalDie = new Die[5][]; // final array in which all rolled dies stores...
String [] playerName = new String[playerCount]; // stores player name
int totalRollDie = 0; // keep track number of user hash rolled dies...
for(int i = 0; i < playerCount; i++) // get all player name from command prompt...
{
System.out.print("What is your name: ");
String plyrName = scan.nextLine();
playerName[i] = plyrName;
}
for(int i = 0; i < playerCount; i++){
System.out.println(playerName[i] + "'s turn....");
totalRollDie = 0;
Die d = new Die();
System.out.println("Rolled : " + d.roll()) ;
tempDie[totalRollDie] = d;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
String choice = scan.next();
while(choice != null && choice.equalsIgnoreCase("YES")){
if(totalRollDie < 5){ // if user want one more time to roll die then first check whether alread user has rolled 5-time or not.
Die dd = new Die();
System.out.println("Rolled : " + dd.roll()) ; // rolled and print whatever value get..
tempDie[totalRollDie] = dd;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
choice = scan.next();
}
}
finalDie[i] = new Die[totalRollDie];
for(int var = 0 ; var < totalRollDie ; var++){
finalDie[i][var] = tempDie[var]; // store Die object into finalDie array which can random number for all user..
}
}
for(int i = 0 ;i < playerCount ; i++){ // finally print whatever user's roll value with all try...
System.out.println(" --------- " + playerName[i] + " ------------ ");
for(Die de : finalDie[i]){
System.out.println(de);
}
}
tempDie = null;
}

Related

Bubble sort and input

I have to enter 3 jumpers who will jump 2 times.
Here is an illustration via my console for the first jump. (it's step is ok)
Then, for the second jump. I have to sort the first jump from the smallest to the biggest.
So, I have to retrieve the jumper Emilie and not Olivia.
I don't understand how to do this ?
I think my problem is my sortBublle() method ?
import java.util.*;
class Main {
public static void main(String[] args) {
String[] arrayJumper = new String[3];
int[] arrayJump = new int[3];
encoding_jump_1(arrayJumper, arrayJump);
sortBublle(arrayJump);
encoding_jump_2(arrayJumper, arrayJump);
}
public static void encoding_jump_1(String[] arrayJumper, int[] arrayJump){
Scanner input = new Scanner(System.in);
int iJumper = 0;
int iJump = 0;
System.out.println("Jump 1 : ");
for(int i=0; i<arrayJumper.length; i++){
System.out.print("Enter jumper " + (i+1) + " : ");
String jumper = input.next();
arrayJumper[iJumper++] = jumper;
System.out.print("Enter for the jumper " + arrayJumper[i] + " the first jump please : ");
int jump = input.nextInt();
while(jump <= 9 || jump >=111){
System.out.print("Error ! The jump should to be between 10 and 100 please : ");
jump = input.nextInt();
}
arrayJump[iJump++] = jump;
}
}
public static void sortBublle(int[] arrayJump){
int size = arrayJump.length;
int tempo = 0;
for(int i=0; i<size; i++){
for(int j=1; j < (size - i) ; j++){
if(arrayJump[j-1] > arrayJump[j]){
tempo = arrayJump[j-1];
arrayJump[j-1] = arrayJump[j];
arrayJump[j] = tempo;
}
}
}
}
public static void encoding_jump_2(String[] arrayJumper, int[] arrayJump){
Scanner input = new Scanner(System.in);
int iJump = 0;
System.out.println("Jump 2 : ");
for(int i=0; i<arrayJumper.length; i++){
System.out.print("Enter for the jumper " + arrayJumper[i] + " the second jump please : ");
int jump = input.nextInt();
while(jump <= 9 || jump >=111){
System.out.print("Error ! The jump should to be between 10 and 100 please : ");
jump = input.nextInt();
}
arrayJump[iJump++] = jump;
}
}
}
Thank you very much for your help.
You are only sorting arrayJump --> You need to sort both arrayJumper and arrayJump`
...
if(arrayJump[j-1] > arrayJump[j]){
tempo = arrayJump[j-1];
arrayJump[j-1] = arrayJump[j];
arrayJump[j] = tempo;
tempName = arrayJumper[j-1];
arrayJumper[j-1] = arrayJumper[j];
arrayJumper[j] = tempName;
}

Compare scanner input to array

Idea:
User inputs their bets by typing either 'W','L' or 'T' (wins, losses or tie). Program generates random results within these parameters. User input and result gets printed, and a score is presented based on correct bets, which is supplied by the program.
Im having issues on how to proceed with comparing user generated input from scanner to an arraylist that produces a random result.
If it were not for the multiple "questions" and "answers" I could use a (val.equals(input)) of sort. However, each individual bet is random and must be matched against the users bets to sum up the users score, that complicates it.
Any help appreciated.
public class test3 {
public static void main(String[] args) {
int score = 0;
System.out.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
String array[] = new String[5];
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter your bet:");
array[i]=input.nextLine();
}
List<String> list = new ArrayList<String>();
list.add("w");
list.add("l");
list.add("t");
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:");
test3 obj = new test3();
for(int i = 0; i < 5; i++){
System.out.print(obj.getRandomList(list) + " ");
}
System.out.println("\n\nYour bets were:");
for (int i = 0; i < 5; i++){
System.out.print(array[i] + " ");
}
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
private Random random = new Random();
public String getRandomList(List<String> list) {
int index = random.nextInt(list.size());
return list.get(index);
}
}
One way to do this is in the code below.
You basically need to compare each element of your input with each element of the random list so run loop.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Test {
private Random random = new Random();
public static void main(String[] args) {
int score = 0;
System.out
.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
String array[] = new String[5];
for (int i = 0; i < 5; i++) {
System.out.println("Please enter your bet:");
array[i] = input.nextLine();
}
System.out.println("\n\nYour bets were:");
for (int i = 0; i < 5; i++) {
System.out.print(array[i] + " ");
}
List<String> list = new ArrayList<String>();
list.add("w");
list.add("l");
list.add("t");
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:");
Test obj = new Test();
List<String> randList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
randList.add(obj.getRandomList(list));
}
for(String randBet : randList){
System.out.print( randBet + " ");
}
System.out.println("");
int counter = 0;
for (String yourbet: Arrays.asList(array)){
if(randList.get(counter).equals(yourbet)){
score++;
}
counter++;
}
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
public String getRandomList(List<String> list) {
int index = random.nextInt(list.size());
return list.get(index);
}
}
I removed test3 for simplicity, but basically you need save results on array and generate random results and saving them (i.e a list). Then you have to iterate through and compare each game result, and if your bet is correct, just add one to score. Check the code below:
Main:
public static void main(String[] args) {
int score = 0;
String array[] = new String[5];
List < String > randomResultList = new ArrayList<String> ( );
System.out.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter your bet:");
array[i]=input.nextLine();
}
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:");
for(int i = 0; i < 5; i++){
String randomResult = getRandomList();
System.out.print( randomResult + " ");
randomResultList.add ( randomResult );
}
System.out.println("\n\nYour bets were:");
for (int i = 0; i < 5; i++){
System.out.print(array[i] + " ");
}
//here is where you compare each result
for(int i = 0; i < 5; i++)
{
if( array[i].equals ( randomResultList.get ( i ) ))
{
score++;
}
}
System.out.println("\n\nYou were correct on: " + score + " bettings");
}
private static Random random = new Random();
public static String getRandomList() {
List<String> list = Arrays.asList("w", "l", "t");
int index = random.nextInt(list.size());
return list.get(index);
}
I/O Example:
Betting game initiating...
Type 'W' for win, 'L' for loss and 'T' for tie.
Please enter your bet:
w
Please enter your bet:
w
Please enter your bet:
w
Please enter your bet:
w
Please enter your bet:
w
This week wins, losses and ties loading...
Result:
l l l t w
Your bets were:
w w w w w
You were correct on: 1 bettings
Extra:
You could do all on the same iteration! check this out.
public static void main(String[] args) {
int score = 0;
// Win Loose or Tie
List<String> list = Arrays.asList("w", "l", "t");
Random rand = new Random ( );
//String with result and bets i.e (wwwww) and (wlltw). This avoid another iteration.
String result="";
String bets = "";
System.out.println("Betting game initiating... \nType 'W' for win, 'L' for loss and 'T' for tie.");
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++)
{
System.out.println("Please enter your bet:");
String bet =input.nextLine();
String randomResult = ( list.get ( rand.nextInt ( list.size ( ) ) ));
//concatenate String with results and bets with +=
result += randomResult;
bets += bet;
//check if u won
if( bet.equals ( randomResult ))
{
score++;
}
}
//This are just the results! no more iterations.
System.out.println("This week wins, losses and ties loading...\n");
System.out.println("Result:" + result);
System.out.println("\n\nYour bets were:" + bets );
System.out.println("\n\nYou were correct on: " + score + " bettings");
}

applying lambda expression in java

Here's my code.I'm not yet familliar with lambda expressions in java 8.
I'd like to apply a lambda expression here doing a random generation of healthy and unhealthy horses.
Then I'll print and run only the healthy horses. How can I do that?
import java.util.Scanner;
import java.util.Random;
public class HorseRace {
static int numHorse = 0;
static int healthyHorse = 0;
public static void main(String[] args) {
//int unhealthyHorse = 0;
Random randomGenerator = new Random();
Scanner input = new Scanner(System.in);
int counter = 0;
do {
System.out.print("Enter number of horses: ");
while (!input.hasNextInt()) {
input.next();
}
numHorse = input.nextInt();
} while (numHorse < 2);
input.nextLine();
Horse[] horseArray = new Horse[numHorse];
while (counter < horseArray.length) {
System.out.print("Name of horse " + (counter + 1) + ": ");
String horseName = input.nextLine();
String warCry = "*****************" + horseName + " says Yahoo! Finished!";
int healthCondition = randomGenerator.nextInt(2);
if (healthCondition == 1) {
horseArray[counter] = new Horse(warCry);
horseArray[counter].setName(horseName);
System.out.println(horseArray[counter]);
System.out.println(this);
System.out.println(healthyHorse);
//unhealthyHorse++;
}
counter++;
}
System.out.println(horseArray.length);
System.out.println("...Barn to Gate...");
for (int i = 0; i < healthyHorse; i++) {
horseArray[i].start();
}
}
}
I have refactored some of the code and used Lambda expressions wherever possible.
public class HorseRace {
public static void main(String[] args) {
//int unhealthyHorse = 0;
Random randomGenerator = new Random();
Scanner input = new Scanner(System.in);
int counter = 0;
int numHorse;
do {
System.out.print("Enter number of horses: ");
while (!input.hasNextInt()) {
input.next();
}
numHorse = input.nextInt();
} while (numHorse < 2);
input.nextLine();
List<Horse> horses = new ArrayList<>();
while (counter < numHorse) {
System.out.print("Name of horse " + (counter + 1) + ": ");
String horseName = input.nextLine();
String warCry = "*****************" + horseName + " says Yahoo! Finished!";
int healthCondition = randomGenerator.nextInt(2);
if (healthCondition == 1) {
Horse horse = new Horse(warCry);
horse.setName(horseName);
horses.add(horse);
}
counter++;
}
horses.forEach(horse -> {
System.out.println(horse);
System.out.println(0);
});
System.out.println(horses.size());
System.out.println("...Barn to Gate...");
horses.forEach(Horse::start);
}
}
Lambda expression is used as below:

How to arrange an array in descending order alongside a string array

here is my code... I need all the contestants to be ranked according to their votes... as you can see there are seperate arrays for the names and vote count(tally)... I was told that bubble sort would work but i cant see how because bubble sort replaces the insides so if tally[2] is greater than tally[1], it will become the new tally[1] meanwhile the name stays the same as name[1] does not change with name[2]...I would prefer that you use basic codes as i am a total noob with programming and have only recently started...also, any recommendations about how i can write my code better/shorter is appreciated
import java.util.*;
public class FroshNight {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String dec = "0";
System.out.println("How many blocks?");
int contno = sc.nextInt();
int winner = 0;
String winname = "a";
String[] code = new String[contno];
int total = 0;
int counter = 0;
String[] contname = new String[contno];
int[] tally = new int[contno];
while (counter<contno) {
System.out.print("Name of Pair:");
contname[counter]=sc.next();
counter++;
}
counter=0;
while (counter<contno) {
System.out.println("Choose a vote code for "+ contname[counter]+"(must not be x)");
code[counter] = sc.next();
counter++;
}
boolean stop = false;
counter=0;
while(stop == false){
System.out.println("Input Vote (x to exit): ");
dec = sc.next();
if(dec.equals("x")) {
stop = true;
}
counter = 0;
while(counter<contno){
if(dec.equals(code[counter])){
tally[counter] +=1;
counter = contno;
}
counter++;
}
}
//>> aft. else
counter = 0;
while(counter<contno){
total += tally[counter];
counter++;
;
}
counter=0;
while(counter<contno){
if(tally[counter]>winner){
winner = tally[counter];
winname = contname[counter];
}
counter++;
}
System.out.print("The Winner is: "+ winname +" - "+winner );
System.out.println("("+((double)winner/total)*100+"%)");
counter = 0;
while (counter<contno) {
System.out.print(contname[counter]+" - Score:");
System.out.print(tally[counter]);
System.out.println("("+((double)tally[counter]/total)*100+"%)");
counter++;
}
//>>> end while
// add rankings here^^
}
}

code is just continue looping.How to solve?

import java.util.Scanner;
public class TestPerson
{
/**
* Creates a new instance of <code>TestPerson</code>.
*/
public TestPerson()
{
}
/**
* #param args
* the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Menus[] menu = { new Menus("Add Member") };
MemberType[] m = { new MemberType("Corporate Member"), new MemberType("VIP Member") };
Clubs[] c = { new Clubs("Yoga", "Miss AA"), new Clubs("Kick-boxing", "Mr.AA"), new Clubs("aerobics", "Mrs.Wendy") };
RegMember[] r = new RegMember[1];
Cmember cm;
Vipmember vip;
Scanner s = new Scanner(System.in);
int choice = 0;
for (int z = 0; z < menu.length; z++)
{
System.out.println((z + 1) + ". " + menu[z].toString());
}
System.out.println("\nEnter Your selection:");
int choice = s.nextInt();
while (choice == 1)
{
for (int i = 0; i < r.length; i++)
{
System.out.println("\nYour reg no is :" + (RegMember.getNextNo() + 1));
for (int a = 0; a < m.length; a++)
{
System.out.println((a + 1) + ". " + m[a].toString());
}
System.out.println("\nEnter Your selection:");
int sel = s.nextInt();
if (sel == 1)
{
s.nextLine();
System.out.println("Enter name:");
String Name = s.nextLine();
System.out.println("Enter Handphone:");
String Hpnum = s.next();
System.out.println("Enter Age:");
int age = s.nextInt();
System.out.println("Enter Company Name:");
String CompanyName = s.nextLine();
String memberType = "Corporate Member";
for (int b = 0; b < c.length; b++)
{
System.out.println((b + 1) + ". " + c[b].toString());
}
System.out.println("\nEnter Your selection:");
int sel2 = s.nextInt();
String clubs = "Yoga";
cm = new Cmember(Name, Hpnum, age, CompanyName, memberType, clubs);
r[i] = new RegMember(cm);
}
else
{
s.nextLine();
System.out.println("---You will get a free exercise class---");
System.out.println("Enter name:");
String Name = s.nextLine();
System.out.println("Enter Handphone:");
String Hpnum = s.next();
System.out.println("Enter Age:");
int age = s.nextInt();
System.out.println("Enter Email:");
String email = s.next();
String memberType = "VIP Member";
vip = new Vipmember(Name, Hpnum, age, email, memberType);
r[i] = new RegMember(vip);
}
s.nextLine();
}
}
displayInfor(r);
}
public static void displayInfor(RegMember[] r)
{
for (int i = 0; i < r.length; i++)
System.out.println(r[i].toString());
}
}
I am a beginner for java. I am facing the problem that my code is continue looping.How to solve it?? thank you.
Your choice variable is never set to not = 1. Therefore the while loop will continue to run forever.
edit: With the amount of log messages in that code you should be able to see where surely.
If you are using If statements as such why not just alter the choice variable manually.
Anyway its too vague your question specify which loop and it would be easier to help

Categories

Resources