How to print the array index of an object class? - java

I have a somewhat big code and I'm triying to print the slot number of an array from an object class that resulted to be the one with the highest weight.
On my main I have declared my array like this:
Car x[] = new car[2];
Now when triying to get which car has the highest weight I've made this validation inside a for loop
//.getweight obtains the weight of each car
if(x[i].getWeight() > max){
max = x[i].getWeight();
}
That code gives me the actual weight number of the heaviest car, but what I want to print is the actual car number. The comparing works but I can't find a way to just print the slot that corresponds to the heaviest car.
UPDATE with full code:
My object car:
public class Car
{
private String color;
private int weight;
private int state;
private int fuel;
private int Maxspeed ;
private int engine;
public Car(){
this.color = "White";
this.weight = 1000;
this.state = 0;
this.fuel =0;
this.Maxspeed = 0;
this.engine = 0;
}
public Car( String color, int weight,
int state, int fuel, int Maxspeed
){
this.color = color;
this.weight = weight;
this.state = state;
this.fuel = fuel;
this.Maxspeed = Maxspeed;
}
public String getColor(){
return this.color;
}
public int getweight(){
return this.weight;
}
public int getstate(){
return this.state;
}
public int getfuel(){
return this.fuel;
}
public int getMaxspeed(){
return this.Maxspeed;
}
public int getengine(){
return this.engine;
}
public void setColor( String color ){
this.color = color;
}
public void setweight( int weight ){
this.weight = weight;
}
public void setstate( int state ){
this.state = state;
}
public void setfuel( int fuel ){
this.fuel = fuel;
}
public void setMaxspeed( int Maxspeed ){
this.Maxspeed = Maxspeed;
}
public void setengine(int engine){
this.engine = engine;
}
public void showdata(){
System.out.println( "\nCar's color is: " + this.getColor() );
System.out.println( "Car's weight is: " + this.getweight() );
System.out.println( "State: " + this.getstate() );
System.out.println( "Fuel: " + this.getfuel());
System.out.println( "Max speed: " + this.getMaxspeed());
}
public void accelerate( int speed ){
if( this.getstate() == 0 ||
this.getstate() == 3 ||
this.getstate() == 4 ||
this.getMaxspeed() < speed )
{
System.out.println("\nCar cannot accelerate...");
}
else{
System.out.println("\nCar is accelerating...");
this.setfuel(this.getfuel()-2);
this.setstate(2);
if( this.getfuel() <= 0 ){
this.setstate(4);
}
}
}
public void crash(){
this.setstate(3);
System.out.println("\nCrash!!!");
}
public void stop(){
this.setstate(1);
System.out.println("\nCar has stopped.");
}
public void addfuel(int fuel){
if(this.getstate() == 0 || this.getstate() == 4){
this.setfuel(this.getfuel()+ fuel);
}
else{
System.out.println("You can't add fuel.");
}
}
public void repair(){
if(this.getstate() == 3){
this.setstate(1);
System.out.println("The car has been repaired");
}
else{
System.out.println("The car is not broken");
}
}
}
My Main:
import java.util.Scanner;
public class aaa{
public static void main (String args []){
Car x[] = new Car[2];
int keep=1;
int counter = 0;
int counter_stopped = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int maxIndex = 0;
int maxweight = 0;
int index_engine = 0;
int min_engine = 0;
Scanner input = new Scanner(System.in);
for(int i = 0; i < x.length; i++){
String color;
int weight;
int fuel;
int Maxspeed;
int engine;
x[i] = new Car();
System.out.print("\nEnter car color " + (i + 1) + ": ");
color = input.next();
System.out.print("Enter car weight " + (i + 1) + ": ");
weight = input.nextInt();
System.out.print("Enter car fuel " + (i + 1) + ": ");
fuel = input.nextInt();
System.out.print("Enter car max speed " + (i + 1) + ": ");
Maxspeed = input.nextInt();
System.out.print("Enter car engine weight " + (i + 1) + ": ");
engine = input.nextInt();
x[i].setColor(color);
x[i].setweight(weight);
x[i].getstate();
x[i].setfuel(fuel);
x[i].setMaxspeed(Maxspeed);
x[i].setengine(engine);
}
for(int i = 0; i < x.length; i++){
int state;
System.out.print("\nEnter car state " + (i + 1) + ": ");
state = input.nextInt();
x[i].setstate(state);
while(state > 4 || state < 0){
System.out.print("state not valid.\nTry again: ");
state = input.nextInt();
x[i].setstate(state);
}
do {
keep = menu();
switch( keep ){
case 1:
accelerate(x[i]);
break;
case 2:
stop(x[i]);
break;
case 3:
crash(x[i]);
break;
case 4:
addfuel(x[i]);
break;
case 5:
repair(x[i]);
break;
case 6:
x[i].showdata();
}
} while(keep != 7);
if(x[i].getstate() == 4 || x[i].getfuel() <= 0){
counter += 1;
}
if(x[i].getstate() == 1){
counter_stopped += 1;
}
int weight = x[i].getweight();
if(weight > max){
maxweight = weight;
maxIndex = i;
}
int weightengine = x[i].getengine();
if(weightengine < min){
min_engine = weightengine;
index_engine = i;
}
}
System.out.println("\nSUMMARY");
System.out.println("Amount of cars with no fuel: " + counter);
System.out.println("Amount of stopped cars: " + counter_stopped);
System.out.println("Heaviest car: " + maxIndex);
System.out.println("Car with the smallest engine: " + index_engine);
System.out.println("=============================================");
}
public static int menu(){
int option = 0;
Scanner s = new Scanner(System.in);
System.out.println("\n1. Accelerate Car ");
System.out.println("2. Stop Car ");
System.out.println("3. Crash Car ");
System.out.println("4. Add fuel ");
System.out.println("5. Repair ");
System.out.println("6. Show data ");
System.out.println("7. Exit ");
System.out.println("=============================================");
System.out.print("Choose an option : ");
option = s.nextInt();
System.out.println("=============================================");
return option;
}
public static void accelerate(Car myCar){
Scanner input = new Scanner(System.in);
int s;
System.out.print("Enter speed: ");
s = input.nextInt();
myCar.accelerate(s);
//myCar.showdata();
}
public static void stop(Car myCar){
myCar.stop();
}
public static void crash(Car myCar){
myCar.crash();
}
public static void addfuel(Car myCar){
int fuel;
Scanner input = new Scanner(System.in);
System.out.print("Amount to add: ");
fuel = input.nextInt();
myCar.addfuel(fuel);
}
public static void repair(Car myCar){
myCar.repair();
}
}
Now, when I compile and test which engine or car is smaller or heaviest I get the number 1 as result.

