User inputted array is entirely the last input - java

When I execute this program, the canidateArray only stores the last user input as every variable in the array.
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class ArrayElection {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of candidates: ");
int loops = input.nextInt();
int loops2 = loops;
Canidate[] canidateArray = new Canidate[loops];
String canidatename;
int canidatevotes = 0;
int outputno = 1;
while (loops > 0){
System.out.println("Enter " + outputno +". name:");
canidatename = input.next();
System.out.println("Enter votes:");
canidatevotes = input.nextInt();
new Canidate(canidatename, canidatevotes);
loops = loops - 1;
outputno = outputno + 1;
}
if (canidateArray[0].getVotes() == canidateArray[1].getVotes()) {
System.out.println("The election is a tie between the following candidates: ");
System.out.println(canidateArray[0].getName() + " (" + canidateArray[0].getVotes() + " votes)");
System.out.println(canidateArray[1].getName() + " (" + canidateArray[1].getVotes() + " votes)");
System.out.println(canidateArray[2].getName() + " (" + canidateArray[2].getVotes() + " votes)");
}
else {
System.out.println("The winner is " + canidateArray[0].getName() + " with " + canidateArray[0].getVotes() + " votes!");
}
}
public static class Canidate {
private static String name;
private static int votes;
public Canidate(String name, int votes) {
this.name = name;
this.votes = votes;
}
public static String getName() {
return name;
}
public static int getVotes() {
return votes;
}
}
}

You don't store anything in the array. Fix :
while (loops > 0){
System.out.println("Enter " + outputno +". name:");
canidatename = input.next();
System.out.println("Enter votes:");
canidatevotes = input.nextInt();
loops = loops - 1;
canidateArray[outputno-1] = new Canidate(canidatename, canidatevotes);
outputno = outputno + 1;
}
But you'll have to fix your last part of code. You test canidateArray[0] vs canidateArray[1] while you can have
1 candidate, then it will trigger an IndexOutOfBoundsException
or more than 2 candidates

Related

Choosing random Index from Array of Objects - Java

