how to transverse arraylist - java

I need to know how to transverse my average function into this result function if u are getting ?
This is the main class:
import java.util.ArrayList;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList < Calculations > students = new ArrayList < Calculations > ();
for (int i = 0; i < 5; ++i) {
Calculations s = new Calculations();
System.out.print("Enter name : ");
s.name = scan.next();
System.out.print("Eter percentage : ");
s.percetage = scan.nextDouble();
students.add(s);
System.out.println("Enter Mrks Obtained");
}
for (Calculations s: students) {
s.result();
for (Calculations i: students) {
s.Average();
}
}
}
}
This is result class:
import java.util.Scanner;
public class Calculations {
public String name;
public double percetage;
public int integer;
public void result() {
System.out.println((percetage >= 35.0 f ? (name + " Pass") : (name + " Fail")));
}
public void Average() {
// TODO Auto-generated method stub
int mark[] = new int[5];
int i;
float sum = 0;
float avg, perc;
Scanner scan = new Scanner(System.in);
System.out.print("Enter marks Obtained in 5 Subjects : ");
for (i = 0; i < 5; i++) {
mark[i] = scan.nextInt();
sum = sum + mark[i];
}
avg = sum / 5;
perc = (sum / 500) * 100;
System.out.print("Average Marks = " + avg);
System.out.print("\nPercentage = " + perc + "%");
}
}

for(Calculations s : students){
s.result();
//for(Calculations i : students){s.Average(); }
s.Average();
}
you dont have to loop your arraylist twice. try changing your code.

It was so hard to follow through your incomplete question, which is not specific either. Your program works fine in my eclipse. I would suggest following:
1) Check the name of the fields/ spelling in you Calculations class to match exactly as it's been used in the main class.
2) Since you're inputting String Scanner, try to read lines as follows:
s.name = scan.nextLine();
I hope it helped.

Related

How to connect two class modules together in Java?