The array index would be i
The actual car would be x[i]

You need to hold on to a reference to the index to the heaviest car. In this example I am using maxIndex.
float maxWeight = 0;
int maxIndex = 0;
for (int i = 0; i < x.length; i++) {
float weight = x[i].getWeight();
if (weight > max) {
maxWeight = weight;
maxIndex = i;
}
}
System.out.println("Slot of heaviest car: " + maxIndex);

Related

Creating a method which specifically calculates the average of the users entered values

I am making a program which allows the user to look at student's grades, find the average, find the highest grade, the lowest etc. For one of the methods I have, it checks for the average of the values that the user entered. I tried to do this but to no avail. Here is the specific code:
public static void classAvg(int numOfKids) {
int average = 0;
for (int i = 0; i < numOfKids; i++) {
average += studentGrade[i];
}
average = (average/numOfKids) * 100;
System.out.println("The average of the class will be " + average + "%");
}
For some better context, here is the rest of the code:
import java.util.Scanner;
public class StudentGradeArray {
static Scanner input = new Scanner(System.in);
static String[] studentName;
static String letterGrade = " ";
static int[] studentGrade;
static int gradeMax = 0;
static int gradeMin = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("How many students are you entering into the database?");
int numOfKids = input.nextInt();
studentGrade = new int[numOfKids];
studentName = new String[numOfKids];
for (int i = 0; i < numOfKids; i++) {
System.out.println("Enter the student's name:");
studentName[i] = input.next();
System.out.println("Enter " + studentName[i] + "'s grade");
studentGrade[i] = input.nextInt();
}
do {
System.out.println("");
System.out.println("Enter a number for the following options:");
System.out.println("");
System.out.println("1. Student's letter grade");
System.out.println("2. Search for a student and their grade");
System.out.println("3. The class average");
System.out.println("4. The student with the highest grade");
System.out.println("5. The student with the lowest grade");
System.out.println("6. List of students that are failing");
System.out.println("7. Quit the program");
int options = input.nextInt();
switch(options) {
case 1:
letterGrade(options); break;
case 2:
searchStudent(); break;
case 3:
classAvg(options); break;
case 4:
markHighest(options); break;
case 5:
markLowest(options); break;
case 6:
markFailing(options); break;
case 7:
return;
default:
System.out.println("");
System.out.println("Please enter a valid option.");
System.out.println(""); break;
}
} while (!input.equals(7));
System.out.println("Program Terminated.");
}
public static void letterGrade(int numOfKids) {
System.out.println("Enter a grade: A, B, C, D, F");
letterGrade = input.next();
if (letterGrade.equalsIgnoreCase("a")) {
gradeMax = 100;
gradeMin = 80;
}
if (letterGrade.equalsIgnoreCase("b")) {
gradeMax = 79;
gradeMin = 70;
}
if (letterGrade.equalsIgnoreCase("c")) {
gradeMax = 69;
gradeMin = 60;
}
if (letterGrade.equalsIgnoreCase("d")) {
gradeMax = 59;
gradeMin = 50;
}
if (letterGrade.equalsIgnoreCase("f")) {
gradeMax = 49;
gradeMin = 0;
}
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] <= gradeMax && studentGrade[i] >= gradeMin) {
System.out.println(studentName[i] + " has a " + letterGrade);
System.out.println(letterGrade + " is equivalent to " + gradeMin + " - " + gradeMax + "%");
}
}
}
public static void searchStudent() {
}
public static void classAvg(int numOfKids) {
int average = 0;
for (int i = 0; i < numOfKids; i++) {
average += studentGrade[i];
}
average = (average/numOfKids) * 100;
System.out.println("The average of the class will be " + average + "%");
}
public static void markHighest(int numOfKids) {
int highestNum = 0;
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] > highestNum) {
highestNum = studentGrade[i];
}
}
System.out.println("The highest mark in the class is " + highestNum + "%");
}
public static void markLowest(int numOfKids) {
int lowestNum = 0;
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] < lowestNum) {
lowestNum = studentGrade[i];
}
}
System.out.println("The highest mark in the class is " + lowestNum + "%");
}
public static void markFailing(int numOfKids) {
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] < 50) {
System.out.println(studentName[i] + " is failing with a mark of " + studentGrade[i] + "%");
}
}
}
}
Looks like the argument passed to the classAvg() is not the numOfKids (or size of array) but the option selected by the user from the menu. Trying passing 'numOfKids' instead of passing 'options' as an argument to the function
case 3:
classAvg(options); break;
Better still use studentGrade.length instead of passing argument.
case 3:
classAvg(options); break;
You are passing in the options, but the method wants numOfKids. In this case options will always be 3.
Try passing in numOfKids instead.
Another problem I see is that both average and numOfKids are integers, which causes chopping remainders and rounding to 0 if the denominator is greater. Perhaps change from
average = (average/numOfKids) * 100;
to
average = ((double) average)/ numOfKids * 100;
I think it is better to create a class called Student, with properties name and grade. for more OOP design.
public class Student{
int[] grades;
String name;
public Student(int[] grade, String name){
this.grade = grade;
this.name = name;
}
public double getAverage(){
return (average/(double)numOfKids) * 100;
}
...
}
And average is of type int and numOfKids too, so the division is not gonna be precise. try this average = (average/(double)numOfKids) * 100;

