Compare scanner input to array - java

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

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

Arrays and Sorting

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()
}
}

How to use 2D arrays with other classes

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

Grade Calculation Program: Array Out of Bounds

I've been working on this program for 20+ hours and I feel like I'm really close to finishing, but I cannot seem to fix my array out of bounds exception. I'll provide my whole code here:
import java.util.Scanner;
import java.util.ArrayList;
public class GradeCalcArryas { /*
* Logan Wegner The purpose is to calculate
* entered grades
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in); // first scanner for inputs
Scanner s1 = new Scanner(System.in); // second scanner for string
boolean done = false; // so an if statement can be inputted for the code
// to break back to the menu
boolean quit = false;
int choice = 0;
final int MAX_STUDENTS = 200;
//Array created to store the information entered for exams
int[] examStats = new int[3];
//Array created to store the information entered for quizzes
int[] quizStats = new int[3];
//Array created to store the information entered for homework
int[] homeworkStats = new int[3];
//Array created to store the student name information entered
String[] studentNames = new String[MAX_STUDENTS];
System.out.println("Welcome to GradeBook!");
System.out.println("Please provide grade item details");
System.out.print("Exams (number, points, weight):");
examStats[0] = s.nextInt(); // inputs exam number
examStats[1] = s.nextInt(); // inputs exam points
examStats[2] = s.nextInt(); // inputs exam weight
System.out.print("Quizzes (number, points, weight):");
quizStats[0] = s.nextInt(); // inputs quiz number
quizStats[1] = s.nextInt(); // inputs quiz points
quizStats[2] = s.nextInt(); // inputs quiz weight
System.out.print("Homework (number, points, weight):");
homeworkStats[0] = s.nextInt(); // inputs homework number
homeworkStats[1] = s.nextInt(); // inputs homework points
homeworkStats[2] = s.nextInt(); // inputs homework weight
/*int numExams = examStats[0];
int numQuizzes = quizStats[0];
int numHW = homeworkStats[0];
int tableLength = numExams + numQuizzes + numHW + 1;*/
/*double[][] examScores = new double[MAX_STUDENTS][];
double[][] quizScores = new double[MAX_STUDENTS][];
double[][] hwScores = new double[MAX_STUDENTS][];*/
//arrays for the average exam, quiz, homework, gradeAverage, and gradeWeightedAverage score of each student
double[] examAverage = new double[MAX_STUDENTS];
double[] quizAverage = new double[MAX_STUDENTS];
double[] hwAverage = new double[MAX_STUDENTS];
double[] gradeAverage = new double[MAX_STUDENTS];
// counters
int numExams = 0;
int numQuizzes = 0;
int numHW = 0;
// declare Double[] exams using length numExams
double[] exams = new double[numExams];
// declare Double[] quizzes using length numQuizzes
double[] quizzes = new double[numQuizzes];
// declare Double[] HW using length numHW
double[] hw = new double[numHW];
//Calculating percentage to multiply exam, quiz, and homework averages
double examWeight = examStats[2]/100;
double quizWeight = quizStats[2]/100;
double hwWeight = homeworkStats[2]/100;
System.out.println("--------------------");
do {
System.out.println("What would you like to do?");
System.out.println(" 1 Add student data");
System.out.println(" 2 Display student grades & statistics");
System.out.println(" 3 Plot grade distribution");
System.out.println(" 4 Quit");
System.out.print("Your choice:");
choice = s.nextInt(); /*
* Choice will determine what the next course of
* action will be with the program
*/
if (choice == 1) { // ADD STUDENT DATA
System.out.println("Enter student data:");
for (int i = 0; i <= MAX_STUDENTS; i++) { // iterate through 200
// times
// (MAX_STUDENTS) or
// break
System.out.print("Data>");
String dataentry = s1.nextLine(); // read inputed data
if (dataentry.equals("done")) { // if user inputs "done",
// break
break;
}
// ArrayList that holds all information (Name, Exams,
// Quizzes, Homework)
ArrayList<String> allInfo = new ArrayList<String>();
// tokenize using ":" delimiter, splitting up the name
// (firstsplit[0]) from the rest of the information
String[] firstsplit = dataentry.split(":");
studentNames[i] = firstsplit[0];
// add name to ArrayList allinfo
allInfo.add(firstsplit[0] + "\t");
// tokenize using " " delimiter, splitting up each score
String[] secondsplit = firstsplit[1].split(" ");
for (int k = 0; k < secondsplit.length; k++) { // iterates
// through
// Array
// secondsplit
allInfo.add(secondsplit[k] + "\t"); // adds item at [k]
// to ArrayList
// allInfo
// if the first char in secondsplit[k] is "e" increment
// numExams
if (secondsplit[k].subSequence(0, 1).equals("e"))
numExams++;
// if the first char in secondsplit[k] is "q" increment
// numQuizzes
if (secondsplit[k].subSequence(0, 1).equals("q"))
numQuizzes++;
// if the first char in secondsplit[k] is "h" increment
// numHW
if (secondsplit[k].subSequence(0, 1).equals("h"))
numHW++;
}
// iterates through Array exams and adds values from allInfo
for (int k = 0; k < exams.length; k++) {
exams[k] = Double.parseDouble(allInfo.get(1 + k)
.substring(1));
}
// iterates through Array quizzes and adds values from
// allInfo
for (int k = 0; k < quizzes.length; k++) {
quizzes[k] = Double.parseDouble(allInfo.get(
1 + numExams + k).substring(1));
}
// iterates through Array hw and adds values from allInfo
for (int k = 0; k < hw.length; k++) {
hw[k] = Double.parseDouble(allInfo.get(
1 + numExams + numQuizzes + k).substring(1));
}
//Index counters for averages
int examIndex = 0;
int quizIndex = 0;
int hwIndex = 0;
int gradeAveragingIndex = 0;
//loop finding the gradeAverage
for(int index = 0; index < MAX_STUDENTS; index++){
examAverage[index] = ((exams[examIndex]) + (exams[examIndex+1]) + (exams[examIndex+2])) / (numExams);
quizAverage[index] = ((quizzes[quizIndex]) + (quizzes[quizIndex+1]) + (quizzes[quizIndex+2])) / (numQuizzes);
hwAverage[index] = ((hw[hwIndex]) + (hw[hwIndex+1]) + (hw[hwIndex+2])) / (numHW);
gradeAverage[index] = ((examAverage[gradeAveragingIndex] * examWeight) + (quizAverage[gradeAveragingIndex] * quizWeight) + (hwAverage[gradeAveragingIndex] * hwWeight) / numExams);
examIndex+=3;
quizIndex+=3;
hwIndex+=3;
gradeAveragingIndex++;
}
}
}
//This choice is to display student grades & statistics in a table
if (choice == 2) {
System.out.println("Display student grades & statistics");
//Formatting for the heading of my grade table
System.out.printf("%-10s","Name");
System.out.printf("%-5s","Exam");
System.out.printf("%-5s","Exam");
System.out.printf("%-5s","Exam");
System.out.printf("%-5s","Quiz");
System.out.printf("%-5s","Quiz");
System.out.printf("%-5s","Quiz");
System.out.printf("%-7s","HWork");
System.out.printf("%-7s","HWork");
System.out.printf("%-7s","HWork");
System.out.printf("%-5s","Grade\n");
//declaring index counters
int studentNameIndex = 0;
int examGradeIndex = 0;
int quizGradeIndex = 0;
int homeworkGradeIndex = 0;
int gradeAverageIndex = 0;
//for loop for the output of exams, quizzes, homework, and grade average
for(int index = 0; index < studentNames.length; index++) {
System.out.printf("%-10s",studentNames[studentNameIndex]);
System.out.printf("%-5.1f",exams[examGradeIndex]);
System.out.printf("%-5.1f",exams[examGradeIndex+1]);
System.out.printf("%-5.1f",exams[examGradeIndex+2]);
System.out.printf("%-5.1f",quizzes[quizGradeIndex]);
System.out.printf("%-5.1f",quizzes[quizGradeIndex+1]);
System.out.printf("%-5.1f",quizzes[quizGradeIndex+2]);
System.out.printf("%-7.1f",hw[homeworkGradeIndex]);
System.out.printf("%-7.1f",hw[homeworkGradeIndex+1]);
System.out.printf("%-7.1f",hw[homeworkGradeIndex+2]);
System.out.printf("%-5.1f",gradeAverage[gradeAverageIndex] + "\n");
studentNameIndex++;
examGradeIndex+=3;
quizGradeIndex+=3;
homeworkGradeIndex+=3;
gradeAverageIndex++;
}
}
if (choice == 3) {
}
if (choice == 4) {
quit = true;
System.out.println("Good bye!");
}
}while (quit == false);
}
}
My out of bounds exception occurs here:
//loop finding the gradeAverage
for(int index = 0; index < MAX_STUDENTS; index++){
examAverage[index] = ((exams[examIndex]) + (exams[examIndex+1]) + (exams[examIndex+2])) / (numExams);
quizAverage[index] = ((quizzes[quizIndex]) + (quizzes[quizIndex+1]) + (quizzes[quizIndex+2])) / (numQuizzes);
hwAverage[index] = ((hw[hwIndex]) + (hw[hwIndex+1]) + (hw[hwIndex+2])) / (numHW);
gradeAverage[index] = ((examAverage[gradeAveragingIndex] * examWeight) + (quizAverage[gradeAveragingIndex] * quizWeight) + (hwAverage[gradeAveragingIndex] * hwWeight) / numExams);
examIndex+=3;
quizIndex+=3;
hwIndex+=3;
gradeAveragingIndex++;
}
My exception is either ArrayOutofBounds: 0 or ArrayOutofBounds: 3. It has something to do with my exam, quiz, and hw arrays. I've moved them around in my program and changed my numExams, numQuizzes, and numHW values, but it still gives me some trouble. I'd love some insight. Thanks in advance guys.
For sure you have issue here:
int numExams = 0;
int numQuizzes = 0;
int numHW = 0;
// declare Double[] exams using length numExams
double[] exams = new double[numExams];
// declare Double[] quizzes using length numQuizzes
double[] quizzes = new double[numQuizzes];
// declare Double[] HW using length numHW
double[] hw = new double[numHW];
Your are declaring here arrays with size 0. If you have more issues - I was not checking.

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

Categories

Resources