String Cannont Be Converted to Char - java

I do not understand why my program will not allow me to convert my variable into char. Any help would be greatly appreciated!!! I am getting a total of 7 errors all either based around my test score grades or around the test score keyboard entry.
public class lab13
{
public static void main(String[] args)
{
// declare variables
int average;
int sum;
int i;
char grade;
int testScore;
//Create a Scanner Object
Scanner keyboard= new Scanner(System.in);
sum = 0;
i = 1;
while (i <= 4)
{
System.out.print("Enter a test score:");
testScore=keyboard.nextLine();
if (testScore < 60)
{
grade =(F);
}
else
{
if (testScore < 70)
{
grade =("D");
}
else
{
if (testScore < 80)
{
grade =("C");
}
else
{
if (testScore < 90)
{
grade =("B");
}
else
{
grade =("A");
}
}
}
}
System.out.print("Test score:"+testScore);
System.out.print("Letter grade:"+grade);
sum = sum + testScore;
i = i + 1;
}
average = sum / 4;
System.out.print("Test score average = " + average);
} // close main
} // close lab13

A char constant can be expressed with '' like
grade = 'F';
and
grade = 'D';
and
grade = 'C';
and
grade = 'B';
and
grade = 'A';

char can only hold a single character, which is defined using single quotes, as in 'C'

Insted of keyboard.nextLine() use keyboard.nextInt() and for character value assignment directly use character with single quota like 'A' instead of ("A")

import java.util.Scanner;
public class lab13
{
public static void main(String[] args)
{
// declare variables
int average;
int sum;
int i;
char grade;
int testScore;
//Create a Scanner Object
Scanner keyboard= new Scanner(System.in);
sum = 0;
i = 1;
while (i <= 4)
{
System.out.print("Enter a test score:");
testScore=keyboard.nextInt();
if (testScore < 60)
{
grade ='F';
}
else
{
if (testScore < 70)
{
grade ='D';
}
else
{
if (testScore < 80)
{
grade ='C';
}
else
{
if (testScore < 90)
{
grade ='B';
}
else
{
grade ='A';
}
}
}
}
System.out.println("Test score:"+testScore);
System.out.println("Letter grade:"+grade);
sum = sum + testScore;
i = i + 1;
}
average = sum / 4;
System.out.print("Test score average = " + average);
} // close main
} // close lab13

Related

java cumulative sum scanner method printf

