Arrays and Sorting - java

My assignment asks me to write a program that will let the user input 10 players' name, age, position, and batting average. (For the sake of less confusion, I made the program input only 3 players). The program should then check and display statistics of only those players who are under 25 years old and have a batting average of .280 or better, then display them in order of age.
My code, shown below, is working perfectly until option 2 is selected. It is not sorting or showing anything. If someone could help me out it would mean so much. Any overall suggestions about my code will also be really helpful.Thank you.
import java.io.*;
import java.util.Scanner;
public class BlueJays {
static String name[] = new String[3]; //Name Array that can hold 10 names
static int age[] = new int[3]; //Age Array that can hold 10 ages
static String position[] = new String[3]; //Position Array that can hold 10 positions
static double average[] = new double[3]; //Average Array the can hold 10 batting averages
static int x, i;
//Main Method
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int menuChoice = 1;
System.out.print("Hello and Wlecome to Blue Jay Java Sort");
while (menuChoice != 3) {
System.out.print("\rEnter Menu Choice\n");
System.out.print("**********************");
System.out.print("\r(1) => Enter Blue Jay Data \n");
System.out.print("(2) => Display Possible Draft Choices \n");
System.out.print("(3) => Exit \r");
//try-catch statement for each case scenario
try {
menuChoice = Integer.parseInt(br.readLine());
} catch (IOException ie) {
ie.printStackTrace();
}
switch(menuChoice) {
case 1:
inputInfo();
break;
case 2:
inputSort();
break;
case 3:
return;
}
}
}
public static void inputInfo() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Scanner p = new Scanner(System.in);
//loop to request to fill array
for (x = 0; x < 3; x++) {
//Ask for player name
System.out.print("\rEnter player full name: ");
//Read input and store name in an Array
name[x] = in.readLine();
//Ask for player age
System.out.print("Enter age of player: ");
//Read input and store age in an Array
age[x] = p.nextInt();
//Ask for position of player
System.out.print("Enter player position: ");
//Read input and store position in an Array
position[x] = in.readLine();
//Ask for batting average of player
System.out.print("Enter batting average of player: ");
//Read input and store batting average in an Array
average[x] = p.nextDouble();
}
}
public static void inputSort() {
int smallest, temp;
//Selection Sort
for (x = 0; x < 3 - 1; ++x) {
smallest = x;
for(i = x + 1; i < 10; ++i) {
if (age[i] < age [smallest]) {
smallest = i;
}
}
temp = age [x];
age [x] = age [smallest];
age [smallest] = temp;
}
System.out.println(" Name " + " -----" + " Age " + "-----" + " Position " + "-----" + "Batting Average ");
for (x = 0 ; x < 3; x++) {
if (age[x] <= 25 && average[x] >= .280) {
System.out.println( name[x] + " ----- " + age[x] + " ----- " + position[x] + " ----- " + average[x]);
}
}
//Close Main()
}
//Close Class
}
`

Modificaton:
Here you need to make a small change in your program as shown below:
In inputSort() method, You need to change your for loop condition from for(i = x + 1; i < 10; ++i) to for(i = x + 1; i < 3; ++i).
You must be getting an error stating ArrayIndexOutOfBound because you were trying to access an index value that does not exist.
public class BlueJays {
static String name[] = new String[3]; //Name Array that can hold 10 names
static int age[] = new int[3]; //Age Array that can hold 10 ages
static String position[] = new String[3]; //Position Array that can hold 10 positions
static double average[] = new double[3]; //Average Array the can hold 10 batting averages
static int x, i;
//Main Method
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int menuChoice = 1;
System.out.print("Hello and Wlecome to Blue Jay Java Sort");
while (menuChoice != 3) {
System.out.print("\rEnter Menu Choice\n");
System.out.print("**********************");
System.out.print("\r(1) => Enter Blue Jay Data \n");
System.out.print("(2) => Display Possible Draft Choices \n");
System.out.print("(3) => Exit \r");
//try-catch statement for each case scenario
try {
menuChoice = Integer.parseInt(br.readLine());
} catch (IOException ie) {
ie.printStackTrace();
}
switch(menuChoice) {
case 1:
inputInfo();
break;
case 2:
inputSort();
break;
case 3:
return;
}
}
}
public static void inputInfo() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Scanner p = new Scanner(System.in);
//loop to request to fill array
for (x = 0; x < 3; x++) {
//Ask for player name
System.out.print("\rEnter player full name: ");
//Read input and store name in an Array
name[x] = in.readLine();
//Ask for player age
System.out.print("Enter age of player: ");
//Read input and store age in an Array
age[x] = p.nextInt();
//Ask for position of player
System.out.print("Enter player position: ");
//Read input and store position in an Array
position[x] = in.readLine();
//Ask for batting average of player
System.out.print("Enter batting average of player: ");
//Read input and store batting average in an Array
average[x] = p.nextDouble();
}
}
public static void inputSort() {
int smallest, temp;
//Selection Sort
for (x = 0; x < 3 - 1; ++x) {
smallest = x;
for(i = x + 1; i < 3; ++i) {
if (age[i] < age[smallest]) {
smallest = i;
}
}
temp = age [x];
age [x] = age [smallest];
age [smallest] = temp;
}
System.out.println(" Name " + " -----" + " Age " + "-----" + " Position " + "-----" + "Batting Average ");
for (x = 0 ; x < 3; x++) {
if (age[x] <= 25 && average[x] >= .280) {
System.out.println( name[x] + " ----- " + age[x] + " ----- " + position[x] + " ----- " + average[x]);
}
}
//Close Main()
}
}

Related

How to insert existing arrays inside a 3D array

I would like to create a 3d array with the already existing arrays(Score, CourseRating, and SlopeRating). I would like to do so, so that I can match the Scores with their Ratings. If it is not possible, I was thinking I could maybe find the index of the score, and match it with the Course and Slope rating so that I can calculate the Handicap Index.
import java.util.Arrays;
import java.util.Scanner;
public class RoughDraft {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int count;
int[] Scores;
double[] SlopeRating;
double[] CourseRating;
System.out.print("\nHow many scores would you like to enter?: ");
count = scnr.nextInt();
// ------ adds Scores, Course Rating and Slope Rating to Arrays ------ //
Scores = new int[count];
CourseRating = new double[count];
SlopeRating = new double[count];
if(count >= 5 && count <= 20) {
for(int i = 0; i < count; i++) {
System.out.printf("\nEnter Score #%d: ", i + 1);
if(scnr.hasNextInt()) {
Scores[i] = scnr.nextInt();
}
System.out.printf("Enter Course Rating #%d: ", i + 1);
if(scnr.hasNextDouble()) {
CourseRating[i] = scnr.nextDouble();
}
System.out.printf("Enter Slope Rating #%d: ", i + 1);
if(scnr.hasNextDouble()) {
SlopeRating[i] = scnr.nextDouble();
}
}
}
else {
System.out.print("Enter a minimum of 5 scores and a maximum of 20 scores.");
main(args);
}
System.out.print("\nScores: " + Arrays.toString(Scores));
System.out.print("\nCourse Ratings: " + Arrays.toString(CourseRating));
System.out.print("\nSlope Rating: " + Arrays.toString(SlopeRating));
}
}

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;
}

How to loop a prompt for a user to re-enter a number if they input a number outside of the parameters

I'm trying to set up a program where the user(student) inputs how many courses they have left to graduate and and how many classes the intend to take per terms and the program will form this data into an array and print out how many terms they have left. The user is not allowed to take more than 5 courses per term so I want to prompt the user that the number they input is incorrect while also looping that input for that specific student without have to close the console and re-run the program. I've tried placing a while(true){} loop there in order to loop it but i can't seem to get the loop i desire.
I've tried placing the while(true){} loop in multiple spots of the code and can't get the desired result.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] students = new int[10][2];
for (int i = 0; i < students.length; i++) {
System.out.println("Enter classes remaining and taking each term for student " + (i + 1) + ": ");
for (int j = 0; j < students[i].length; j++) {
students[i][j] = input.nextInt();
if (students[i][1] > 5)
System.out.println("The number of classes per term for student " + (i + 1) + " is invalid.");
}
}
System.out.println();
for (int i = 0; i < students.length; i++) {
System.out.println("Student " + (i + 1) + " has " + (int) Math.round(students[i][0] / students[i][1]) + " terms left to graduate.");
}
}
I expect the output for the first input to print","The number of class per term for student n is invalid." and repeat the prompt to enter the numbers for that same student n without proceeding to the next student input.
Here is the updated one based on your new comments. You should be good from here, make changes whatever you need.
public class StudentInfo
{
public static int totalStudents = 6;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[][] Students = new int[totalStudents][3];
// Student[i][0] will hold the Remaining classes.
// Student[i][1] will hold the Classes per semester and
// Student[i][2] will hold the number of total Semesters to complete all courses.
for (int i = 0; i < totalStudents; i++)
{
System.out.print("\n\nEnter the information for " + (i + 1) + "-th student.");
System.out.print("\n\nEnter the total number of remaining courses: ");
Students[i][0] = input.nextInt();
System.out.print("\nEnter the total number of courses per semester: ");
Students[i][1] = input.nextInt();
while (Students[i][1] > 5)
{
System.out.println("\nStudents are not allowed to take more than 5 classes per semester.");
System.out.print("Enter the total number of courses per semester: ");
Students[i][1] = input.nextInt();
}
int ts = Students[i][0] / Students[i][1];
if (Students[i][0] % Students[i][1] != 0)
ts++;
Students[i][2] = ts;
System.out.println("\nThis student needs a total of " + ts + " semesters to finish all courses.");
}
input.close();
}
}
public static void main(String[] args) {
//scanner library
Scanner input = new Scanner (System.in);
//Initialize array
int[][] students = new int [10][2];
//iterate scanner and condition loop
for(int i=0; i<students.length; i++){
System.out.print("Enter classes remaining and taking each term for student "+ (i+1) +": ");
for (int j=0; j<students[i].length;j++){
students[i][j]= input.nextInt();
}
while(students [i][1] > 5) {
System.out.println("The number of classes per term for student " + (i+1) + " is invalid.");
i--;
break;
}
}
System.out.println();
//Print out results compiled from array
for(int i =0; i<students.length; i++) {
System.out.println("Student "+(i+1)+" has "+ (int) Math.ceil((double)students[i][0]/students[i][1]) + " terms left to graduate.");
}
}

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");
}

Input String and int in the same line

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]);

Categories

Resources