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;
}
Related
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");
}
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;
}
How can I input a String and an int in the same line? Then I want to proceed it to get the largest number from int that I already input:
Here is the code I have written so far.
import java.util.Scanner;
public class NamaNilaiMaksimum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name[] = new String[6];
int number[] = new int[6];
int max = 0, largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
name[x] = in.nextLine();
number[x] = in.nextInt();
}
for (int x = 1; x <= as; x++) {
if (number[x] > largest) {
largest = number[x];
}
}
System.out.println("Result = " + largest);
}
}
There's an error when I input the others name and number.
I expect the output will be like this
Name & Number : John 45
Name & Number : Paul 30
Name & Number : Andy 25
Result: John 45
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String InputValue;
String name[] = new String[6];
int number[] = new int[6];
String LargeName = "";
int largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
InputValue = in.nextLine();
String[] Value = InputValue.split(" ");
name[x] = Value[0];
number[x] = Integer.parseInt(Value[1]);
}
for (int x = 1; x < number.length; x++) {
if (number[x] > largest) {
largest = number[x];
LargeName = name[x];
}
}
System.out.println("Result = " + LargeName + " " + largest);
}
Hope this works for you.
System.out.print(" Name & number : ");
/*
Get the input value "name and age" separated with space " " and splite it.
1st part is name and second part is the age as tring format!
*/
String[] Value = in.nextLine().split(" ");
name[x] = Value[0];
// Convert age with string format to int.
number[x] = Integer.parseInt(Value[1]);
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^^
}
}
In the below code I have taken three sets of values (i<3) in the first for loop. I am able to compute the same data using different integers, e.g. i<5, i<6. Please suggest a way where I can get the number of values that are being entered on the console and then use them as <(number of values entered/2).
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("please enter 3 birth - death pairs");
List<Dinosaur> dinoList = new ArrayList<Dinosaur>();
// int dinoStrength=s.nextInt();
for (int i = 0; i <3; i++)
{
int num1 = s.nextInt();
int num2 = s.nextInt();
Dinosaur d = new Dinosaur(num1, num2);
dinoList.add(d);
}
//System.out.println(dinoList);
Collections.sort(dinoList);
//System.out.println(dinoList);
int maxCount = 0;
List<String> ls=new ArrayList<String>();
for (Dinosaur dino : dinoList)
{
// System.out.println("start date" + dino.getStartDate());
// System.out.println("end date"+ dino.getEndDate());
int count = 0;
for (Dinosaur dino2 : dinoList) {
if (dino2.getStartDate() <= dino.getEndDate()
&& dino2.getEndDate() >= dino.getStartDate())
count++;
}
//System.out.println(count);
if (maxCount < count) {
maxCount = count;
ls.clear();
ls.add(dino.getStartDate()+"-"+dino.getEndDate());
}
else if(maxCount==count)
{
ls.add(dino.getStartDate()+"-"+dino.getEndDate());
}
}
//System.out.println(maxCount);
//System.out.println(ls);
System.out.println("Max no of Dinos alive at the same time :"+maxCount);
}
Scanner s = new Scanner(System.in);
System.out.println("please enter 3 birth - death pairs");
List<Dinosaur> dinoList = new ArrayList<Dinosaur>();
// int dinoStrength=s.nextInt();
while(s.hasNextInt())
{
int num1 = s.nextInt();
int num2 = s.nextInt();
if(num2 ==num1)//Your condition(Here I assume date of birth should not be equal to death date.)
break;
Dinosaur d = new Dinosaur(num1, num2);
dinoList.add(d);
}
You can try something like this .