how to take the result from the loop into string with index? - java

I am trying to build a string, and put the result of the loop
"att" into string with the index "i". So, I can sort the string and output the highest attendance school with the school number. Thanks!
import java.util.Scanner;
public class PengjuShanP1 {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many schools do you have in your district: ");
int nos = scnr.nextInt();
int[] nums = new int[nos];
System.out.println();
double ax = 0;
for (int i = 1; i < nos + 1; ++i) {
System.out.println("Enter data for school " + i);
System.out.print(" How many students are enrolled in school : ");
int num = scnr.nextInt();
System.out.print(" Enter the attendance for day 1: ");
int d1 = scnr.nextInt();
System.out.print(" Enter the attendance for day 2: ");
int d2 = scnr.nextInt();
System.out.print(" Enter the attendance for day 3: ");
int d3 = scnr.nextInt();
System.out.print(" Enter the attendance for day 4: ");
int d4 = scnr.nextInt();
System.out.print(" Enter the attendance for day 5: ");
int d5 = scnr.nextInt();
double avg = ((d1 + d2 + d3 + d4 + d5) / 5) * 100;
double att = avg / num;
ax = att + ax;
System.out.println();
System.out.println("Attendance " + att + "% for school " + i);
System.out.println();
}
System.out.print(ax);
}
}

EDIT
Given that the school id is an integer, it's possible to do this in a simple array, which is more space and time efficient than the collections API below.
Initialize a double array early on:
double[] schools = new double[nos];
Add data in the loop:
schools[i] = att;
And find the highest at the end, with printing:
double highest = 0;
int index = 0;
for (int i = 0; i < schools.length; i++)
{
if (schools[i] > highest)
{
index = i;
highest = schools[i];
}
}
System.out.println("The school with the best attendance is school " + (index + 1) + " with " + highest + "% attendance");
The full example:
import java.util.Scanner;
public class ValuePairSortingSimpler
{
public static void main(String[] args)
{
Scanner scnr = new Scanner(System.in);
System.out.print("How many schools do you have in your district: ");
int nos = scnr.nextInt();
double[] schools = new double[nos];
System.out.println();
double ax = 0;
for (int i = 0; i < nos; i++)
{
System.out.println("Enter data for school " + (i + 1));
System.out.print(" How many students are enrolled in school : ");
int num = scnr.nextInt();
System.out.print(" Enter the attendance for day 1: ");
int d1 = scnr.nextInt();
System.out.print(" Enter the attendance for day 2: ");
int d2 = scnr.nextInt();
System.out.print(" Enter the attendance for day 3: ");
int d3 = scnr.nextInt();
System.out.print(" Enter the attendance for day 4: ");
int d4 = scnr.nextInt();
System.out.print(" Enter the attendance for day 5: ");
int d5 = scnr.nextInt();
double avg = ((d1 + d2 + d3 + d4 + d5) / 5) * 100;
double att = avg / num;
schools[i] = att;
ax = att + ax;
System.out.println();
System.out.println("Attendance " + att + "% for school " + (i + 1));
System.out.println();
}
double highest = 0;
int index = 0;
for (int i = 0; i < schools.length; i++)
{
if (schools[i] > highest)
{
index = i;
highest = schools[i];
}
}
System.out.println("The school with the best attendance is school " + (index + 1) + " with " + highest + "% attendance");
System.out.print(ax);
}
}
Original Post:
I'm not sure a string is the best route here. If I'm not mistaken, you'd like to store several pairs of values in a list or array and then sort that by one of the values. That problem is best solved using the collections API. For an example:
Define a list of key-value pairs at the beginning (before the loop). The key will be the school id and the value will be the attendance.
List<Map.Entry<Integer, Double>> schools = new ArrayList<>();
Then add the data to the list in the loop:
schools.add(Map.entry(i, att));
And at the end, sort it descending by value (highest first), then print the results.
schools.sort((a,b)->(int)Math.round(b.getValue()-a.getValue()));
System.out.println("The school with best attendance is school " + schools.get(0).getKey() + " with " + schools.get(0).getValue() + "% attendance!");
A full example follows:
public static void main(String[] args)
{
Scanner scnr = new Scanner(System.in);
System.out.print("How many schools do you have in your district: ");
int nos = scnr.nextInt();
List<Map.Entry<Integer, Double>> schools = new ArrayList<>();
System.out.println();
double ax = 0;
for (int i = 1; i < nos + 1; ++i)
{
System.out.println("Enter data for school " + i);
System.out.print(" How many students are enrolled in school : ");
int num = scnr.nextInt();
System.out.print(" Enter the attendance for day 1: ");
int d1 = scnr.nextInt();
System.out.print(" Enter the attendance for day 2: ");
int d2 = scnr.nextInt();
System.out.print(" Enter the attendance for day 3: ");
int d3 = scnr.nextInt();
System.out.print(" Enter the attendance for day 4: ");
int d4 = scnr.nextInt();
System.out.print(" Enter the attendance for day 5: ");
int d5 = scnr.nextInt();
double avg = ((d1 + d2 + d3 + d4 + d5) / 5) * 100;
double att = avg / num;
schools.add(Map.entry(i, att));
ax = att + ax;
System.out.println();
System.out.println("Attendance " + att + "% for school " + i);
System.out.println();
}
System.out.print(ax);
schools.sort((a,b)->(int)Math.round(b.getValue()-a.getValue()));
System.out.println("The school with best attendance is school " + schools.get(0).getKey() + " with " + schools.get(0).getValue() + "% attendance!");
}