I am new to java and having issues with my first project. I can't seem to get the variables in the correct scope and am unsure about the scanner methods. If anyone can help me with making it work it would be very helpful, thank you!
Create a new program called LetterGrade. Prompt the user to enter their name.
Create a method called calculateAvg(). Method should use a cumulative sum algorithm to prompt the user to enter 3 scores and calculate the average. Then, return that value to main.
Once the average is returned, Print the student's name and their average using printf() command. Create another method called printLetter(). Method should pass a parameter (average grade).
Use if … else if … else statements to print whether the student has an ‘A’, ‘B’, ‘C’, ‘D’, or ‘F’ average grade.
Grade Scale:
90-100 - A
80-89 - B
70-79 - C
60-69 - D
0-59 - F
Here is what I have so far:
import java.util.*;
public class LetterGrade {
private static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("This program will calculate 3 scores to find the");
System.out.println("average score and letter grade.");
System.out.println();
Scanner console = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = console.nextLine();
final double total = calculateAverage();
System.out.printf("Name: %s/nAverage: %f",name, total);
}
public static double calculateAverage() {
double sum = 0.0;
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + ": ");
double next = console.nextDouble();
sum += next;
double total = (sum / 3);
return total;
}
return total;
}
public static double printLetter(int total) {
double total = console.nextDouble();
if (total < 60) {
System.out.print("You're grade is an F.");
} else if (total < 70) {
System.out.print("You're grade is a D.");
} else if (total < 80) {
System.out.print("You're grade is a C.");
} else if (total < 90) {
System.out.print("You're grade is a B.");
} else if (total <= 100) {
System.out.print("You're grade is an A.");
} else {
System.out.print("You have input an invalid number.");
}
}
}
public static double calculateAverage() {
double sum = 0.0;
for (int i = 0; i < 3; i++) {
System.out.print("Please enter score #" + (i+1) + ": ");
double next = console.nextDouble();
sum += next;
}
double total = (sum / 3);
return total;
}
public class LetterGrade{
private static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("This program will calculate 3 scores to find the");
System.out.println("average score and letter grade.");
System.out.println();
System.out.println("Enter your name: ");
String name = console.nextLine();
final double total = calculateAverage();
System.out.printf("Name: %s/nAverage: %f",name, total);
printLetter(total);
}
public static double calculateAverage() {
double sum = 0.0;
double total = 0.0;
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + ": ");
double next = console.nextDouble();
sum += next;
}
total = (sum / 3);
return total;
}
public static void printLetter(double total){
if (total < 60) {
System.out.print("You're grade is an F.");
}
else if (total < 70){
System.out.print("You're grade is a D.");
}
else if (total < 80){
System.out.print("You're grade is a C.");
}
else if (total < 90){
System.out.print("You're grade is a B.");
}
else if (total <= 100){
System.out.print("You're grade is an A.");
}
else{
System.out.print("You have input an invalid number.");
}
}
}
The immediate issue is that your for statement:
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + "? ");
double next = console.nextDouble();
sum += next;
double total = (sum / 3);
return total;
}
does, not actually "loop" since you return during the very first iteration from it.
You probably want to move the last two lines where you calculate the total outside of it.
Other than that there were a few minor typos:
import java.util.Scanner;
class LetterGrade {
private static final int NUM_SCORES = 3;
public static void main(String[] args) {
System.out.printf("This program will calculate the average from %d scores and give you a letter grade.%n%n",
NUM_SCORES);
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter your name: ");
String name = scanner.nextLine();
double average = calculateAverage(scanner);
System.out.printf("%nReport:%n");
System.out.printf("Name: %s%nAverage: %.2f%n", name, average);
printLetterGrade(average);
}
}
private static double calculateAverage(Scanner scanner) {
double total = 0;
for (int i = 1; i <= NUM_SCORES; i++) {
double next = getDoubleInput(scanner, String.format("Please enter score #%d: ", i), 0, 100);
total += next;
}
return total / NUM_SCORES;
}
private static void printLetterGrade(double average) {
if (average < 60) {
System.out.println("Your grade is a F.");
} else if (average < 70) {
System.out.println("Your grade is a D.");
} else if (average < 80) {
System.out.println("Your grade is a C.");
} else if (average < 90) {
System.out.println("Your grade is a B.");
} else {
System.out.println("Your grade is an A.");
}
}
private static double getDoubleInput(Scanner scanner, String prompt, double minValue, double maxValue) {
System.out.print(prompt);
double validDouble = -1;
while (scanner.hasNext()) {
if (scanner.hasNextDouble()) {
validDouble = scanner.nextDouble();
if (validDouble >= minValue && validDouble <= maxValue) {
break;
} else {
System.out.printf("Error: Please enter a double between %.0f and %.0f inclusive%n", minValue,
maxValue);
System.out.print(prompt);
}
} else {
System.out.printf("Error: Please enter a double between %.0f and %.0f inclusive%n", minValue, maxValue);
System.out.print(prompt);
scanner.next();
}
}
return validDouble;
}
}
Example Usage:
This program will calculate the average from 3 scores and give you a letter grade.
Enter your name: Megan
Please enter score #1: -100
Error: Please enter a double between 0 and 100 inclusive
Please enter score #1: 105
Error: Please enter a double between 0 and 100 inclusive
Please enter score #1: 99
Please enter score #2: 98
Please enter score #3: 100
Report:
Name: Megan
Average: 99.00
Your grade is an A.
Try it out here.
this problem is with your foor loop which with every iteration it reset its value. you can also write much simple code as below:
public static double calculateAverage() {
double sum = 0.0;
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + ": ");
sum += console.nextDouble();
}
return (sum / 3);
}

Java code will not quit when using -1 and numbers do not transfer to alphabetic grades