Speeding up/increasing performance of an Java array class

For class, I have to write a program using arrays where someone can look up popular baby names during a certain time frame. (Ex: The most popular boy and girl name from 1890-1910 is ....)
I think the program is decent, but it runs really slow. I don't know if it is just because of my code, or having a simple program look through a large file; but is there a way to speed up the process?
import java.io.*;
import java.util.*;
import java.net.URL;
public class BabyNamesMainDriver {
// ===========================================================================================
private static void process(Scanner sc, String[] args) throws Exception {
// The two arrays
ArrayList<BabyNameClass> boys = new ArrayList<BabyNameClass>();
ArrayList<BabyNameClass> girls = new ArrayList<BabyNameClass>();
System.out.println("Enter a start year between 1880 and 2016:");// start year
int startYear = sc.nextInt();
if (startYear < 1880 || startYear > 2016)// Error check
System.out.println("ERROR: Invalid start year.\n");
else
System.out.println("Enter a end year. Must be less then 2016 but greater than the start year :");// End year
int endYear = sc.nextInt();
if (endYear < 1880 || endYear > 2016)// Error check
System.out.println("ERROR: Invalid end year. \n");
else
System.out.println("Enter the number of baby names to list. ");// Number of baby names
int numOfNames = sc.nextInt();
// if (topBabies <= 0);//Error Check
// System.out.println("ERROR: Invalid number of names. \n");
ReadBabyNames(startYear, endYear, boys, girls);// Reads file info
// Header for top girl names
System.out.print("\nTop " + numOfNames + " Girl names:\n");
for (int i = 0; i < numOfNames; i++) {
System.out.println(girls.get(i));
}
// Header for top boy names
System.out.print("\nTop " + numOfNames + " Boy names:\n");
for (int i = 0; i < numOfNames; i++) {
System.out.println(boys.get(i));
}
sc.nextLine();
}
// ===========================================================================================
private static void ReadBabyNames(int startYear, int endYear, ArrayList<BabyNameClass> boys,
ArrayList<BabyNameClass> girls) throws IOException, Exception {
System.out.println("Please stand by...");
for (int year = startYear; year <= endYear; year++) {
#SuppressWarnings("resource")
Scanner sc = new Scanner(
new URL("https://cs.stcc.edu/~silvestri/babynames/yob" + year + ".txt").openStream());// file from
// URL
sc.useDelimiter("\\s*,\\s*|\\s+");
while (sc.hasNextLine()) {
String name = sc.next();
String sex = sc.next();
int number = sc.nextInt();
sc.nextLine();
BabyNameClass babies = new BabyNameClass(name, number);
Collections.sort(boys);
Collections.sort(girls);
// Getting number of lil' babies
if (sex.equalsIgnoreCase("F")) {
int index = 1;
index = girls.indexOf(babies);
if (index == -1)
girls.add(babies);
else
girls.get(index).addToAmount(number);
} else {
int index = 1;
index = boys.indexOf(babies);
if (index == -1)
boys.add(babies);
else
boys.get(index).addToAmount(number);
}
}
}
}
// ===========================================================================================
public static void main(String args[]) throws Exception {
final String TITLE = "Baby Name Ranking";
final String CONTINUE_PROMPT = "\nDo this again? [y/N] ";
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
do {
process(sc, args);
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using " + TITLE);
}
// ===========================================================================================
private static boolean doThisAgain(Scanner sc, String prompt) {
System.out.print(prompt);
String doOver = sc.nextLine();
return doOver.equalsIgnoreCase("Y");
}
}
2nd class
public class BabyNameClass implements Comparable<BabyNameClass> {
// ==========================
private String name;
private int num;
// ===========================================================================================
public BabyNameClass(String name, int num) {
this.name = name;
this.num = num;
}
// ===========================================================================================
public String getName() {
return this.name;
}
// ===========================================================================================
public int getNum() {
return this.num;
}
// ===========================================================================================
public void addToAmount(int num) {
this.num += num;
}
// ===========================================================================================
public void setAmount(int num) {
this.num = num;
}
// ===========================================================================================
public boolean equals(Object lak) {
if (lak == null)
return false;
if (this == lak)
return true;
if (getClass() != lak.getClass())
return false;
BabyNameClass Gu = (BabyNameClass) lak;
if (name == null) {
if (Gu.name != null)
return false;
} else if (!name.equals(Gu.name))
return false;
return true;
}
// ===========================================================================================
public int compareTo(BabyNameClass arg0) {
if (this.num < arg0.num)
return 1;
if (this.num > arg0.num)
return -1;
if (this.name.compareTo(arg0.name) > 0)
return 1;
if (this.name.compareTo(arg0.name) < 0)
return -1;
else
return 0;
}
// ===========================================================================================
public String toString() {
return " " + this.num + " babies were named " + this.name;
}
}
You're sorting two arraylists every single time you read a new line from the txt file. Why? Sorting is very cpu-intensive. Especially when those txt files you are using are huge.
Just try and move the sort out of the while loop.

Simple ATM task, problems with array.

I want to overwrite the first element of my transaction array when it gets full. So when I print the array, it is always showing the latest transactions.
I think the problem is in the moveTrans method or the findNr method but I'm not sure and I can't figure out what is wrong.
Code:
import java.util.Scanner;
import java.util.*;
public class BankoTest {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int amount = 0;
int choice = 0;
int [] trans = new int[4];
int sum;
int balance = 0;
while (choice != 4)
{
choice = menu();
switch(choice)
{
case 1://
System.out.print("Deposit. Amount? :");
amount = scan.nextInt();
balance = balance + amount;
makeTransactions(trans, amount);
break;
case 2://
System.out.print("Withdra. Amount?");
amount = scan.nextInt();
balance = balance - amount;
makeTransactions(trans, -amount);
break;
case 3:
showTransactions(trans, balance);
break;
case 4:
System.out.println("Thank you. ");
break;
}
}
}
public static int menu()
{
Scanner scan = new Scanner(System.in);
int choice = 0;
System.out.println("1. Deposit ");
System.out.println("2. Withdraw ");
System.out.println("3. Saldo ");
System.out.println("4. End ");
System.out.println();
System.out.println("Choice: ");
choice = scan.nextInt();
return choice;
}
public static void showTransactions(int [] trans, int balance)
{
System.out.println();
System.out.println("Transactions summary :");
System.out.println();
for(int i = 0; i < trans.length-1; i++)
{
if(trans[i] == 0)
{
System.out.print("");
}
else
{
System.out.print(trans[i] + "\n");
balance = balance + trans[i];
}
}
// Printing saldo.
System.out.println();
System.out.println("Current balance: " + balance + " kr" + "\n" );
System.out.println();
}
//Puts amount last among the transactions that are stored in the array. Using the findNr method to find the first available spot
//in the array. moveTrans is used to make room for the new transaction when the array is full.
public static void makeTransactions(int [] trans, int amount )
{
int position = findNr(trans);
if(position == -1)
{
moveTrans(trans);
position = findNr(trans);
trans[position] = amount;
}
else
{
trans[position] = amount;
}
}
public static int findNr(int [] trans)
{
int position = -1;
for(int i = 0; i <= trans.length-1; i++)
{
if(trans[i] == 0)
{
position = i;
break;
}
}
return position;
}
public static void moveTrans(int [] trans)
{
for(int i = 0; i < trans.length-1; i++)
trans[0] = trans[i + 1] ;
}
}
just modify the following method alone
public static void makeTransactions(int[] trans, int amount) {
int position = findNr(trans);
if (position == -1) {
moveTrans(trans);
position = findNr(trans);
trans[position] = amount;
} else {
if (position != 0 && position == trans.length - 1) {
// shift the elements back
for (int i = 0; i < position; i++)
trans[i] = trans[i] + 1;
trans[position - 1] = amount;
}else
trans[position] = amount;
}
}
Please check this it may help some thing to you
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int choice = 0;
int[] trans = new int[4];
int sum;
int balance = 0;
while (choice != 4) {
choice = menu();
switch (choice) {
case 1://
System.out.print("Deposit. Amount? :");
amount = scan.nextInt();
balance = balance + amount;
makeTransactions(trans, amount);
break;
case 2://
System.out.print("Withdra. Amount?");
amount = scan.nextInt();
balance = balance - amount;
makeTransactions(trans, -amount);
break;
case 3:
showTransactions(trans, balance);
break;
case 4:
System.out.println("Thank you. ");
break;
}
}
}
public static int menu() {
Scanner scan = new Scanner(System.in);
int choice = 0;
System.out.println("1. Deposit ");
System.out.println("2. Withdraw ");
System.out.println("3. Saldo ");
System.out.println("4. End ");
System.out.println();
System.out.println("Choice: ");
choice = scan.nextInt();
return choice;
}
public static void showTransactions(int[] trans, int balance) {
System.out.println();
System.out.println("Transactions summary :");
System.out.println();
for (int i = 0; i < trans.length - 1; i++) {
if (trans[i] == 0) {
System.out.print("");
}
else {
System.out.print(trans[i] + "\n");
// balance = trans[i];
}
}
// Printing saldo.
System.out.println();
System.out.println("Current balance: " + balance + " INR" + "\n");
System.out.println();
}
// Puts amount last among the transactions that are stored in the array.
// Using the findNr method to find the first available spot
// in the array. moveTrans is used to make room for the new transaction when
// the array is full.
public static void makeTransactions(int[] trans, int amount) {
int position = findNr(trans);
if (position == -1) {
moveTrans(trans);
System.out.println("Your transaction limit is over.");
// position = findNr(trans);
// System.out.println("Position -------> "+position);
// trans[position] = amount;
} else {
trans[position] = amount;
}
}
public static int findNr(int[] trans) {
int position = -1;
for (int i = 0; i <= trans.length - 1; i++) {
if (trans[i] == 0) {
position = i;
break;
}
}
return position;
}
public static void moveTrans(int[] trans) {
System.out.println("------Your Transaction Details----------");
for (int i = 0; i < trans.length; i++) {
System.out.println("Transation " + (i + 1) + " :: " + trans[i]);
trans[0] = trans[i];
}
System.out.println("----------------------------------------");
}