The question is not clear and array index always start from zero instead of 1 as mentioned in the for loop. if you are looking to store att in array of String, declare String array and store att in the string array

Related

How to set a limit in a for loop?

I have to create a program to calculate the average of each students' scores. I managed to do that but how can I limit the score to be only between 0 to 100? I've searched other questions and many shows to put while statement. The problem is that I don't know where to add the while. So here's the code:
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Total += new Scanner(System.in).nextInt();
Total += Score;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
If there is any other ways please do state. Thanks in advance.
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
double Input = 0; **//Add this in your variable**
boolean Valid = false; **//Add this in your variable**
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
//validation of your input from 0 to 100
if(Input>=0&&Input<=100)
{
Valid = true;
}
//enter while loop if not valid
while(!Valid)
{
System.out.println("");
System.out.print("Please enter a valid score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
if(Input>=0&&Input<=100)
{
Valid = true;
}
}
Valid = false; //reset validation;
Total += Input;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
An easy way to go about this would be to put the user-input prompt inside of a while loop, and only break out once you've verified that the grade is valid:
Scanner scanner = new Scanner(System.in);
int score;
while (true) {
System.out.print("Please enter score " + (g + 1) + ": ");
score = scanner.nextInt();
if (score >= 0 && score <= 100) {
break;
}
System.out.println("Please enter a valid score between 0 and 100!");
}
Total += score;
Remember to close your Scanners to avoid memory leaks!

Java Change Prompt Order

I am currently working on a java program that has to do with taking classes and the amount of credits for each class. I have everything set up how I need it, except the order.
I would like it to ask for a class, then how many credits that class is, then ask for the next class, and those credits, and so on. Right now, it will ask for all of the classes, then all of the credits. Here's the code I have:
//Jake Petersen
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.println("Please enter a course:");
courseArray[i] = scan.nextLine();
}
int creditArray[] = new int[courses];
for (int i = 0; i < creditArray.length;) {
System.out.println("Please enter how many credits "+ courseArray[i] + " is:");
int input = scan.nextInt();
if (input >= 1 && input <= 4) {
creditArray[i++] = input;
}
}
int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Do all the prompts in a single for loop:
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
int creditArray[] = new int[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.print("Please enter a course:");
courseArray[i] = scan.nextLine();
System.out.print("Please enter how many credits "+ courseArray[i] + " is:");
String credits = scan.nextLine();
int input = Integer.parseInt(credits);
if (input >= 1 && input <= 4) {
creditArray[i] = input;
}
else {
creditArray[i] = 0;
}
} int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Of course this assumes that the 2 arrays have the same size. Perhaps you want to prompt for a class count first, to know how large to make the arrays, or grow them dynamically.