I am trying to code a text based Adventure Game, but the random enemy selection does not work. Always the "Assassin" gets chosen, but I can't figure out why.
package defaultdfs;
import java.util.Random;
import java.util.Scanner;
public class main {
// System Objects
static Scanner in = new Scanner(System.in);
static Random rand = new Random();
//OBJ
static Entity s = new Entity("Skeleton", 200, 5, 2, 200);
static Entity z = new Entity("Zombie", 150, 2, 1, 150);
static Entity w = new Entity("Warrior", 175, 3, 1, 175);
static Entity a = new Entity("Assasin", 75, 1, 1, 75);
// Game Variables
static Entity[] enemies = {w, z, s, a};
static int maxEnemyHealth = 75;
static int enemyAttackDam = 25;
// Player Variables
static int health = 100;
static int attackDamage = 50;
static int numHealthPot = 3;
static int healthPotHealAmount = 30;
static int healthPotDropChance = 50;
static int ShieldDropChance = 0;
static int enemyCounter = 0;
static int defense = 0;
static int enemyHealth = 0;
static int damageDealt = 0;
static int damageTaken = 0;
//Items
static boolean sword = false;
static int swordDropChance = 0;
static boolean running = true;
static Entity enemy;
public static void main(String[] args) {
welcome();
GAME: while (running) {
System.out.println("-------------------------------------------------");
int ra = rand.nextInt(enemies.length); //RANDOM ENEMY SELECTION in two steps
enemy = enemies[ra];
// enemy = enemies[rand.nextInt(enemies.length)]; //in one step
System.out.println(ra);
System.out.println("\t# " + enemy.name + " appeared! #\n");
while (enemy.enemyHealth > 0) {
monitoring(enemy, Entity.enemyHealth);
String input = in.nextLine();
if (input.equals("1")) {
damageDealt = rand.nextInt(attackDamage);
damageTaken = rand.nextInt(enemyAttackDam);
enemy.enemyHealth -= damageDealt;
health -= damageTaken;
// Iteminfluence
health += defense;
System.out.println("\t> You strike the " + enemy.name + " for " + damageDealt + " damage.");
System.out.println("\t> You recive " + damageTaken + " in retaliation!");
if (health < 1) {
dead();
break;
}
} else if (input.equals("2")) {
healingProcess(enemy);
}
else if (input.equals("3")) {
runOption(enemy);
continue GAME;
}
else {
System.out.println("\tInvalid command!");
}
}
if (health < 1) {
System.out.println("You limp out of the dungeon, weak from battle!");
break;
}
defmsg(enemy);
enemyC();
healpot(enemy);
defense(enemy);
sword(enemy);
options();
String input = in.nextLine();
while (!input.equals("1") && !input.equals("2")) {
System.out.println("Invalid command!");
input = in.nextLine();
}
if (input.equals(input.equals("1"))) {
System.out.println("You continue on ypur adventure!");
}
else if (input.equals("2")) {
System.out.println("You exit the dungeon, successful from your adventure!");
break;
}
}
thx();
}
private static void sword(Entity enemy) {
if (rand.nextInt(100) < swordDropChance) {
attackDamage += 5;
System.out.println(" # The " + enemy.name + " dropped a piece of armor! # ");
System.out.println(" # You attack now with +5! # ");
}
}
private static void defmsg(Entity enemy) {
System.out.println("-------------------------------------------------");
System.out.println(" # " + enemy.name + " was defeated! # ");
System.out.println(" # You have " + health + "HP left. # ");
enemy.enemyHealth = enemy.inHealth;
}
private static void options() {
System.out.println("-------------------------------------------------");
System.out.println("What would you like to do now? ");
System.out.println("1. Continue fighting");
System.out.println("2. Exit dungeon");
}
private static void thx() {
System.out.println("#######################");
System.out.println("# THANKS FOR PLAYING! #");
System.out.println("#######################");
}
private static void welcome() {
System.out.println("Welcome to the Dungeon!");
}
private static void attack(int enemyHealth, int damageDealt, int damageTaken) {
enemy.enemyHealth -= damageDealt;
health -= damageTaken;
// Iteminfluence
health += defense;
}
private static void dead() {
System.out.println("\t> You have taken too much damage, you are too weak to go on!");
}
private static void monitoring(Entity enemy, int enemyHealth) {
System.out.println("\tYour HP: " + health);
System.out.println("\t" + enemy.name + "'s HP: " + enemy.enemyHealth);
System.out.println("\n\tWhat would you like to do?");
System.out.println("\t1. Attack");
System.out.println("\t2. Drink health potion");
System.out.println("\t3. Run!");
}
private static void runOption(Entity enemy) {
System.out.println("\tYou run away from the " + enemy.name + "!");
}
private static void healingProcess(Entity enemy) {
if (numHealthPot > 0) {
int prevHealth = health;
health += healthPotHealAmount;
if (health == 100) {
System.out.println("You can not heal yourself!");
} else if (health > 100) {
health = 100;
numHealthPot--;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotHealAmount + " . "
+ "\n\t> You now have " + health + " HP." + "\n\t> You have " + numHealthPot
+ " health potions left.\n");
} else {
numHealthPot--;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotHealAmount + " . "
+ "\n\t> You now have " + health + " HP." + "\n\t> You have " + numHealthPot
+ " health potions left.\n");
}
}
else {
System.out.println("\t> You have no health potions left! Defeat enemies for a chance to get one!");
}
}
private static void enemyC() {
enemyCounter++;
if (enemyCounter == 1) {
System.out.println(" # You killed one enemy! # ");
} else {
System.out.println(" # You killed " + enemyCounter + " enemies! # ");
}
}
private static void healpot(Entity enemy) {
if (rand.nextInt(100) < healthPotDropChance) {
numHealthPot++;
System.out.println(" # The " + enemy.name + " dropped a health potion! # ");
System.out.println(" # You now have " + numHealthPot + " heaalth potion(s). # ");
}
}
public static void defense(Entity enemy) {
if (rand.nextInt(100) < ShieldDropChance) {
defense += 5;
System.out.println(" # The " + enemy.name + " dropped a piece of armor! # ");
System.out.println(" # You now have " + defense + " defensepoints! # ");
}
}
}
I Tried to split the part up and print out the number it choose. And the random selection works but its always the same enemy which gets chosen.
public class Entity {
static String name;
static int enemyHealth = 100;
static int ShieldDropChance = 0;
static int swordDropChance = 0;
static int inHealth = 0;
public static int getSwordDropChance() {
return swordDropChance;
}
public static void setSwordDropChance(int swordDropChance) {
Entity.swordDropChance = swordDropChance;
}
public static int getShieldDropChance() {
return ShieldDropChance;
}
public static void setShieldDropChance(int shieldDropChance) {
ShieldDropChance = shieldDropChance;
}
public static String getName() {
return name;
}
public static void setName(String name) {
Entity.name = name;
}
public static int getEnemyHealth() {
return enemyHealth;
}
public static void setEnemyHealth(int enemyHealth) {
Entity.enemyHealth = enemyHealth;
}
public Entity (String name, int enemyHealth, int ShieldDropChance, int swordDropChance, int inHealth) {
this.name = name;
this.enemyHealth = enemyHealth;
this.ShieldDropChance = ShieldDropChance;
this.swordDropChance = swordDropChance;
this.inHealth = inHealth;
}
}
What Anon said. Change your entity class to this, and you shouldn't even need to touch the rest of your code.
Remember that static means it's one value associated with the class itself and not any particular instance. But for some reason, Java lets you reference static values via an instance (like you did), which does nothing except trick you into thinking it's not static. I really don't know why that's a thing.
public class Entity {
String name;
int enemyHealth = 100;
int shieldDropChance = 0;
int swordDropChance = 0;
int inHealth = 0;
public int getSwordDropChance() {
return swordDropChance;
}
public void setSwordDropChance(int swordDropChance) {
this.swordDropChance = swordDropChance;
}
public int getShieldDropChance() {
return shieldDropChance;
}
public void setShieldDropChance(int shieldDropChance) {
this.shieldDropChance = shieldDropChance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEnemyHealth() {
return enemyHealth;
}
public void setEnemyHealth(int enemyHealth) {
this.enemyHealth = enemyHealth;
}
public Entity (String name, int enemyHealth, int ShieldDropChance, int swordDropChance, int inHealth) {
this.name = name;
this.enemyHealth = enemyHealth;
this.ShieldDropChance = ShieldDropChance;
this.swordDropChance = swordDropChance;
this.inHealth = inHealth;
}
}

An ArrayList that should have objects from a created class but print as null

My first class that creates the ArrayList and populates it with the Skill objects
import java.util.ArrayList;
public class Skill {
String skillName;
int skillValue;
public static ArrayList<Skill> skillList = new ArrayList<Skill>();
public Skill(String newSkillName, int newSkillValue){
setSkillName(newSkillName);
setSkillValue(newSkillValue);
}
public static void initializeSkillList(){
//Creating the Skill obj's
Skill str = new Skill("Str", 1);
Skill dex = new Skill("Dex", 1);
Skill intl = new Skill("Int", 1);
Skill con = new Skill("Con", 3);
//Adding them to the Skill ArrayList
skillList.add(str);
skillList.add(dex);
skillList.add(intl);
skillList.add(con);
//Debug statement to check if the values are correct
System.out.println(skillList.get(1).skillValue);
}
}
I am attempting to access the objects skillValue and skillName from the ArrayList in my Main.java class. I have setters and getters.
This is the Main class
import java.util.Scanner;
public class Main {
static Character playerCharacter;
static boolean charCreationComplete = false;
static boolean endGame = false;
static Scanner scnr = new Scanner(System.in);
public static void main(String[] args){
System.out.println("\n\nWelcome to Garterra!\n\n");
Archetype.initializeArchetypeList();
Skill.initializeSkillList();
if (!charCreationComplete){
charCreation(scnr);
charCreationComplete = true;
}
charCreation(scnr); then accesses the skillList through getters and setters
charCreation() Method:
private static void charCreation(Scanner scnr){
System.out.println("\nEnter player name:\n\n");
String newName = scnr.nextLine();
System.out.println("You Entered " + newName + " for your name!\n");
System.out.println("Next, Choose your Archetype: 0 = Ranger\n");
int archetypeIndex = scnr.nextInt();
Character.currArchetype = Archetype.archetypeList.get(archetypeIndex);
Character.archetypeName = Archetype.archetypeList.get(archetypeIndex).getArchetypeName();
System.out.println("You have chosen " + Character.archetypeName + ".\nThis gives you " + Character.currArchetype.totalSpendableSkillPoints + " total spendable skill points!\n");
System.out.println("Now, spend those skill points.\n");
if (Character.currArchetype.getArchetypeName().contains("Ranger")){
Ranger.dexModifierCalc(1);
Ranger.conModifierCalc(1);
}
while (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Strength?\nThis impacts your melee weapon damage and carry weight.\n");
int strAddPoints = scnr.nextInt();
Skill.skillList.get(0).setSkillValue(Skill.skillList.get(0).getSkillValue() + strAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - strAddPoints);
strAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(0).getSkillValue() + "\n");
if (Character.currArchetype.totalSpendableSkillPoints == 0){
break;
}
if (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Dexterity?\nThis impacts your ranged weapon damage.\n");
int dexAddPoints = scnr.nextInt();
Skill.skillList.get(1).setSkillValue(Skill.skillList.get(1).getSkillValue() + dexAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - dexAddPoints);
dexAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(1).getSkillValue() + "\n");
}
if (Character.currArchetype.totalSpendableSkillPoints == 0){
break;
}
if (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Intelligence?\nThis impacts your magic damage.\n");
int intAddPoints = scnr.nextInt();
Skill.skillList.get(2).setSkillValue(Skill.skillList.get(2).getSkillValue() + intAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - intAddPoints);
intAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(2).getSkillValue() + "\n");
}
if (Character.currArchetype.totalSpendableSkillPoints == 0){
break;
}
if (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Strength?\nThis impacts your melee weapon damage and carry weight.\n");
int conAddPoints = scnr.nextInt();
Skill.skillList.get(3).setSkillValue(Skill.skillList.get(3).getSkillValue() + conAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - conAddPoints);
conAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(3).getSkillValue() + "\n");
}
}
int newHealthPoints = Character.healthPointsCalc();
System.out.println("You have " + newHealthPoints + " health points!\n\n");
int newTotalCarryWeight = Character.carryWeightCalc(Character.currArchetype.getLevel());
System.out.println("Your total carry weight is " + newTotalCarryWeight + ".\n");
int newExperince = 0;
playerCharacter = new Character(newName, newHealthPoints, newExperince, 1, Archetype.archetypeList.get(archetypeIndex), newTotalCarryWeight);
}
If you create a getter for "skillList" then you can just say
Skill.getSkillList();
And then do whatever you want with this list.
To make your code a little better, change this
public static ArrayList<Skill> skillList = new ArrayList<>();
to this
public static List<Skill> skillList = new ArrayList<>();