I have a program that contains five .txt files. These files are read in and put into different arrays. One is an array of names. The other four are arrays with test scores.
Currently, the program does create the arrays correctly. Next the program is to calculate and display the average for each test (this works fine). Then the program prompts the user for a name. If a name is found a new menu will prompt the user to select which test they want the data on. (This works fine).
The problem: I have the main program class and another GradeBook class (does calculations) on another page. How do I connect the two pages together?
For example: If the studentName is 'Andrew' and it is found in studentNameArray, and I select 1 for which test score I want to see (scoreOneArray), say the number 88. My program finds 'Andrew' and '88'. What it does not do is send 'Andrew' and '88' to GradeBook to have the data compute test percentage (88/100) and find the corresponding letter grade (in this case 'B'). Lastly, then print students name, test score (88%), and the letter grade.
Program (main):
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
double test1Calculation;
double test2Calculation;
double test3Calculation;
double test4Calculation;
int i, j, k, l;
int testOneSum = 0;
int testTwoSum = 0;
int testThreeSum = 0;
int testFourSum = 0;
int checker = 0;
int index=0;
String choice;
Scanner students = new Scanner(new File("names.txt"));
Scanner TestOne = new Scanner(new File("testOne.txt"));
Scanner TestTwo = new Scanner(new File("testTwo.txt"));
Scanner TestThree = new Scanner(new File("testThree.txt"));
Scanner TestFour = new Scanner(new File("testFour.txt"));
String token1 = "";
List<String> studentName = new ArrayList<>();
while (students.hasNext()) {
// find next line
token1 = students.next();
studentName.add(token1);
}
String[] studentNameArray = studentName.toArray(new String[0]);
List<Integer> scoreOne = new ArrayList<>();
// while loop
while (TestOne.hasNext()) {
// find next line
Integer token2 = TestOne.nextInt();
scoreOne.add(token2);
}
Integer[] scoreOneArray = scoreOne.toArray(new Integer[0]);
List<Integer> scoreTwo = new ArrayList<>();
// while loop
while (TestTwo.hasNext()) {
// find next line
Integer token3 = TestTwo.nextInt();
scoreTwo.add(token3);
}
Integer[] scoreTwoArray = scoreTwo.toArray(new Integer[0]);
List<Integer> scoreThree = new ArrayList<>();
// while loop
while (TestThree.hasNext()) {
// find next line
Integer token4 = TestThree.nextInt();
scoreThree.add(token4);
}
Integer[] scoreThreeArray = scoreThree.toArray(new Integer[0]);
List<Integer> scoreFour = new ArrayList<>();
// while loop
while (TestFour.hasNext()) {
// find next line
Integer token5 = TestFour.nextInt();
scoreFour.add(token5);
}
Integer[] scoreFourArray = scoreFour.toArray(new Integer[0]);
for (i = 0; i < scoreOneArray.length; i++)
testOneSum += scoreOneArray[i];
test1Calculation = (double) testOneSum / 5;
for (j = 0; j < scoreTwoArray.length; j++)
testTwoSum += scoreTwoArray[j];
test2Calculation = (double) testTwoSum / 5;
for (k = 0; k < scoreThreeArray.length; k++)
testThreeSum += scoreThreeArray[k];
test3Calculation = (double) testThreeSum / 5;
for (l = 0; l < scoreFourArray.length; l++)
testFourSum += scoreFourArray[l];
test4Calculation = (double) testFourSum / 5;
System.out.println("The average for test one is: " + test1Calculation);
System.out.println("The average for test two is: " + test2Calculation);
System.out.println("The average for test three is: " + test3Calculation);
System.out.println("The average for test four is: " + test4Calculation);
Scanner studentSearch = new Scanner(System.in);
System.out.println("Enter student name : ");
String foundStudent = studentSearch.nextLine();
boolean found = Arrays.stream(studentNameArray).anyMatch(t -> t.equals(foundStudent));
if (found) {
index++;
System.out.println(foundStudent + " is found.");
//menu loop
do {
//displayed user options
System.out.println("1. To find score for first test");
System.out.println("2. To find score for second test");
System.out.println("3. To find score for third test");
System.out.println("4. To find score for fourth test");
//menu choices
Scanner keyboard = new Scanner(System.in);
System.out.print("\nEnter your choice: ");
choice = keyboard.next();
if (choice.equals("1")) {
int score= scoreOneArray[index];
System.out.println(score);
checker = -1;
} else if (choice.equals("2")) {
int score= scoreTwoArray[index];
System.out.println(score);
checker = -1;
} else if (choice.equals("3")) {
int score= scoreThreeArray[index];
System.out.println(score);
checker = -1;
} else if (choice.equals("4")) {
int score= scoreFourArray[index];
System.out.println(score);
checker = -1;
} else {
//Error message
System.out.println("invalid choice");
}
}
while (checker != -1);
} // End of Menu Method
else {
System.out.println(foundStudent + " is not found.");}
students.close();
TestOne.close();
TestTwo.close();
TestThree.close();
TestFour.close();
}
}
Calculations(GradeBook):
import java.util.ArrayList;
public class GradeBook {
private char[] letterGrade = {'A', 'B', 'C', 'D', 'F'};
private ArrayList<String> names = new ArrayList<>();
private double [][] scores = new double[5][4];
public GradeBook(ArrayList<String> studentNames, double[][] studentScores){
this.names = studentNames;
for (int i = 0; i < 5; i++){
for (int j = 0; j < 4; j++){
scores [i][j] = studentScores[i][j];
}
}
}
public String getName(int studentIndex){
return names.get(studentIndex);
}
public double getAverage(int studentIndex){
double total = 0;
for (int i = 0; i < 4; i++){
total += scores[studentIndex][i];
}
return (total / 4);
}
public char getLetterGrade(double avgScore){
if (avgScore >= 90 && avgScore <= 100){
return letterGrade[0];
}
else if (avgScore >= 80 && avgScore <= 89){
return letterGrade[1];
}
else if (avgScore >= 70 && avgScore <= 79){
return letterGrade[2];
}
else if (avgScore >= 60 && avgScore <= 69){
return letterGrade[3];
}
else if (avgScore >= 0 && avgScore <= 59){
return letterGrade[4];
}
return ' ';
}
public void getStudent(){
for (int i = 0; i < names.size(); i++){
System.out.println("\nStudent #" + (i+1)
+"\n\t\tName: " + names.get(i)
+"\n\t\tAverage: " + getAverage(i) + "%"
+"\n\t\tLetter Grade: " + getLetterGrade(getAverage(i))
+"\n\n");
}
}
}
I don't understand how much of what's going on in GradeBook relates to what you're doing in your main function. I see how in your main you're coming up with a single score based on the user's selection of a student and a test number. But once you have this user and score, I don't see how that matches up with the data in the double[][] studentScores table contained in GradeBook. What is that data? Where does it come from?
Your code in main seems to have a significant problem. index will always be 1 by the time it's used. Its value is not affected by what is entered as a student name. I think you mean for it to be. Also, I don't understand how the single integer score you come up with in main matches up with the avgScore accepted by the GradeBook. But ignoring all of that...
It seems like you'd have just a single GradeBook, right? So I think you'd instantiate just a single instance of it, and then you could use it to look up the student's name and to calculate the grade based on the student's score. Assuming that index matched up with the names list in GradeBook, and you somehow computed an averageScore, that would look something like this...
public class Main {
public static void main(String[] args) throws IOException {
...
GradeBook gradeBook = new GradeBook(...);
...
while (...) {
index = ...
...
averageScore = ...
...
studentName = gradeBook.getName(index);
grade = gradeBook. getLetterGrade(averageScore);
System.out.println(String.format("Student: %s. Grade: %s", studentName, grade));
}
The other use case I can see is that you'd calculate somehow calculate the studentScores table from the data you read in main, and then you could create a GradeBook with that to have it display all of that information. That would look like this...
studentScores = ...
...
GradeBook gradeBook = new GradeBook(studentScores);
gradeBook.getStudent()

Issue: Reading 10 different marks into my marks variable. FOR loop

import java.util.*;
public class loops
{
public static void main (String []args)
{
Scanner input = new Scanner (System.in).useDelimiter("\n");
for (int i = 0; i <= 9; i++)
{
System.out.print("Enter your mark: ");
int marks = input.nextInt();
}
int marks = + input.nextInt();
int totalmarks = marks / 10;
System.out.println("The class average was:"+ totalmarks + ".");
}
}
The question is not clearly asked but according to my interpretation, the problem is to add all the input marks and give the average, so declare a sum variable with initial value 0 and add all the marks coming as input and take the average.
import java.util.*;
public class loops
{
public static void main (String []args)
{
Scanner input = new Scanner (System.in).useDelimiter("\n");
int sum=0;
for (int i = 0; i <= 9; i++)
{
System.out.print("Enter your mark: ");
int marks = input.nextInt();
sum=sum+marks;
}
int totalmarks = sum / 10;
System.out.println("The class average was:"+ totalmarks + ".");
}
}

Changing input variables in a java loop

I have an assignment, and I need to use a loop to allow a user to enter ten different numbers in a programme which then adds up the variables.
I have found various pieces of code and stitched them together to create this:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
String totalNum, num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;
Scanner in = new Scanner (System.in);
System.out.println("Please enter ten numbers:");
int[] inputs = new int[10];
for (int i = 0; i < inputs.length; ++i)
{
inputs[i] = in.next();
}
//Process
totalNum = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10;
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}
It's not great, but it's the best I have so far. Please help?
You don't need the variables num1 to num10. You can simply sum up in the loop itself. Like:
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += = in.next(); // sum = sum + in.next();
}
Furthermore you assigned your variables as Strings, but you need int. In your case it would print something like 1111111111, if the input would always be a 1.
Take a look here how you would handle Integers properly.
You can achieve that in two ways, either inside the loop itself just add the number or if you need to keep track of them for later just add them to the array.
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
String total;
Scanner in = new Scanner (System.in);
int numOfInputValues = 10;
System.out.println("Please enter ten numbers:");
int[] inputs = new int[numOfInputValues];
for (int i = 0; i < numOfInputValues; ++i)
{
// Append to array only if you need to keep track of input
inputs[i] = in.next();
// Parses to integer
total += in.nextInt();
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}
First of all, your class should be in CamelCase. First letter is always in capital letter.
Second, you don't need an array to save those numbers.
Third you should make a global variable that you can change with ease. That is a good practice.
And you should always close stream objects like Scanner, because they leak memory.
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
int numberQuantity = 10;
int totalNum = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter ten numbers:");
for (int i = 0; i <= numberQuantity; i++) {
totalNum += in.nextInt();
}
in.close();
System.out.println(totalNum);
}
}
So the simplest answer I found is:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
int totalNum, num1;
totalNum = 0;
for (int numbers = 1 /*declare*/; numbers <= 10/*initialise*/; numbers ++/*increment*/)
{
num1 = Integer.parseInt(JOptionPane.showInputDialog("Input any number:"));
totalNum = totalNum + num1;
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
Try this way I only re-edit your code:
import javax.swing.*;
public class InputNums {
public static void main(String[] args) {
int total = 0;
for (int i = 0, n = 0; i < 10;) {
boolean flag = false;
try {
n = Integer.parseInt(JOptionPane
.showInputDialog("Input any number:"));
} catch (NumberFormatException nfe) {
flag = true;
}
if (flag) {
flag = false;
JOptionPane.showMessageDialog(null,
"Invalid no Entered\nEnter Again...");
continue;
}
total += n;
i++;
}
JOptionPane.showMessageDialog(null, "Total = " + total);
}
}

Copy Constructor Test not Working (Java)

I'm working on CS homework and have run into a problem. The end of the homework asks about using a copy constructor. The goal is to "make one Payroll object, instantiate it, make a second one, then print them both. Then, change values in the second Payroll object, and show that the changed values only appear in one and not both (that is, print out the original and the copy with slightly changed values)." I tried changing the values in the second Payroll object, but it also changes it in the first. I've listed my code below:
import java.util.Random;
public class Payroll {
private int[] employeeId;
private int[] hours;
private double[] payRate;
public Payroll(){
this.employeeId = new int[0];
this.hours = new int[0];
this.payRate = new double[0];
}
public Payroll(Payroll obj){
this.employeeId = obj.employeeId;
this.hours = obj.hours;
this.payRate = obj.payRate;
}
public Payroll(int i){
this.employeeId = new int[i];
this.hours = new int[i];
this.payRate = new double[i];
}
public int getEmployeeIdAt(int index){
return employeeId[index];
}
public int getHoursAt(int index){
return hours[index];
}
public double getPayRateAt(int index){
return payRate[index];
}
public double getGrossPay(int index){
double grossPay = hours[index] * payRate[index];
grossPay = Math.round(grossPay * 100);
return grossPay/100;
}
public void setEmployeeIdAt(int index, int id){
this.employeeId[index] = id;
}
public void setHoursAt(int index, int hrs){
this.hours[index] = hrs;
}
public void setPayRateAt(int index, double pr){
this.payRate[index] = pr;
}
public void setHoursAt(int i){
Random rand = new Random();
int randHours = rand.nextInt((50 - 15) + 1) + 15;
this.hours[i] = randHours;
}
}
import java.util.Scanner;
public class PayrollDriver {
public static void main(String[] args) {
Payroll pr = new Payroll(5);
Scanner scan = new Scanner(System.in);
int empID = 1001;
for(int i = 0; i < 5; i++){
pr.setEmployeeIdAt(i, empID);
empID++;
}
for(int i = 0; i < 5; i++){
System.out.println("Enter the hourly pay rate for employee number " + pr.getEmployeeIdAt(i) + ": ");
double payRate = scan.nextDouble();
if(payRate < 7.50){
do{
System.out.println("ERROR: Enter 7.50 or greater for pay rate: ");
payRate = scan.nextDouble();
} while(payRate < 7.50);
}
pr.setPayRateAt(i, payRate);
pr.setHoursAt(i);
}
System.out.println("PAYROLL DATA");
System.out.println("======================");
for(int i = 0; i < 5; i++){
System.out.println("Employee ID: " + pr.getEmployeeIdAt(i) + " Hours: " + pr.getHoursAt(i) + " Rate: " + pr.getPayRateAt(i) +
" Gross Pay: $" + pr.getGrossPay(i));
}
System.out.println("Would you like to run the Copy Constructor Test? Enter 'y' (lowercase) if yes, enter any other letter if no: ");
char copyTestVerify = scan.next().charAt(0);
if(copyTestVerify == 'y'){
CopyConstructorTest ct = new CopyConstructorTest();
ct.CopyTest();
}
scan.close();
}
}
The following is my CopyConstructorTest class, the one that tests whether or not the copy constructor will change the original object's values:
public class CopyConstructorTest {
public void CopyTest(){
Payroll pay = new Payroll(5);
pay.setEmployeeIdAt(0, 1001);
Payroll payCopy = new Payroll(pay);
System.out.println("Original: " + pay.getEmployeeIdAt(0));
System.out.println("Copy: " + payCopy.getEmployeeIdAt(0));
payCopy.setEmployeeIdAt(0, 5000);
System.out.println("Original after changes: " + pay.getEmployeeIdAt(0));
System.out.println("Copy after changes: " + payCopy.getEmployeeIdAt(0));
}
}
I'm not positive on what I'm doing wrong. Any help or guidance is much appreciated.
You are just copying the references to the arrays, not the actual data. Therefore whenever you change the data in one of your objects, the changes are seen in both, since they point to the same array.
The easiest way to copy the data is probably using System.arraycopy():
public Payroll(Payroll obj) {
this.employeeId = new int[obj.employeeId.length];
System.arraycopy(obj.employeeId, 0, this.employeeId, 0, obj.employeeId.length);
...

unexpected results - can please some one point the mistake

after spending number of hours and trying different things, i can't figure out what is wrong with my code, it's a simple program : `
public class AssignGrades {
private int ntotal=0;
private int []y;
//constructor to initialize class instances
AssignGrades(int t)
{
ntotal = t;
//y = num1;
}
AssignGrades( int []num1)
{
y=num1;
for (int i=0;i<y.length;i++)
y[i] = num1[i];
}
//method to sort grades int []num1
void setGrades()
{
int [] y = new int[ntotal];
for (int i=0;i<y.length;i++)
{
//assign grades
if
(y[i]<80){
System.out.println("grade is A" +y[i]);}
else if (y[i]<70)
System.out.println("grade is B" +y[i]);
else if (y[i]<60)
System.out.println("grade is c" +y[i]);
else
System.out.println("FAIL" +y[i]);
}
}
//show student grades - to print array[] values
void showGrades()
{
for (int u: y)
System.out.println(u);
}
}`
my client program
`import java.util.Scanner;
public class AssignGradesDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int t=0;
System.out.println("enter no of students" );
Scanner input = new Scanner(System.in);
{
t=input.nextInt();
// input.close();
}
int [] num1 = new int[t];
System.out.println("enter grades");
Scanner input1 = new Scanner(System.in);
for (int i=0;i<num1.length;i++)
{
num1[i]=input1.nextInt();
}
input1.close();
AssignGrades ag = new AssignGrades(t);
AssignGrades ag1 = new AssignGrades( num1);
ag.setGrades();
ag1.showGrades();
}
}
output is:
enter no of students
2
enter grades
78
98
grade is A0
grade is A0
78
98
Question: now in the output 'A' and '0' -> where the problem is, it looks like array is not initialized, all the values appear to be zero: whereas when I print them separately, they are initialized.?!
Please let me know if more clarification is required. thanks
You have a local variable called y and a class variable with the same name y. That seems to be the problem. You are using the local y but you meant to use the class y, I think.
OK, your code had lots of problems. Here is the fixed version.
public class AssignGrades {
private int[] y;
public AssignGrades(int[] num1) {
y = num1;
}
// method to set grades
void setGrades() {
for (int i = 0; i < y.length; i++)
{
// assign grades
if (y[i] < 50)
System.out.println("FAIL" + y[i]);
else if (y[i] < 60)
System.out.println("grade is C" + y[i]);
else if (y[i] < 70)
System.out.println("grade is B" + y[i]);
else if (y[i] < 80) {
System.out.println("grade is A" + y[i]);
}
}
}
// method to show student grades
void showGrades() {
for (int u : y){
System.out.println(u);
}
}
}
import java.util.Scanner;
public class AssignGradesDemo {
public static void main(String[] args) {
int t = 0;
System.out.println("enter no of students");
Scanner input = new Scanner(System.in);
t = input.nextInt();
int[] num1 = new int[t];
System.out.println("enter grades");
for (int i = 0; i < num1.length; i++) {
num1[i] = input.nextInt();
}
input.close();
AssignGrades ag = new AssignGrades(num1);
ag.setGrades();
ag.showGrades();
}
}

Categories