Guidance needed for Invalid input error and collaborative class statistics for Grade Calculator

I am building a grade calculator in Java, I am having trouble adding a couple features to it, and it appears that I keep mucking it up too while I try to make changes. I have been working on it all week, and started over in the book and the powerpoint slides, and I just feel like there are just some pieces I am still not getting.
I need to make sure the invalid scores, reenter error shows up everytime a negative score is inputted. And then I need to calculate the class statistics of Average, Lowest and Highest scores. So basically a collaboration of how ever much data was inputted which could be any number of exams or students.
Here is my code, please let me know if you need more info. I am really new to this so I apologize that it is not the greatest.
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args){
double examAverage = 0, scoresEntered = 0, examSum = 0;
double totalExamSum = 0, allScoresEntered = 0;
//variables for input
Scanner GC = new Scanner(System.in);
//Scanner for integer inputs
System.out.println("Welcome to Grade Calculator!" +"\n");
System.out.println("Please enter the number of students:");
int numberStudents = GC.nextInt();
//number of students input
System.out.println("Please enter the number of exams:");
int numberOfExams = GC.nextInt();
//number of exams input
for (int i = 1; i <= numberStudents; i++) {
Scanner name = new Scanner(System.in);
//scanner for student name input
//Scanner for name input
System.out.println("\n--------------------------------------");
System.out.print("Enter student " + i + "'s name : " );
String studentname = name.nextLine();
//student name input
System.out.print("Enter exam scores : ");
for (int j = 0; j < numberOfExams; j++) {
scoresEntered = GC.nextDouble();
examSum = (examSum + scoresEntered);}
//score input and sum of all input scores
do{
System.out.println("Invalid exam scores, reenter: ");
scoresEntered =GC.nextDouble();
} while(scoresEntered<0);
//my attempt at the Invalid exam score error
examAverage = (examSum/numberOfExams);
//examaverage calculator
System.out.println("\n--------------------------------------");
System.out.println("Grade Statistics for " + name);
System.out.println(" Average : " + examAverage);
//Conditions and print outputs below for grade averages
if(examAverage <= 100 & examAverage >=90){
System.out.println(" Letter Grade: A");
System.out.println(" " + name + " gets 4 stars! ****");
examAverage = 0;
examSum = 0;}
else if(examAverage <=89.99 & examAverage >=80){
System.out.println(" Letter Grade: B");
System.out.println(" " + name + " " + " gets 3 stars! ***");
examAverage = 0;
examSum = 0;}
else if(examAverage <=79.99 & examAverage >=70){
System.out.println(" Letter Grade: C");
System.out.println(" " + name + " " + " gets 2 stars! **");
examAverage = 0;
examSum = 0;}
else if(examAverage <=69.99 & examAverage >=60){
System.out.println(" Letter Grade: D");
System.out.println(" " + name + " " + " gets 1 stars! *");
examAverage = 0;
examSum = 0;}
else if(examAverage <=59.99 & examAverage >=50){
System.out.println(" Letter Grade: F");
System.out.println(" " + name + " " + " gets 0 stars!");
examAverage = 0;
examSum = 0;}
//still need class statistics as well as help with the invalid exam scores, reenter error.
}
}
}
What jumps out at me is the looping around your score input:
for (int j = 0; j < numberOfExams; j++)
{
scoresEntered = GC.nextDouble();
examSum = (examSum + scoresEntered);
}
//score input and sum of all input scores
do
{
System.out.println("Invalid exam score, reenter: ");
scoresEntered = GC.nextDouble();
} while(scoresEntered < 0);
I've deliberately reformatted what you posted to try to make the problem more obvious. What you appear to be doing is reading in all the scores. Then, regardless of what was entered, you tell the user the exam scores are invalid and ask them to re-enter. Remember, a do...while loop always executes at least once. If the first re-entered score is above zero, that is all you'll read as the while condition is then satisfied.
If you are trying to validate each score before it is added to examSum, you need something more like this:
for (int j = 0; j < numberOfExams; j++)
{
while ((scoresEntered = GC.nextDouble()) < 0)
System.out.println("Invalid exam scores, reenter: ");
examSum = (examSum + scoresEntered);
}