Creating an array of objects but it doesn't find the symbols

I am creating an array of Players in a minigame in Java. There is a class called Players and one called Game.
In the Main we scan two names and send them to the Game
game.createPlayer(name1, name2);
and later on try to get some information back
playerArray[(game.getPlayerTurn() % 2)].getPlayerName();
The Player gets constructed in the Game as an array:
public class Game
{
private Player[] playerArray;
[...]
public void createPlayer(String name1, String name2)
{
Player[] playerArray = new Player[2];
playerArray[0] = new Player(name2);
playerArray[1] = new Player(name1);
}
with the Player as a standard class:
public class Player
{
private String playerName;
public Player( String playerName )
{
this.playerName = playerName;
}
public String getPlayerName()
{
return playerName;
}
}
This however returns multiple errors saying it cannot find the symbol wherever i try to find out the name of the player. Did I not properly instanciate them?
Additional code (as per request):
package oop.nimspiel;
import java.util.Scanner;
import java.util.Arrays;
public class Game
{
private int take;
private int turn;
private int playerTake;
private int playerTurn;
protected Player[] playerArray;
public Game(int turn, int playerTurn)
{
this.turn = turn;
this.playerTurn = playerTurn;
}
protected void setPlayerTake(int take)
{
this.playerTake = take;
}
public int getPlayerTake()
{
return playerTake;
}
public void incrementTurns()
{
turn = turn + 1;
playerTurn = playerTurn + 1;
}
public int getTurn()
{
return turn;
}
public int getPlayerTurn()
{
return playerTurn;
}
public void createPlayer(String name1, String name2)
{
this.playerArray = new Player[2];
playerArray[0] = new Player(name2);
playerArray[1] = new Player(name1);
}
public String getPlayer()
{
String playerName = playerArray[(getPlayerTurn() % 2)].getPlayerName();
return playerName;
}
public void checkTake(int take)
{
Scanner input = new Scanner(System.in);
this.take = take;
boolean rightInput = false;
do {
if (take < 1 || take > 3)
{
System.out.println("Your input was wrong, please use a number between 1 and 3.");
System.out.println("How many stones would you like to take?");
take = input.nextInt();
rightInput = false;
}
else if (stoneheap.getStones() < take) {
System.out.println("There are only " + stoneheap.getStones() + " stones left.");
System.out.println("Please take less.");
System.out.println("How many stones would you like to take?");
take = input.nextInt();
rightInput = false;
}
else
{
rightInput = true;
}
} while (rightInput == false);
}
}
and the Main:
package oop.nimspiel;
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
private int take;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String nextRound;
do
{
int maxPlayers = 2;
int startTurn = 1;
Game game = new Game ( startTurn, (1 + (int)(Math.random() * ((maxPlayers - 1) + 1)) ) );
int minStones = 20;
int maxStones = 30;
Stoneheap stoneheap = new Stoneheap((minStones + (int)(Math.random() * ((maxStones - minStones) + 1)) ) );
System.out.println("Rules: Two players take stones from a heap of 20 to 30 until there are no more left. The one to take the last stone loses. Each round you can only take between 1 - 3 stones. Have fun!"); // Rules
System.out.println("");
System.out.println("Hello Player 1, what is your name?");
String name1 = input.next();
System.out.println("");
System.out.println("Hello Player 2, what is your name?");
String name2 = input.next();
game.createPlayer(name1, name2);
System.out.println("");
System.out.println("Number of stones: " + stoneheap.getStones());
System.out.println("The first to draw is Player " + game.getPlayerTurn());
System.out.println("The game starts now!");
while (stoneheap.getStones() > 0)
{
if ((game.getPlayerTurn() % 2) > 0) // Turn Player 1
{
System.out.println("It is your turn " + playerArray[(game.getPlayerTurn() % 2)].getPlayerName() + ".");
System.out.println("How many stones would you like to take?");
int take = input.nextInt();
game.checkTake(take);
game.setPlayerTake(take);
stoneheap.currentStones();
System.out.println("There are " + stoneheap.getStones() + " stones left.");
}
else // Turn Player 2
{
System.out.println("It is your turn " + playerArray[(game.getPlayerTurn() % 2)].getPlayerName() + ".");
System.out.println("How many stones would you like to take?");
int take = input.nextInt();
game.checkTake(take);
game.setPlayerTake(take);
stoneheap.currentStones();
System.out.println("There are " + stoneheap.getStones() + " stones left.");
}
game.incrementTurns();
}
System.out.println("The game has ended and the winner is ...");
System.out.println(playerArray[(game.getPlayerTurn() % 2)].getPlayerName());
System.out.println("It took " + (game.getTurn() - 1) + " turns." );
System.out.println("");
System.out.println("Do you want to play another round? Y for yes, anything else for no");
String userInput = input.next();
nextRound = userInput.toUpperCase();
} while (nextRound.equals("Y"));
}
}
In your createPlayer method, you should access playerArray by this keyword (this.playerArray = new Player[2]).
Currently you are creating an array on the fly, and the class variable is untouched, that's why you are getting an exception.
public class Game
{
private Player[] playerArray;
[...]
public void createPlayer(String name1, String name2)
{
this.playerArray = new Player[2];
playerArray[0] = new Player(name2);
playerArray[1] = new Player(name1);
}

Why does my code throw a NoSuchElementException?

The Java program for my school work gives me an error:
Welcome to Surinam Airlines - We may get you there!
We have 6 seats available for flight JAVA123.
How many seats do you want to book? 3
Enter passenger #1's name: Taylor Swift
Enter passenger #1's food option
(V = vegetarian, N = no preference, H = Halal): V
Enter passenger #1's class (1 = first, 2 = business, 3 = economy): 1
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown source)
at Passenger.enterPassenger(Passenger.java:64)
at RunAirLine.main(RunAirLine.java:23)
It seems to have something to do with the object not being instantiated though I can't quite figure out why. Does anyone know what's wrong?
import java.util.*;
public class RunAirLine {
private static Passenger seatArray[][] = new Passenger[2][3]; // declares new
// array of
// Passengers
static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to Surinam Airlines – We may get you there!");
System.out.println();
int seats = 6; // available seats
while (seats > 0) {
System.out.println("We have " + seats
+ " seats available for flight JAVA123.");
System.out.println();
System.out.print("How many seats do you want to book? ");
int n = kb.nextInt();
System.out.println();
for (int i = 0; i < n; i++) {
int x = emptySeat()[0];
int y = emptySeat()[1];
// retrieves info from emptySeat() function
seatArray[x][y] = new Passenger();
seatArray[x][y].enterPassenger(7 - seats); // gives the method the nth
// passenger number
seats--; // takes away 1 from the available seats
}
System.out.println();
}
System.out.println("No seats available.");
System.out.println();
System.out.println("Flight manifest:");
System.out.println();
for (int y = 0; y < 3; y++) { // prints out the list of flyers
for (int x = 0; x < 2; x++) {
System.out.println(seatArray[x][y].getSeat() + " "
+ seatArray[x][y].printPassengerCode());
}
}
kb.close();
}
public static int[] emptySeat() {
for (int y = 0; y < 3; y++) {// finds the next empty seat
for (int x = 0; x < 2; x++) {
if (seatArray[x][y] == null || seatArray[x][y].getSeat().equals("")) {
// if the spot hasn't been declared yet or is empty
return new int[] { x, y };
}
}
}
return null; // if none found then return null
}
}
Passenger.java
import java.util.*;
public class Passenger {
private String name;
private String seat;
private char foodOption;
private int seatClass;
// reduces some redundancy
private String classStr;
private String prefStr;
public Passenger() { // constructors
name = "";
seat = "";
foodOption = ' ';
seatClass = -1;
}
public Passenger(String n, String s, char f, int sc) { // assigns values
// according to input
name = n;
seat = s;
foodOption = f;
seatClass = sc;
}
// get and set methods
public void setName(String n) {
name = n;
}
public void setSeat(String s) {
seat = s;
}
public void setFoodOption(char f) {
foodOption = f;
}
public void setSeatClass(int sc) {
seatClass = sc;
}
public String getName() {
return name;
}
public String getSeat() {
return seat;
}
public char getFoodOption() {
return foodOption;
}
public int getSeatClass() {
return seatClass;
}
// end of get and set methods
public void enterPassenger(int i) {
Scanner kb = new Scanner(System.in);
// asks the important questions
System.out.print("Enter passenger #" + i + "’s name: ");
name = kb.nextLine();
System.out.println("Enter passenger #" + i + "’s food option ");
System.out.print("(V = vegetarian, N = no preference, H = Halal): ");
foodOption = kb.nextLine().toUpperCase().charAt(0);
System.out.print("Enter passenger #" + i
+ "’s class (1 = first, 2 = business, 3 = economy): ");
seatClass = kb.nextInt();
System.out.println();
char seatChar = 'A'; // calculates the seat number
if (i % 2 == 0)
seatChar = 'B';
seat = Integer.toString(i / 2 + i % 2) + seatChar;
classStr = "Economy Class"; // transfers the class choice int into string
switch (seatClass) {
case 1:
classStr = "First Class";
break;
case 2:
classStr = "Business Class";
break;
}
prefStr = "No preference"; // transfers the preference char into string
switch (foodOption) {
case 'V':
prefStr = "Vegetarian";
break;
case 'H':
prefStr = "Halal";
break;
}
System.out.println("Done – Seat " + seat + " booked");
System.out
.println("-------------------------------------------------------------------");
System.out.println(name + "(" + classStr + " - Seat " + seat + ") - "
+ prefStr);
System.out
.println("-------------------------------------------------------------------");
kb.close();
}
public void printTicketStub() {
char initial = name.split(" ")[0].toUpperCase().charAt(0); // splits name
// into first
// name and
// second name
System.out.println(initial + ". " + name.split(" ")[1] + "(" + classStr
+ " - Seat " + seat + ") - " + prefStr);
}
public String printPassengerCode() { // forms the code as required
return seatClass + name.toUpperCase().substring(name.length() - 4)
+ foodOption;
}
}
You have two problems:
You create a Scanner for System.in twice. You should only do this once. I have commented out the one you create in Passenger.java, and changed the reference to the one in RunAirLine.java:
public void enterPassenger(int i) {
// Scanner kb = new Scanner(System.in);
// asks the important questions
System.out.print("Enter passenger #" + i + "’s name: ");
name = RunAirLine.kb.nextLine();
System.out.println("Enter passenger #" + i + "’s food option ");
System.out.print("(V = vegetarian, N = no preference, H = Halal): ");
foodOption = RunAirLine.kb.nextLine().toUpperCase().charAt(0);
System.out.print("Enter passenger #" + i
+ "’s class (1 = first, 2 = business, 3 = economy): ");
seatClass = RunAirLine.kb.nextInt();
RunAirLine.kb.nextLine();
Every time you do nextInt(), it doesn't take the new line off the Scanner's reading, which messes stuff up. If you want nextInt() to be on it's own line, you should throw a dummy RunAirLine.kb.nextLine(); after the nextInt() call. This needs to be done twice, once in the code I've fixed above, and once in your RunAirLine.class:
System.out.print("How many seats do you want to book? ");
int n = kb.nextInt();
kb.nextLine();
System.out.println();
Further reading on Why you shouldn't have multiple Scanners. the tl;dr of is that closing System.in closes the stream forever.

I am trying to get the average of a certain student but it adds all the the values

I am trying to get the average of a certain student but it adds all the the values. this is the output program
CMPE 325 Student Record Holder System
--------------------------------
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
--------------------------------
Enter your choice: 1
How many Students you want to input?:
2
Student[1]Enter
Id Number: 1
First Name: Erwin
Middle Name: asdasdas
Last Name: sadasdas
Degree: asdasdas
Year Level: 1
Student[2]Enter
Id Number: 2
First Name: INK
Middle Name: asdasd
Last Name: asdas
Degree: sadas
Year Level: 3
CMPE 325 Student Record Holder System
--------------------------------
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
--------------------------------
Enter your choice: 3
Enter Id Number: 1
----------------Student Info--------------
Id Number: 1
Name:Erwin asdasdas sadasdas
Degree and Year: asdasdas-1
The number of Subjects:
3
Name of Course: Law
Enter Grade: 3
Name of Course: Laww2
Enter Grade: 1
Name of Course: Law4
Enter Grade: 2
Enter another subject and grade? [Y]or[N]n
CMPE 325 Student Record Holder System
--------------------------------
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
-------------------------------
Enter your choice: 3
Enter Id Number: 2
----------------Student Info--------------
Id Number: 2
Name:IDK asdasd asdas
Degree and Year: sadas-3
The number of Subjects:
2
Name of Course: psych
Enter Grade: 3
Name of Course: egg
Enter Grade: 2
Enter another subject and grade? [Y]or[N]n
CMPE 325 Student Record Holder System
--------------------------------
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
--------------------------------
Enter your choice: 4
ENTER ID NUMBER: 1
SUM: 11.0
AVERAGE: 2.2
this is my Tester
import java.util.ArrayList;
import java.util.Scanner;
public class RecHolder {
static ArrayList<Rec> record = new ArrayList<Rec>();
static ArrayList<Grade> records = new ArrayList<Grade>();
public RecHolder() {
menu();
}
#SuppressWarnings("resource")
public static void menu() {
Scanner in = new Scanner(System.in);
int choice;
System.out.println("CMPE 325 Student Record Holder System");
System.out.println("--------------------------------");
System.out.println("1.Add Student");
System.out.println("2.View Records");
System.out.println("3.Update Students");
System.out.println("4.Get Average");
System.out.println("5.Exit");
System.out.println();
System.out.println("--------------------------------");
System.out.print("Enter your choice: ");
choice = in.nextInt();
switch (choice)
{
case 1: record(); break;
case 2: display(); break;
case 3: update(); break;
case 4: average(); break;
case 5: break;
}
}
#SuppressWarnings("resource")
public static void record() {
Scanner in = new Scanner(System.in);
int total;
System.out.println("How many Students you want to input?: ");
total = in.nextInt();
Rec[] student = new Rec[total];
for (int index = 0; index < student.length; index++) {
student[index] = new Rec();
System.out.printf("Student[%d]", index + 1);
System.out.println("Enter");
in.nextLine();
System.out.print("Id Number: ");
student[index].setIdNumber(in.nextLine());
System.out.print("First Name: ");
student[index].setFirstName(in.nextLine());
System.out.print("Middle Name: ");
student[index].setMiddleName(in.nextLine());
System.out.print("Last Name: ");
student[index].setLastName(in.nextLine());
System.out.print("Degree: ");
student[index].setDegree(in.nextLine());
System.out.print("Year Level: ");
student[index].setYearLevel(in.nextInt());
record.add(student[index]);
}
menu();
}
#SuppressWarnings("resource")
public static void displayall() {
Scanner in = new Scanner(System.in);
if(record.size() == 0)
{
System.out.print("Invalid\n");
in.nextLine();
menu();
}
else
{
if(records.size() == 1){
System.out.print("-------------The Record for all Student-----------");
for (int i = 0; i < record.size(); i++) {
System.out.printf("\nStudent[%d]", i + 1);
System.out.print("\nId Number: " + record.get(i).getIdNumber());
System.out.print("\nName: "+ record.get(i).getFirstName() + " "+ record.get(i).getMiddleName() + " "+ record.get(i).getLastName());
System.out.print("\nDegree and Year: "+ record.get(i).getDegree() + "-"+ record.get(i).getYearLevel()+"\n\n");
}
in.nextLine();
display();
}
else{
System.out.print("--------------The Record for all Student------------");
for (int i = 0; i < record.size(); i++) {
System.out.printf("\nStudent[%d]", i + 1);
System.out
.print("\nId Number: " + record.get(i).getIdNumber());
System.out.print("\nName: "+ record.get(i).getFirstName() + " "+ record.get(i).getMiddleName() + " "+ record.get(i).getLastName());
System.out.print("\nDegree and Year: "+ record.get(i).getDegree() + "-"+ record.get(i).getYearLevel()+"\n\n");
}
// for(int loopforSubjct = 0 ; loopforSubjct < records.size(); loopforSubjct++ )
// {
// System.out.printf("\nSubject: "+ records.get(loopforSubjct).getSubject()+" Grade: "+ records.get(loopforSubjct).getGrade());
// }
in.nextLine();
}
}
display();
}
#SuppressWarnings("resource")
public static void specific() {
Scanner in = new Scanner(System.in);
if(record.size() == 0)
{
System.out.print("Enter Data 1st\n");
in.nextLine();
menu();
}
else{
String id = new String();
System.out.print("Enter Id Number: ");
id = in.nextLine();
if(records.size()==1){
for (int loopforSpcfc = 0; loopforSpcfc < record.size(); loopforSpcfc++) {
if (id.equals(record.get(loopforSpcfc).getIdNumber())) {
System.out.printf("\n ----------------Student Exists-------------- ");
System.out.print("\nId Number: "+ record.get(loopforSpcfc).getIdNumber());
System.out.print("\nName:"+ record.get(loopforSpcfc).getFirstName() + " "+ record.get(loopforSpcfc).getMiddleName() + " "+ record.get(loopforSpcfc).getLastName());
System.out.print("\nDegree and Year: "+ record.get(loopforSpcfc).getDegree() + "-"+ record.get(loopforSpcfc).getYearLevel() + "\n\n");in.nextLine();
}
else
{ in.nextLine();
System.out.print("Student Number Invalid!\n");
menu();
}
}
}
else{
for (int loopforSpcfc = 0; loopforSpcfc < record.size(); loopforSpcfc++) {
if (id.equals(record.get(loopforSpcfc).getIdNumber())) {
System.out.printf("\nStudent Exists");
System.out.print("\nId Number: "+ record.get(loopforSpcfc).getIdNumber());
System.out.print("\nName: "+ record.get(loopforSpcfc).getFirstName() + " "+ record.get(loopforSpcfc).getMiddleName() + " "+ record.get(loopforSpcfc).getLastName());
System.out.print("\nDegree and Year: "+ record.get(loopforSpcfc).getDegree() + "-"+ record.get(loopforSpcfc).getYearLevel() +"\n\n");
System.out.println();
}
}
for(int loopforSubjct = 0 ; loopforSubjct < records.size(); loopforSubjct++ )
{
System.out.printf("\nSubject: "+ records.get(loopforSubjct).getSubject()+" Grade: "+ records.get(loopforSubjct).getGrade());
}
in.nextLine();
}
}
display();
}
public static void update(){
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
if(record.size() == 0)
{
System.out.print("Enter Data 1st\n");
in.nextLine();
menu();
}
else{
String idnum = new String();
char answer;
in.nextLine();
System.out.print("Enter Id Number: ");
idnum = in.nextLine();
int total;
for (int loopforSpcfc = 0; loopforSpcfc < record.size(); loopforSpcfc++) {
if (idnum.equals(record.get(loopforSpcfc).getIdNumber())) {
System.out.printf("\n ----------------Student Info-------------- ");
System.out.print("\nId Number: "+ record.get(loopforSpcfc).getIdNumber());
System.out.print("\nName:"+ record.get(loopforSpcfc).getFirstName() + " "+ record.get(loopforSpcfc).getMiddleName() + " "+ record.get(loopforSpcfc).getLastName());
System.out.print("\nDegree and Year: "+ record.get(loopforSpcfc).getDegree() + "-"+ record.get(loopforSpcfc).getYearLevel() + "\n\n");in.nextLine();
}
}
for(int loop=0;loop<record.size();loop++){{
if(idnum.equals(record.get(loop).getIdNumber())){
System.out.println("The number of Sujects: ");
total = in.nextInt();
do{
Grade[] update = new Grade[total];
for(int indexupdater = 0;indexupdater<update.length;indexupdater++){
update[indexupdater] = new Grade();
in.nextLine();
System.out.print("Name of Course: ");
update[indexupdater].setSubject(in.nextLine());
System.out.print("Enter Grade: ");
update[indexupdater].setGrade(in.nextDouble());
records.add(update[indexupdater]);
}
System.out.print("Enter another subject and grade? [Y]or[N]");
String ans = in.next();
answer = ans.charAt(0);
}while(answer == 'y');
}
}
}
}
menu();
}
public static void average()
{
Scanner in = new Scanner(System.in);
if(record.size() == 0)
{
System.out.print("Enter Data 1st\n");
in.nextLine();
menu();
}
else{
double sum=0;
double average=0;
String ID = new String();
System.out.print("Enter An Valid Id Number: ");
for(int xx=0;xx<record.size();xx++){
if(ID.equals(record.get(xx).getIdNumber()))
{
for(int ind=0;ind<records.size();ind++)
{
sum += records.get(ind).getGrade();
}
average=sum/records.size();
System.out.println(average);
System.out.print("SUM: "+sum);
System.out.print("\nAVERAGE: "+average);
}
}
}
}
public static void display(){
Scanner input = new Scanner(System.in);
int choice;
System.out.println("--------------------------------");
System.out.println("1.View List");
System.out.println("2.View Specific Record");
System.out.println("3.Exit");
System.out.println();
System.out.println("--------------------------------");
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice) {
case 1:
displayall();
break;
case 2:
specific();
break;
case 3:
menu();
break;
}
}
public static void main(String[] args) {
new RecHolder();
}
}
This is for my Grades
public class Grade {
private String IDNumber;
private String subject;
private double grade;
private double average;
public Grade()
{
String IDNum;
String sub;
double grad;
double ave;
}
public Grade(String IDNum,String sub,double grad,double ave)
{
this.IDNumber=IDNum;
this.subject=sub;
this.grade=grad;
this.average=ave;
}
public void setSubject(String subject)
{
this.subject=subject;
}
public String getSubject()
{
return subject;
}
public void setGrade(double grade)
{
this.grade=grade;
}
public double getGrade()
{
return grade;
}
public String getIDNumber()
{
return IDNumber;
}
}
for the StudntRecord
public class Rec
{
private String IDNumber;
private String firstName;
private String middleName;
private String lastName;
private String degree;
private int yearLevel;
#Override
public String toString()
{
return ("ID Number: "+this.getIdNumber()+
"\nName: "+ this.getFirstName()+
" "+ this.getMiddleName()+
" "+ this.getLastName()+
"\nDegree and YearLevel: "+ this.getDegree() +
" - " + this.getYearLevel());
}
public Rec()
{
String IDNum;
String fName;
String mName;
String lName;
String deg;
int level;
}
public Rec(String IDNum, String fName, String mName, String lName, String deg,int level )
{
this.IDNumber=IDNum;
this.firstName=fName;
this.middleName=mName;
this.lastName=lName;
this.degree=deg;
this.yearLevel=level;
}
public void setIdNumber(String IDNumber)
{
this.IDNumber = IDNumber;
}
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
public void setMiddleName(String middleName)
{
this.middleName=middleName;
}
public void setLastName(String lastName)
{
this.lastName=lastName;
}
public void setDegree(String degree)
{
this.degree=degree;
}
public void setYearLevel(int yearLevel)
{
this.yearLevel=yearLevel;
}
public String getIdNumber()
{
return IDNumber;
}
public String getFirstName()
{
return firstName;
}
public String getMiddleName()
{
return middleName;
}
public String getLastName()
{
return lastName;
}
public String getDegree()
{
return degree;
}
public int getYearLevel()
{
return yearLevel;
}
}
Shouldn't you calculate the average AFTER everything is added into the sum?
You should calculate average outside the for loop.
for(int ind=0;ind<records.size();ind++)
{
sum += records.get(ind).getGrade();
}
average=sum/records.size();
System.out.println(average);
Average needs to be calculated after the entire for loop adds things up, Just as Prasad said before.
code is written based to complete ASSUMPTIONS since the original poster #user3145523 has not posted his complete source code when i am posting this
String ID = "fillit";
// fetch grade list
for(ArrayList gradeList2 : records.get(ID).grade)
{
double sum = 0.0;
double average = 0.0;
// cal values for all grades
for(int gradeValue : gradeList2)
{
sum = sum + gradeValue;
}
// cal average of sum
average = sum / gradeList2.count();
}
System.out.print("SUM: "+sum);
System.out.print("\nAVERAGE: "+average);
Assumptions
records is assumed to be a main ArrayList (the question is TAGGED arraylist)
the records is assumed to contain another ArrayList called grades (in the first post the user seems to have a dynamic way to allocate grade count and a simple array for grade seems unlikely )
assumed ArrayList grades is assumed to contain integer-int elements
major assumption average of grades of one student is computed . reason -> original poster said
i want that method to only calculate the a certain number.. Look the output above. it calculated all my input and get its average i need help with that
Asking user if this is fine in post (got no other option to contact)
is this fine ? ? ?
output pasted->
CMPE 325 Student Record Holder System
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
-------------------------------- Enter your choice: 1 How many Students you want to input?: 2 Student[1]Enter Id Number: 1 First
Name: a Middle Name: b Last Name: c Degree: 1 Year Level: 1
Student[2]Enter Id Number: 2 First Name: d Middle Name: e Last Name: f
Degree: 1 Year Level: 1 CMPE 325 Student Record Holder System
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
-------------------------------- Enter your choice: 3
Enter Id Number: 1
----------------Student Info-------------- Id Number: 1 Name:a b c
Degree and Year: 1-1
The number of Sujects: 2 Name of Course: aa Enter Grade: 2 Name of
Course: bb Enter Grade: 6 Enter another subject and grade? [Y]or[N]n
CMPE 325 Student Record Holder System
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
-------------------------------- Enter your choice: 3
Enter Id Number: 2
----------------Student Info-------------- Id Number: 2 Name:d e f
Degree and Year: 1-1
The number of Sujects: 2 Name of Course: cc Enter Grade: 5 Name of
Course: dd Enter Grade: 7 Enter another subject and grade? [Y]or[N]n
CMPE 325 Student Record Holder System
1.Add Student
2.View Records
3.Update Students
4.Get Average
5.Exit
-------------------------------- Enter your choice: 4 Enter An Valid Id Number: 1 SUM: 8.0 AVERAGE: 2.0
CODE -> includes originally posted codes too (adding on user... request)
import java.util.ArrayList;
import java.util.Scanner;
public class RecHolder {
static ArrayList<Rec> record = new ArrayList<Rec>();
static ArrayList<Grade> records = new ArrayList<Grade>();
public RecHolder() {
menu();
}
#SuppressWarnings("resource")
public static void menu() {
Scanner in = new Scanner(System.in);
int choice;
System.out.println("CMPE 325 Student Record Holder System");
System.out.println("--------------------------------");
System.out.println("1.Add Student");
System.out.println("2.View Records");
System.out.println("3.Update Students");
System.out.println("4.Get Average");
System.out.println("5.Exit");
System.out.println();
System.out.println("--------------------------------");
System.out.print("Enter your choice: ");
choice = in.nextInt();
switch (choice) {
case 1:
record();
break;
case 2:
display();
break;
case 3:
update();
break;
case 4:
average();
break;
case 5:
break;
}
}
public static void record() {
Scanner in = new Scanner(System.in);
int total;
System.out.println("How many Students you want to input?: ");
total = in.nextInt();
Rec[] student = new Rec[total];
for (int index = 0; index < student.length; index++) {
student[index] = new Rec();
System.out.printf("Student[%d]", index + 1);
System.out.println("Enter");
in.nextLine();
System.out.print("Id Number: ");
student[index].setIdNumber(in.nextLine());
System.out.print("First Name: ");
student[index].setFirstName(in.nextLine());
System.out.print("Middle Name: ");
student[index].setMiddleName(in.nextLine());
System.out.print("Last Name: ");
student[index].setLastName(in.nextLine());
System.out.print("Degree: ");
student[index].setDegree(in.nextLine());
System.out.print("Year Level: ");
student[index].setYearLevel(in.nextInt());
record.add(student[index]);
}
menu();
}
public static void displayall() {
Scanner in = new Scanner(System.in);
if (record.size() == 0) {
System.out.print("Invalid\n");
in.nextLine();
menu();
} else {
if (records.size() == 1) {
System.out
.print("-------------The Record for all Student-----------");
for (int i = 0; i < record.size(); i++) {
System.out.printf("\nStudent[%d]", i + 1);
System.out.print("\nId Number: "
+ record.get(i).getIdNumber());
System.out.print("\nName: " + record.get(i).getFirstName()
+ " " + record.get(i).getMiddleName() + " "
+ record.get(i).getLastName());
System.out.print("\nDegree and Year: "
+ record.get(i).getDegree() + "-"
+ record.get(i).getYearLevel() + "\n\n");
}
in.nextLine();
display();
}
else {
System.out
.print("--------------The Record for all Student------------");
for (int i = 0; i < record.size(); i++) {
System.out.printf("\nStudent[%d]", i + 1);
System.out.print("\nId Number: "
+ record.get(i).getIdNumber());
System.out.print("\nName: " + record.get(i).getFirstName()
+ " " + record.get(i).getMiddleName() + " "
+ record.get(i).getLastName());
System.out.print("\nDegree and Year: "
+ record.get(i).getDegree() + "-"
+ record.get(i).getYearLevel() + "\n\n");
}
// for(int loopforSubjct = 0 ; loopforSubjct < records.size();
// loopforSubjct++ )
// {
// System.out.printf("\nSubject: "+
// records.get(loopforSubjct).getSubject()+" Grade: "+
// records.get(loopforSubjct).getGrade());
// }
in.nextLine();
}
}
display();
}
public static void specific() {
Scanner in = new Scanner(System.in);
if (record.size() == 0) {
System.out.print("Enter Data 1st\n");
in.nextLine();
menu();
} else {
String id = new String();
System.out.print("Enter Id Number: ");
id = in.nextLine();
if (records.size() == 1) {
for (int loopforSpcfc = 0; loopforSpcfc < record.size(); loopforSpcfc++) {
if (id.equals(record.get(loopforSpcfc).getIdNumber())) {
System.out
.printf("\n ----------------Student Exists-------------- ");
System.out.print("\nId Number: "
+ record.get(loopforSpcfc).getIdNumber());
System.out.print("\nName:"
+ record.get(loopforSpcfc).getFirstName() + " "
+ record.get(loopforSpcfc).getMiddleName()
+ " " + record.get(loopforSpcfc).getLastName());
System.out.print("\nDegree and Year: "
+ record.get(loopforSpcfc).getDegree() + "-"
+ record.get(loopforSpcfc).getYearLevel()
+ "\n\n");
in.nextLine();
} else {
in.nextLine();
System.out.print("Student Number Invalid!\n");
menu();
}
}
}
else {
for (int loopforSpcfc = 0; loopforSpcfc < record.size(); loopforSpcfc++) {
if (id.equals(record.get(loopforSpcfc).getIdNumber())) {
System.out.printf("\nStudent Exists");
System.out.print("\nId Number: "
+ record.get(loopforSpcfc).getIdNumber());
System.out.print("\nName: "
+ record.get(loopforSpcfc).getFirstName() + " "
+ record.get(loopforSpcfc).getMiddleName()
+ " " + record.get(loopforSpcfc).getLastName());
System.out.print("\nDegree and Year: "
+ record.get(loopforSpcfc).getDegree() + "-"
+ record.get(loopforSpcfc).getYearLevel()
+ "\n\n");
System.out.println();
}
}
for (int loopforSubjct = 0; loopforSubjct < records.size(); loopforSubjct++) {
System.out.printf("\nSubject: "
+ records.get(loopforSubjct).getSubject()
+ " Grade: "
+ records.get(loopforSubjct).getGrade());
}
in.nextLine();
}
}
display();
}
public static void update() {
Scanner in = new Scanner(System.in);
if (record.size() == 0) {
System.out.print("Enter Data 1st\n");
in.nextLine();
menu();
} else {
String idnum = new String();
char answer;
in.nextLine();
System.out.print("Enter Id Number: ");
idnum = in.nextLine();
int total;
for (int loopforSpcfc = 0; loopforSpcfc < record.size(); loopforSpcfc++) {
if (idnum.equals(record.get(loopforSpcfc).getIdNumber())) {
System.out
.printf("\n ----------------Student Info-------------- ");
System.out.print("\nId Number: "
+ record.get(loopforSpcfc).getIdNumber());
System.out.print("\nName:"
+ record.get(loopforSpcfc).getFirstName() + " "
+ record.get(loopforSpcfc).getMiddleName() + " "
+ record.get(loopforSpcfc).getLastName());
System.out.print("\nDegree and Year: "
+ record.get(loopforSpcfc).getDegree() + "-"
+ record.get(loopforSpcfc).getYearLevel() + "\n\n");
in.nextLine();
}
}
for (int loop = 0; loop < record.size(); loop++) {
{
if (idnum.equals(record.get(loop).getIdNumber())) {
System.out.println("The number of Sujects: ");
total = in.nextInt();
do {
Grade[] update = new Grade[total];
for (int indexupdater = 0; indexupdater < update.length; indexupdater++) {
update[indexupdater] = new Grade();
// set ID... String
update[indexupdater].setIDNumber(idnum);
in.nextLine();
System.out.print("Name of Course: ");
update[indexupdater].setSubject(in.nextLine());
System.out.print("Enter Grade: ");
update[indexupdater].setGrade(in.nextDouble());
records.add(update[indexupdater]);
}
System.out
.print("Enter another subject and grade? [Y]or[N]");
String ans = in.next();
answer = ans.charAt(0);
} while (answer == 'y');
}
}
}
}
menu();
}
public static void average() {
Scanner in = new Scanner(System.in);
if (record.size() == 0) {
System.out.print("Enter Data 1st\n");
in.nextLine();
menu();
} else {
double sum = 0;
double average = 0;
String ID = new String();
System.out.print("Enter An Valid Id Number: ");
ID = in.nextLine();
for (Rec rec : record) {
if (rec.getIdNumber().equals(ID)) {
for (Grade grade : records) {
if (grade.getIDNumber().equals(ID)) {
// System.out.println(grade.getIDNumber());
sum = sum + grade.getGrade();
}
} // end loop-grade
average = sum / records.size();
} // end if
} // end loop-rec
System.out.print("SUM: " + sum);
System.out.print("\nAVERAGE: " + average);
}
}
public static void display() {
Scanner input = new Scanner(System.in);
int choice;
System.out.println("--------------------------------");
System.out.println("1.View List");
System.out.println("2.View Specific Record");
System.out.println("3.Exit");
System.out.println();
System.out.println("--------------------------------");
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice) {
case 1:
displayall();
break;
case 2:
specific();
break;
case 3:
menu();
break;
}
}
public static void main(String[] args) {
new RecHolder();
}
}
class Grade {
private String IDNumber;
private String subject;
private double grade;
private double average;
public Grade() {
String IDNum;
String sub;
double grad;
double ave;
}
public Grade(String IDNum, String sub, double grad, double ave) {
this.IDNumber = IDNum;
this.subject = sub;
this.grade = grad;
this.average = ave;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSubject() {
return subject;
}
public void setGrade(double grade) {
this.grade = grade;
}
public double getGrade() {
return grade;
}
public String getIDNumber() {
return IDNumber;
}
public void setIDNumber(String ID) {
this.IDNumber = ID;
}
}
public class Rec {
private String IDNumber;
private String firstName;
private String middleName;
private String lastName;
private String degree;
private int yearLevel;
#Override
public String toString() {
return ("ID Number: " + this.getIdNumber() + "\nName: "
+ this.getFirstName() + " " + this.getMiddleName() + " "
+ this.getLastName() + "\nDegree and YearLevel: "
+ this.getDegree() + " - " + this.getYearLevel());
}
public Rec() {
String IDNum;
String fName;
String mName;
String lName;
String deg;
int level;
}
public Rec(String IDNum, String fName, String mName, String lName,
String deg, int level) {
this.IDNumber = IDNum;
this.firstName = fName;
this.middleName = mName;
this.lastName = lName;
this.degree = deg;
this.yearLevel = level;
}
public void setIdNumber(String IDNumber) {
this.IDNumber = IDNumber;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setDegree(String degree) {
this.degree = degree;
}
public void setYearLevel(int yearLevel) {
this.yearLevel = yearLevel;
}
public String getIdNumber() {
return IDNumber;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public String getDegree() {
return degree;
}
public int getYearLevel() {
return yearLevel;
}
}
You need to post the whole code so that we can understand the structure. How is the 'records' maintained and all.
With the available code, what i understand is :
if(ID.equals(record.get(xx).getIdNumber()))
This will check the condition and enter the loop.
But once entered,
for(int ind=0;ind<records.size();ind++)
{
sum += records.get(ind).getGrade();
average=sum/records.size();
}
Here, id is not considered. All the grades are summed up and average is calculated.
Your code structure may not be having link between id and the corresponding records or you are not considering the grades for the id through proper logic.
The whole code structure is required to help you further.
Maybe you can try this:
ID = in.nextLine();
for (int ind = 0; ind < records.size(); ind++) {
if (ID.equals(record.get(ind).getIdNumber())) {
sum += records.get(ind).getGrade();
}
}
System.out.print("SUM: " + sum);
average = sum / records.size();
System.out.print("\nAVERAGE: " + average);

Categories