How to get the total of each column

Its been a ridiculous task especially to build the total of each vertical column & to show it on screen. Though, calculating the total of horizontal row never seemed to be a challenge.
The problem I'm having is three-fold.
How do I calculate the total of each vertical column ?
The index (id) is getting printed in descending order. How do I make it print in ascending order ?
Further, in the percentage column the value after the decimal point is being discarded. How do I get that displayed? For eg.. if
answer is supposed to be 78.25% it exhibits as 78.0%
P.S : (2 places after the decimal point is what I'm aiming at.)
POJO class -- StudentsProg.java
package com.students.marks;
import java.util.Arrays;
public class StudentsProg {
private int id = 0;
private String name;
private int english;
private int german;
private int french;
private int arabic;
private double percentage;
private int total_marks;
private int rowHighest;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getGerman() {
return german;
}
public void setGerman(int german) {
this.german = german;
}
public int getFrench() {
return french;
}
public void setFrench(int french) {
this.french = french;
}
public int getArabic() {
return arabic;
}
public void setArabic(int arabic) {
this.arabic = arabic;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public int getTotal_marks() {
return total_marks;
}
public void setTotal_marks(int total_marks) {
this.total_marks = total_marks;
}
public int getRowHighest() {
return rowHighest;
}
public void setRowHighest(int rowHighest) {
this.rowHighest = rowHighest;
}
public String toString() {
id = id+1;
return (id + "\t" +name+ "\t\t" +english+ "\t" + " " +german+ "\t" + " "+ french+ "\t" + " " +arabic+ "\t" +" " +total_marks+ "\t\t" + " " +percentage+ "\t\t" +rowHighest);
}
}
StudentsProgMain.java
import java.util.Scanner;
public class StudentsProgMain {
#SuppressWarnings("resource")
public static void main(String[] args) {
int count = 0;
StudentsProg[] stud = new StudentsProg[15];
int choice=0;
int max = 0;
Scanner scanner = new Scanner(System.in);
do{
System.out.println("1: Add new Student");
System.out.println("2: List Student");
System.out.println("3: List Student By Name.");
System.out.println("4: Delete Student");
System.out.println("5: Exit");
System.out.println("Please enter your choice \n\n");
choice=scanner.nextInt();
switch(choice){
case 1:
stud[count] = new StudentsProg();
System.out.println("Enter student name");
stud[count].setName(scanner.next());
System.out.println("Enter marks in English");
stud[count].setEnglish(scanner.nextInt());
System.out.println("Enter marks in German");
stud[count].setGerman(scanner.nextInt());
System.out.println("Enter marks in French");
stud[count].setFrench(scanner.nextInt());
System.out.println("Enter marks in Arabic");
stud[count].setArabic(scanner.nextInt());
count++;
break;
case 2:
System.out.println("ID\t" + "Name \t\t\t" + "English\t" + " " + "German\t"+ " " + "French\t" + " " + "Arabic\t"
+" "+ "Total Marks\t" + " " + "Percentage\t" + "Highest Marks(Row)\n" +
"------------------------------------------------------------------------"
+ "------------------------------------------- \n ");
for(int i=0; i<count; i++){
if(stud[i]!=null){
int total_marks = stud[i].getEnglish()+stud[i].getGerman()+ stud[i].getFrench()+stud[i].getArabic();
stud[i].setTotal_marks(total_marks);
double calc_per = ((total_marks*100)/400);
stud[i].setPercentage(calc_per);
int arrayListMarks [] = {stud[i].getEnglish(), stud[i].getFrench(), stud[i].getGerman(), stud[i].getArabic()};
max = arrayListMarks[0];
for (int j = 1; j < arrayListMarks.length; j++) {
if(arrayListMarks[j] > max)
max = arrayListMarks[j]; }
stud[i].setRowHighest(max);
System.out.println(stud[i].toString());
System.out.println("\n");}
}
System.out.println("--------------------------------------------------------------"
+ "----------------------------------------------------- \n");
System.out.println("\tTotal :" +"\n");
break;
case 3 :
System.out.println("Please enter your name");
String name = scanner.next();
System.out.println("\n" + "ID\t" + "Name \t\t\t" + "English\t" + " " + "German\t"+ " " + "French\t" + " " + "Arabic\t"
+" "+ "Total Marks\t" + " " + "Percentage\t" + "Highest Marks(Row)\n" +
"------------------------------------------------------------------------"
+ "------------------------------------------- \n ");
for(int i =0 ; i<count; i++){
if(stud[i]!=null && stud[i].getName().equals(name))
System.out.println(stud[i].toString()); }
System.out.println("--------------------------------------------------------------"
+ "----------------------------------------------------- \n");
break;
case 4 :
System.out.println("Please enter your name");
String naam = scanner.next();
for (int i = 0; i<count; i++) {
if(stud[i]!=null && stud[i].getName()==naam)
stud[i]=null;
}
break;
case 5:
System.exit(0);
System.out.println("You have exited successfully");
default :
System.out.println("Invalid choice");
}
}while(true);
}
}
The problem with the percentage calculation is that the line of code double calc_per = ((total_marks*100)/400); will do integer arithmetic and truncate each intermediate result as an integer. To fix this you need to include a floating point number somewhere in the calculation either by converting total_marks to double like so:
double calc_per = ((Integer.valueOf(total_marks).doubleValue()*100)/400);
Or using a float constant like so:
double calc_per = ((total_marks*100.0)/400);
Vertical totals should just be a matter of adding the row value to a variable inside your print loop.
I'm not really sure about your index order problem but the code in toString() that reads id = id+1; looks wrong. This will increment the Id each time you call toString(). Instead of that, your creation code should set the value of id just after creating the object, something like:
stud[count] = new StudentsProg();
// add the following line of code.
stud[count].setId(count);
System.out.println("Enter student name");
stud[count].setName(scanner.next());

Array not printing properly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why does the array "prevScore" not print the value "points"?
I want it to print out points for prevScore [0], and then null 0
This is the array, after the // is something I thought I could use.
int [] prevScore = new int[10]; //{ 0 };
String [] prevScoreName = new String[10]; //{"John Doe"};
public static int[] scoreChange (int prevScore[], int points)
{
for(int i = 9; i > 0; i--){
prevScore[i] = prevScore[i-1];
}
prevScore[0]= points;
return prevScore;
}
I dont know if the print of prevScore is needed.
//a method that prints high scores
public static void printScores (int prevScore[], String prevScoreName[])
{
for (int i = 10; i > 0; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}
}
Here is the rest of my program I am working on... currently only i get one, 0 John Doe.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
do {
int menuchoice = 0;
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1){
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2){
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName); }
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR"); }
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct){
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ){
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}
Use this loop:
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
I think it should solve your problem.
Update
based on your updated program. Move the following code above the start of the 'do' loop.
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
That is you are moving these lines out of the loop. It should work now.
That is the start of your 'main' method should look something like this:
public static void main(String args[]) throws IOException {
int press = 0;
int[] prevScore = new int[] { 0 };
String[] prevScoreName = new String[] { "John Doe" };
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions," + "3 prev score");
Your printScore() method is trying to access element [10] of an array whose index range is 0 - 9, and is never accessing element [0]. You may want to print the most recent score first:
for (int i = 0; i < 10; i++) {
Or conversely, to print the most recent score last:
for (int i = 9; i >= 0; i--) {
Thank you so much! It Works! The only problem still is that the scorelist prints backwards.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
int[] prevScore = new int[10];
String[] prevScoreName = new String[10];
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1) {
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2) {
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName);
}
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR");
}
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct) {
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ) {
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
System.out.println("Scores: ");
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}

Categories

Resources