Sum of integers in an array and multiplying integer by 1.5

I am having an issue getting the sum of the integers in my array AND an issue getting the product of an integer * 1.5. My code below could be completely off as I am new to Java and have been at this for hours and hours. The purpose of the program is to enter the number of hours worked, each day, for 5 days. With that, and the pay rate, you're supposed to output the average hours worked, total hours, and total pay. The pay should also include overtime if there is any. Any help would be appreciated.
String name;
String id;
int payRate;
int[] hours = new int[5];
int avgHours;
int totalPay;
int totalHours = 0;
int counter;
int overTime = 0;
//housekeeping
System.out.print("Enter the Employee's name: ");
inputString = input.readLine();
name = inputString;
System.out.print("Enter the Employee's ID: ");
inputString = input.readLine();
id = inputString;
System.out.print("Enter the Employee's pay rate: ");
inputString = input.readLine();
payRate = Integer.parseInt(inputString);
//hoursPay
counter = 0;
for(hours[counter] = 0; counter < 5; counter++)
{
System.out.print("How many hours did the employee work? ");
inputString = input.readLine();
hours[counter] = Integer.parseInt(inputString);
}//endfor
for(totalHours = 0; counter < 5; hours[counter]++);
{
totalHours += hours[counter];
if(totalHours > 40)
{
overTime = payRate + (payRate / 2);
}//endif
}//endwhile
//print
if(counter == 5)
{
System.out.println(name + " " + id + " $" + payRate + "/hour" );
avgHours = totalHours / counter;
totalPay = totalHours * payRate + overTime;
System.out.println...
System.out.println...
System.out.println...
#bp_1,
I re-do all the code again and pasted it below. It WORKS. There was some fundamental error you making while coding. Compare your code with mine and you will see the difference.
String name;
String id;
int payRate;
int[] hours = new int[5];
int avgHours;
int totalPay;
int totalHours = 0;
int counter;
int overTime = 0;
Scanner input = new Scanner(System.in);
//housekeeping
System.out.print("Enter the Employee's name: ");
String inputString = input.nextLine();
name = inputString;
System.out.print("Enter the Employee's ID: ");
inputString = input.nextLine();
id = inputString;
System.out.print("Enter the Employee's pay rate: ");
inputString = input.nextLine();
payRate = Integer.parseInt(inputString);
//hoursPay
counter = 0;
for (hours[counter] = 0; counter < 5; counter++) {
System.out.print("How many hours did the employee work? ");
inputString = input.nextLine();
hours[counter] = Integer.parseInt(inputString);
}//endfor
counter = 0;// reset counter here
for (totalHours = 0; counter < 5; counter++) {
totalHours += hours[counter];
if (totalHours > 40) {
overTime = payRate + (payRate / 2);
}//endif
}//end of for loop
if (counter == 5) {
System.out.println(name + " " + id + " $" + payRate + "/hour");
avgHours = totalHours / counter;
totalPay = totalHours * payRate + overTime;
System.out.println("Average Hours: " + avgHours);
System.out.println("Total pay: " + totalPay);
System.out.println("Total Hours: " + totalHours);
System.out.println("Overtime ($): " + overTime);
}//end of if
In place of
for(totalHours = 0; counter < 5; hours[counter]++);
write
for(counter = 0; counter < 5; counter++)
semicolon removed.
counter incremented instead of hours[counter]

I'm having a issue with my while loop displaying two prints the second time around

This is what I have:
import java.util.*;
import java.text.*;
public class Proj4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String again = "y";
final int MAX_STUDENTS = 100;
final int MIN_EXAM = 0;
final int MAX_EXAM = 50;
final int MIN_FINAL = 0;
final int MAX_FINAL = 100;
String[] names = new String[MAX_STUDENTS];
int[] exams = new int[MAX_STUDENTS * 4];
int student = 1;
DecimalFormat df = new DecimalFormat("#0.0");
do {
System.out.print("Please enter the name of student " + student
+ ": ");
String line;
line = s.nextLine().toUpperCase();
names = line.split(" ");
for (int i = 0; i < 4; i++) {
if (i == 3) {
System.out.print("Please enter score for Final Exam: ");
exams[i] = s.nextInt();
}
else {
System.out.print("Please enter score for Exam " + (i + 1)
+ ": ");
exams[i] = s.nextInt();
if (student == 1) {
if ((exams[0] < MIN_EXAM || exams[0] > MAX_EXAM)
|| (exams[1] < MIN_EXAM || exams[1] > MAX_EXAM)
|| (exams[2] < MIN_EXAM || exams[2] > MAX_EXAM)) {
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
} else if (exams[3] < MIN_FINAL || exams[3] > MAX_FINAL) {
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
} else if (student == 2) {
if ((exams[0] < MIN_EXAM || exams[0] > MAX_EXAM)
|| (exams[1] < MIN_EXAM || exams[1] > MAX_EXAM)
|| (exams[2] < MIN_EXAM || exams[2] > MAX_EXAM)) {
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i + 4] = s.nextInt();
} else if (exams[3] < MIN_FINAL || exams[3] > MAX_FINAL) {
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i + 4] = s.nextInt();
}
}
}
}
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
if (again.equalsIgnoreCase("y"))
student++;
} while (again.equalsIgnoreCase("y"));
System.out.println("***Class Results***");
System.out
.println(names[1]
+ ","
+ names[0]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[0] + exams[1] + exams[2] + exams[3]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
if (student == 2)
;
System.out
.println(names[3]
+ ","
+ names[2]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[4] + exams[5] + exams[6] + exams[7]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
if (student == 3)
;
System.out
.println(names[5]
+ ","
+ names[4]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[8] + exams[9] + exams[10] + exams[11]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
if (student == 4)
;
System.out
.println(names[7]
+ ","
+ names[6]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[12] + exams[13] + exams[14] + exams[15]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
}
}
My program seems to be running exactly the way i want/need it to, the only problem is, when i allow the program to run again it outputs two strings on the same line like this:
Please enter the name of student 2: Please enter score for Exam 1:
I don't know what to do to fix this. is there something in my code that messes up only on the second and probably 3rd and 4th times?
Remove semicolons after ifs
if (student == 3)
; // <- remove it
System.out.println(//...
because now Java understands it as
if (student == 3){}
System.out.println(//...
change
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
to
System.out.print("do you wish to enter another? (y or n) ");
again = s.nextLine();
next will not consume new line mark, so when you use nextLine after next it will consume only this new line mark and go to another instruction. Same rule apply for nextInt.
To store array of student names you could use two dimensional array of Strings
String[][] names = new String[MAX_STUDENTS][];
and store student names in each row based on student number
names[student] = line.split(" ");
To get first name of first student you will have to use this form
names[0][0]; //you probably know that indexes in array starts from zero
To get names of all students you can iterate over each rows and then over columns
for(int stId=0; stId<student; stId++){
for(int nameNumber=0; nameNumber<names[stId].length; nameNumber++){
// print names[stId][nameNumber]`
If you want the strings to print on a new line use println instead of print, or include a linebreak character in your string.

Categories

Resources