When using -1 to quit it does not work and also it does not turn the grades from numerical or alphabetic. This is just a simple grade book for a college class.
public class Assignment3
{
public static void main(String[] args)
{`enter code here`
// Defining the constants for min and max range
final int minValue = -1;
final int maxValue = 100;
promptForInt(String message, int minValue,int maxValue);
}
public static void promptForInt(String message,int minValue,int maxValue)
{
System.out.println(message);
convertToLetter(double avg);
// Declaring variables for inital value in the loop
float sum = 0;
int numStudents = 0;
float score = 0;
boolean doneYet = false;
//Sentinel-controlled do-while loop, don't know how many times will run
do
{
System.out.printf("Enter the score for student #%d"
+ "(or -1 to quit): ", numStudents);
Scanner keyboard = new Scanner(System.in);
score = Float.parseFloat(keyboard.nextLine());
if (score != -1)
{
sum += score;
numStudents += 1;
}
}while (score != -1);
double avgScore = (double) sum / numStudents;
System.out.println("The average score is: " + avgScore
+ " which equates to a " + avg);
do
{
// Input Validation
if (score > minValue || score < maxValue)
{
System.err.printf("Invalid value. The acceptable range is"
+ "between %d and %d\n"
+ "Please try again\n",minValue, maxValue);
}
else
{
doneYet = true;
}
}while (doneYet == false);
}
public static void convertToLetter(double avg)
{
// Identifying the ranges for the grade letter
if (avg >= 90)
{
System.out.println("A");
}
else if (avg >= 80)
{
System.out.println("B");
}
else if (avg >= 70)
{
System.out.println("C");
}
else if (avg >= 60)
{
System.out.println("D");
}
else
{
System.out.println("F");
}
}
}
You need to fix you function calls and call the convertToLetter after the user inputs scores.
Try this code:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
public class Assignment3
{
public static void main(String[] args)
{
// Defining the constants for min and max range
final int minValue = -1;
final int maxValue = 100;
promptForInt("", minValue, maxValue);
}
public static void promptForInt(String message,int minValue,int maxValue)
{
System.out.println(message);
//convertToLetter(double avg);
// Declaring variables for inital value in the loop
float sum = 0;
int numStudents = 0;
float score = 0;
boolean doneYet = false;
//Sentinel-controlled do-while loop, don't know how many times will run
do
{
System.out.printf("Enter the score for student #%d"
+ "(or -1 to quit): ", numStudents);
Scanner keyboard = new Scanner(System.in);
score = Float.parseFloat(keyboard.nextLine());
if (score != -1)
{
sum += score;
numStudents += 1;
}
}while (score != -1);
double avgScore = (double) sum / numStudents;
convertToLetter(avgScore);
System.out.println("The average score is: " + avgScore
+ " which equates to a " + avgScore);
do
{
// Input Validation
if (score > minValue || score < maxValue)
{
System.err.printf("Invalid value. The acceptable range is"
+ "between %d and %d\n"
+ "Please try again\n",minValue, maxValue);
}
else
{
doneYet = true;
}
}while (doneYet == false);
}
public static void convertToLetter(double avg)
{
// Identifying the ranges for the grade letter
if (avg >= 90)
{
System.out.println("A");
}
else if (avg >= 80)
{
System.out.println("B");
}
else if (avg >= 70)
{
System.out.println("C");
}
else if (avg >= 60)
{
System.out.println("D");
}
else
{
System.out.println("F");
}
}
}
There was some logic error on your part. I have corrected the code.
This will convert the marks into grades and not run into any infinite loops too. Comment if you have any doubts.
import java.util.Scanner;
public class Assignment3
{
public static void main(String[] args)
{
// Defining the constants for min and max range
final int minValue = -1;
final int maxValue = 100;
promptForInt("", minValue, maxValue);
}
public static void promptForInt(String message,int minValue,int maxValue)
{
System.out.println(message);
//convertToLetter(double avg);
// Declaring variables for inital value in the loop
float sum = 0;
int numStudents = 0;
float score = 0;
boolean doneYet = false;
//Sentinel-controlled do-while loop, don't know how many times will run
do
{
System.out.printf("Enter the score for student #%d"
+ "(or -1 to quit): ", numStudents);
Scanner keyboard = new Scanner(System.in);
score = Float.parseFloat(keyboard.nextLine());
if (score != -1)
{
sum += score;
numStudents += 1;
}
}while (score != -1);
double avgScore = (double) sum / numStudents;
System.out.println("The average score is: " + avgScore
+ " which equates to a " + convertToLetter(avgScore));
do
{
// Input Validation
if (score < minValue || score > maxValue)
{
System.err.printf("Invalid value. The acceptable range is"
+ "between %d and %d\n"
+ "Please try again\n",minValue, maxValue);
}
else
{
doneYet = true;
}
}while (doneYet == false);
}
public static String convertToLetter(double avg)
{
// Identifying the ranges for the grade letter
if (avg >= 90)
{
return "A";
}
else if (avg >= 80)
{
return "B";
}
else if (avg >= 70)
{
return "C";
}
else if (avg >= 60)
{
return "D";
}
else
{
return "F";
}
}
}

Having issues running this code, I'm getting a .class error

I'm having issues getting this to run.
I can't manage to get the return value to work properly. I'm a few weeks into this course and I'm learning a lot but this project has been a little bit of a struggle for me.
I'm collecting data, creating an average and then using that average to output the corresponding letter grade.
Any help would be appreciated.
import java.util.*;
public class LetterGrade
{
public static void main(String args[])
{
calculateAvg();
double avgScore;
printLetter(double);
}
public static void calculateAvg()
{
Scanner console = new Scanner(System.in);
double avgScore;
for (double i = 0; i >0; i++)
{
System.out.println("Enter your full name.");
String name = console.nextLine();
System.out.println("Enter test score 1");
double score1 = console.nextDouble();
System.out.println("Enter test score 2");
double score2 = console.nextDouble();
System.out.println("Enter test score 3");
double score3 = console.nextDouble();
avgScore = (score1 + score2 + score3) / 3;
avgScore = console.nextInt();
System.out.printf( "%s, your average test score is: %.1f",name,avgScore);
return avgScore;
}
}
public static void printLetter(double avgScore)
{
Scanner console = new Scanner(System.in);
char grade;
if (avgScore >= 90)
{
grade = 'A';
}
else if (avgScore >= 80)
{
grade = 'B';
}
else if (avgScore >= 70)
{
grade = 'C';
}
else if (avgScore >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
System.out.println("With that average, your grade is: " + grade);
}
}
There are several errors in your program.
I have corrected the program with comments:
import java.util.*;
public class LetterGrade
{
public static void main(String args[])
{
double avgScore= calculateAvg();
printLetter(avgScore); //pass variable name here not datatype
}
public static double calculateAvg() //must have return type
{
Scanner console = new Scanner(System.in);
double avgScore;
// for (double i = 0; i 0; i++)
//{
System.out.println("Enter your full name.");
String name = console.nextLine();
System.out.println("Enter test score 1");
double score1 = console.nextDouble();
System.out.println("Enter test score 2");
double score2 = console.nextDouble();
System.out.println("Enter test score 3");
double score3 = console.nextDouble();
avgScore = (score1 + score2 + score3) / 3;
// avgScore = console.nextInt();
System.out.printf( "%s, your average test score is: %.1f",name,avgScore);
return avgScore;
// }
}
public static void printLetter(double avgScore)
{
//Scanner console = new Scanner(System.in);
char grade;
if (avgScore >= 90)
{
grade = 'A';
}
else if (avgScore >= 80)
{
grade = 'B';
}
else if (avgScore >= 70)
{
grade = 'C';
}
else if (avgScore >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
System.out.println("With that average, your grade is: " + grade);
}
}
OUTPUT:
Enter your full name.
manisha
Enter test score 1
12
Enter test score 2
14
Enter test score 3
15
manisha, your average test score is: 13.7With that average, your grade is: F
You made many mistakes.
In the main method you should save the calculated average into the variable and pass it to the printLetter method like this
double avgScore = calculateAvg();
printLetter(avgScore);
The calculateAvg method return type should be double so you have to declare it like this
public static double calculateAvg()
Also the for loop inside calculateAvg is wrong and unnecessary so just remove it. And assigning the scanner.nextInt() value to the avgScore will discard the properly calculated value. so the calculateAvg method should be like this
The printLetter method is correct but contains unnecessary lines like
Scanner console = new Scanner(System.in); //Could be removed
The resulting code is
import java.util.*;
public class LetterGrade
{
public static void main(String args[])
{
double avgScore = calculateAvg();
printLetter(avgScore);
}
public static double calculateAvg()
{
Scanner console = new Scanner(System.in);
double avgScore;
System.out.println("Enter your full name.");
String name = console.nextLine();
System.out.println("Enter test score 1");
double score1 = console.nextDouble();
System.out.println("Enter test score 2");
double score2 = console.nextDouble();
System.out.println("Enter test score 3");
double score3 = console.nextDouble();
avgScore = (score1 + score2 + score3) / 3;
System.out.printf( "%s, your average test score is: %.1f\n", name, avgScore);
return avgScore;
}
public static void printLetter(double avgScore)
{
char grade;
if (avgScore >= 90)
{
grade = 'A';
}
else if (avgScore >= 80)
{
grade = 'B';
}
else if (avgScore >= 70)
{
grade = 'C';
}
else if (avgScore >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
System.out.println("With that average, your grade is: " + grade);
}
}
Checkout your main function. You have to assign the variable correctly to the return value of the calculateAvg method. Try this out:
public static void main(String args[]) {
double avgScore = calculateAvg();
printLetter(avgScore);
}
Also notice: double is the type of the variable, not the name. You have to give the name into the printLetter() method.
Another issue I just found is the doubled assigning of the avgScore variable which you have in your calculateAvg() method. Remove this line:
avgScore = console.nextInt();
This would force the user to again type in a value, which gets then assigned to the variable avgScore. This is not necessary.
Try to change the main method to this:
public static void main(String args[]) {
double avgScore = calculateAvg();
printLetter(avgScore);
}
There are some comments that I hope to be useful for you:
1- change the code in the main method to be like that
double avgScore = calculateAvg();
printLetter(avgScore);
2- check the use of the for loop (maybe you need a do while loop)
3- remove the scanner in "printLetter" method
4- also as #NiklasLehnfeld suggest to remove avgscore = console.nextInt();

Output multiple strings from scanner input

The purpose of my program is to accept ints, doubles, and strings from the user and when the program is terminated by inputing the word "quit", the program averages the ints and doubles, and outputs the submitted strings. Here is what i have so far:
import java.util.*;
public class Lab09 {
public static void main(String [] args) {
Scanner console = new Scanner(System.in);
double sumI = 0;
double sumD = 0;
String words = "";
int numInputInt = 0;
int numInputDoub = 0;
do {
System.out.print("Enter something: ");
if (console.hasNextInt()) {
int numI = console.nextInt();
if (numI >= -100 && numI <= 100) {
sumI += numI;
numInputInt++;
}
else {
System.out.println("Integer out of range!(-100 .. 100)");
}
}
else if (console.hasNextDouble()) {
double numD = console.nextDouble();
if (numD >= -10.0 && numD <= 10.0) {
sumD += numD;
numInputDoub++;
}
else {
System.out.println("Double out of range!(-10.0 .. 10.0)");
}
}
else {
words = console.next();
}
} while (!words.equalsIgnoreCase("quit"));
System.out.println("Program terminated...");
double avgInt = sumI / numInputInt;
double avgDoub = sumD / numInputDoub;
if (numInputInt > 0) {
System.out.println("\tAveragae of Integers: " + avgInt);
}
else {
System.out.println("\tNo intergers submitted");
}
if (numInputDoub > 0) {
System.out.println("\tAverage of Doubles: " + avgDoub);
}
else {
System.out.println("\tNo doubles submitted");
}
System.out.println(words);
}
}
The ints and doubles get processed well, but im stuck in the strings. Any ideas on how to go about doing so?
Thanks in advance!
While you could build a List<String> of words it looks like you just want to concatenate each new word to your String words like,
if (words.length() > 0) words += " "; // <-- add a space.
words += console.next(); // <-- += not =
Then change your loop test to something like,
while (!words.trim().toLowerCase().endsWith("quit"));
And it should work something like you would expect.
You could use
String input = "";
do {
//...
}
else {
input = console.next();
words += input + " ";
}
console.nextLine(); // Read the carriage return
} while (!input.equalsIgnoreCase("quit"));
//...
System.out.println(words.trim());
to concatenate the text, but this is rather inefficient when done within a loop.
A better solution would be to use a StringBuilder...
StringBuilder work = new StringBuilder(128);
String input = "";
do {
//...
}
else {
input = console.next();
words.append(" ").append(input);
}
console.nextLine(); // Read the carriage return
} while (!input.equalsIgnoreCase("quit"));
//...
System.out.println(words);
I just read your comment that you can't use any other class, try this:
import java.util.*;
public class Lab09 {
public static void main(String [] args) {
Scanner console = new Scanner(System.in);
double sumI = 0;
double sumD = 0;
String words = "";
int numInputInt = 0;
int numInputDoub = 0;
do {
System.out.print("Enter something: ");
if (console.hasNextInt()) {
int numI = console.nextInt();
if (numI >= -100 && numI <= 100) {
sumI += numI;
numInputInt++;
}
else {
System.out.println("Integer out of range!(-100 .. 100)");
}
}
else if (console.hasNextDouble()) {
double numD = console.nextDouble();
if (numD >= -10.0 && numD <= 10.0) {
sumD += numD;
numInputDoub++;
}
else {
System.out.println("Double out of range!(-10.0 .. 10.0)");
}
}
else {
words = words.concat(" ").concat(console.next());
}
} while (!words.contains("quit"));
System.out.println("Program terminated...");
double avgInt = sumI / numInputInt;
double avgDoub = sumD / numInputDoub;
if (numInputInt > 0) {
System.out.println("\tAveragae of Integers: " + avgInt);
}
else {
System.out.println("\tNo intergers submitted");
}
if (numInputDoub > 0) {
System.out.println("\tAverage of Doubles: " + avgDoub);
}
else {
System.out.println("\tNo doubles submitted");
}
System.out.println(words);
}
}

How can I achieve this specific output using for loops to simplify storing data in an array?

public class IndividualProject2 {
public static void main(String[] args) {
int i;
for( i = 0; i < 7; i++){
Scanner gradeInput = new Scanner(System.in);
System.out.println("Enter midterm 1 score: ");
int num1 = gradeInput.nextInt();
System.out.println("Enter midterm 2 score: ");
int num2 = gradeInput.nextInt();
System.out.println("Enter final score: ");
int num3 = gradeInput.nextInt();
}
}
public static char function (int grade){
String[] name = new String[7];
char[] finalGrade = new char[7];
char letter;
if (grade >= 90){
letter = 'A';
System.out.println(letter);
}
else if (grade >= 80 && grade < 90){
letter = 'B';
System.out.println(letter);
}
else if(grade >= 70 && grade < 80){
letter = 'C';
System.out.println(letter);
}
else{
letter = 'F';
System.out.println(letter);
}
for(int counter=0; counter < finalGrade.length; counter++ ){
finalGrade[counter] = letter;
}
return letter;
}
public static int function (int midtermOne, int midtermTwo) {
int result;
int[] midterm = new int[7];
if ( midtermOne > midtermTwo)
{
result = midtermOne;
}
else{
result = midtermTwo;
}
for(int counter=0; counter < midterm.length; counter++ ){
midterm[counter] = result;
}
return result;
}
public static double function (int num1, int num2, int num3){
double result;
double[] average = new double[7];
result = (num1 + num2 + num3)/3.0;
for(int counter=0; counter < average.length; counter++ ){
average[counter] = result;
}
return result;
}
}
The output should look like this http://i.imgur.com/GHo2YS6.png
I am having difficulty creating a loop that match this specific output.How do I take the inputs in the the loop while using the three function methods to store the values in the arrays. I feel very overwhelmed on how to do this.
Move Scanner gradeInput = new Scanner(System.in); before the for loop in your main. In this way you can avoid doing the same thing 7 times which is not useful in anyway.
Declare four arrays - name, midTerm1, midTerm2 and avg for holding 4 values for each student. You can define them at the class level or inside main.
Fill these four arrays for each student something like
for(int i = 0; i < 7; i++){
System.out.println("Student number " + (i + 1) );
System.out.print("Enter student's name: ");
name[i] = gradeInput.next();
System.out.print("Enter midterm 1 score: ");
midTerm1[i] = gradeInput.nextInt();
System.out.print("Enter midterm 2 score: ");
midTerm2[i] = gradeInput.nextInt();
System.out.print("Enter final score: ");
avg[i] = gradeInput.nextInt();
}
Once, this is done do as below
System.out.printf("%-8s %6s %8s %8s\n", "name", "final", "midterm", "average");
for(int i = 0; i < 7; i++) {
System.out.printf("%-8s %6c %8d %2.6f\n", name[i] , function(avg[i]), function(md1[i], md2[i]), function(md1[i], md2[i], avg[i]));
}
Remove all the print statements from function (int grade).
One side note It is also possible not to hard code the value for number of students - in your case 7 and pass it from command line. In this case, you can use that number to initialize all the four arrays sizes and modify the for loops appropriately.
For example - inside main, you can do something like
public static void main(String[] args) {
int noOfStudents;
if (args.length == 1) {
noOfStudents = Integer.parseInt(args[0]);
name = new String[noOfStudents];
midTerm1 = new int[noOfStudents];
midTerm2 = new int[noOfStudents];
avg = new int[noOfStudents];
} else {
System.out.println("please provide a value for no of students data that need to be processed");
return;
}
}

Categories