How to add the user input in the loop? - java

I'm using array and loop, at the first input the user must enter the number of subjects and use the number to be the size of the array. Then on the loop, the program will accept "grades" on each subject.
I need to add those grades.
Please help.
import java.util.Scanner;
public class CaseStudy1 {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int numsub, grade, sum, ave;
System.out.print("\nEnter number of subjects: ");
numsub = inp.nextInt();
int num[]=new int [numsub];
int y=0;
for(int x=0;x<numsub;x++) {
y=y+1;
System.out.print("\nEnter Grade in Subject [" + y + "] : ");
grade = inp.nextInt();
num[x]=grade;
}
}
}

you alreday got a variable for sum, just add this
sum+=grade;
into your for-loop after
num[x] = grade;

Include another variable called gradsum initialize with 0. Then add grade to gradsum while getting the grade values.
int gradsum = 0;
int y=0;
for(int x=0;x<numsub;x++) {
y=y+1;
System.out.print("\nEnter Grade in Subject [" + y + "] : ");
grade = inp.nextInt();
num[x]=grade;
gradsum +=grade;
}
System.out.print(" Total of the Grade : "+gradsum );
System.out.print(" Average : " + gradsum / numsub );

Related

Java grades exercise

I'm Adrian and i'm kinda new to programming, would like to learn more and improve. I was asked to do a grade average exercise and i did this , but i'm stuck at making the code so if you type a number instead of a name the code will return from the last mistake the writer did , like it asks for a name and you put "5". In my code gives an error and have to re-run it. Any tips?
import java.util.*;
import java.math.*;
import java.io.*;
class Grades {
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
At the heart of any solution for this, it requires a loop, and a condition for resetting.
String result = null;
while (result == null) {
//OUT: Prompt for input
String input = keyboard.next();
if (/* input is valid */) {
result = input; //the loop can now end
} else {
//OUT: state the input was invalid somehow
}
//Since this is a loop, it repeats back at the start of the while
}
//When we reach here, result will be a non-null, valid value
I've left determining whether a given input is valid up to your discretions. That said, you may consider learning about methods next, as you can abstract this prompting/verification into a much simpler line of code in doing so (see: the DRY principle)
There are several ways to do it.
But the best way is to use regex to validate the user input.
Have a look at the below code, you can add other validations as well using regex.
import java.util.Scanner;
class Grades {
public static boolean isAlphabetOnly(String str)
{
return (str.matches("^[a-zA-Z]*$"));
}
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
if(!isAlphabetOnly(name)){
System.out.println("Please enter alfabets only");
return;
}
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}

Need assistance nest for loop to add all rrows and colums in table in java

The question is: Reads a set of numbers given in a table, and displays the total. (add rows and columns)
Here is what I have so far. I need guidance on how to get the right output. Thanks in advance.
*Do not want to use array.
import java.util.Scanner;
public class tableintegers {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Give the number of rows and number of columns: ");
int rows=input.nextInt();
int cols=input.nextInt();
int total=0, sum=0, numbers=0;
for(int i=0;i<rows; i++) {
if (rows>i) {
System.out.print("Enter row " +(i+1)+ ":");
numbers=input.nextInt();
input.nextInt();
}
sum+=numbers;
total=sum+numbers;
}
System.out.println("The grand total is: " +total);
}
}
The below program will ask the user to first insert the number of rows and columns separately. Next, a nested for loop is used to ask the user to insert the values for each column in each row.
The first For Loop iterates through the number of rows. For each iteration, the second For Loop will iterate through the number of columns entered. Thus asking the user to enter a value for each column.
A total of the values entered for each row will be calculated by sumOfRow. Finally, these values will be added together and a final total will be displayed.
Hope this helps :)
import java.util.Scanner;
public class tableintegers {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Enter the number of rows:");
int rows=input.nextInt();
System.out.print("Enter the number of columns:");
int cols=input.nextInt();
int total=0, sumOfRow=0, numbers=0;
for(int i=0; i<rows; i++) {
sumOfRow = 0;
System.out.println("\nRow No. " + (i + 1) );
for(int j=0; j<cols; j++) {
System.out.print("Enter value for Column " + (j+1) + ": ");
numbers = input.nextInt();
sumOfRow += numbers;
}
System.out.println("Sum of Row No. " + (i+1) + " Values: " + sumOfRow);
total += sumOfRow;
}
System.out.println("\nThe grand total is: " +total);
}
}
import java.util.Scanner;
public class tableintegers {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Give the number of rows and number of columns: ");
int rows=input.nextInt();
int cols=input.nextInt();
int sumRow=0;
for(int i=1;i<=rows; i++) {
System.out.print("Enter row " +i+ ":");
for(int j=1;j<=cols; j++) {
int numbers=input.nextInt();
sumRow+=numbers;
}
}
System.out.println("The grand total is: " +sumRow);
}
}

Printing Appropriate Number Through Array

I'm trying to print out a baseball players on base percentage. So far, the code is going great. The only issue is that when I'm printing out the OBP for each year, I can't seem to match up the correct year that correlates to the year the user input. Each time it loops in the method printOnBasePercentage() it increments the year by one. Is there a way I can resolve this issue? Thanks.
I've tried adding +startYear++ and that didn't seem to work. It got me closer.
public static void main(String[] args) {
int numYears;
double [] years;
String name;
int startYear;
double oBP;
int hits, walks, sacFlies, hitsByPitch, atBats;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter name of baseball player: ");
name = keyboard.nextLine();
System.out.print("Enter the number of years " + name +" has been playing: ");
numYears = keyboard.nextInt();
years = new double[numYears];
System.out.print("Enter " +name +" first year on the team: ");
startYear = keyboard.nextInt();
for (int index = 0; index < years.length; index++) {
System.out.print("For Year: "+ startYear++);
System.out.print("\nEnter how many hits the player has: ");
hits = keyboard.nextInt();
System.out.print("Enter the number of walks the player has: ");
walks = keyboard.nextInt();
System.out.print("Enter the number of sacrifice flies the player has: ");
sacFlies = keyboard.nextInt();
System.out.print("Enter the number of hits by pitch the player has: ");
hitsByPitch = keyboard.nextInt();
System.out.print("Enter the amount of at bats the player has: ");
atBats = keyboard.nextInt();
years[index] = ((hits + walks + hitsByPitch) / atBats+ walks+ hitsByPitch +sacFlies);
}
printOnBasePercentage(name, startYear, years);
}
public static void printOnBasePercentage(String name, int startYear, double []years){
for (int index = 0; index < years.length; index++){
System.out.println("\n" + name + "'s On Base Percentage");
System.out.printf("For Year: " +startYear + " " + "%.3f", years[index]);
}
}
The problem is you use one changeable variable in the both loops. In the main method you increment startYear variable and after that you pass this changed variable in the printonBasePercentage method. Try to replace this line:
System.out.print("For Year: "+ startYear++);
by:
System.out.print("For Year: "+ startYear + index);

How to use Scanner get store input in one integer

How can I make it so the there will be the same number of questions as the user inputs the number of jobs. For example, lets say you had worked in 5 jobs, I want the program to ask the user to ask,
Your salary for job 1
Job 2
Job 3
Job 4
Job 5, and so on. My code right now is.
import java.util.Scanner;
public class Personal_Info {
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int Salary1;
int Salary2;
int Salary3;
int TotalJobs;
int Average;
String Name;
int Largest;
int Smallest;
int Sum;
System.out.print("What is your first name?: ");
Name = Scanner.nextLine();
System.out.print("How many jobs have you had?: ");
TotalJobs = Scanner.nextInt();
System.out.print("Enter income from job #1: ");
Salary1 = Scanner.nextInt();
System.out.print("Enter income from job #3: ");
Salary2 = Scanner.nextInt();
System.out.print("Enter income from job #3: ");
Salary3 = Scanner.nextInt();
Sum = Salary1 + Salary2 + Salary3;
Average = Sum / TotalJobs;
Largest = Salary1;
Smallest = Salary1;
if(Salary2 > Largest)
Largest = Salary2;
if(Salary3 > Largest)
Largest = Salary3;
if(Salary2 < Smallest)
Smallest = Salary2;
if (Salary3 < Smallest)
Smallest = Salary3;
System.out.println("Hello " + Name + "You've had " + TotalJobs + " jobs. " + "The highest paying job paid is " + Largest + ". The lowest paying job paid is "+ Smallest + ". The average is " + Average + ".");
but it wouldn't work cause it'll only ask the user three times, job 1, 2, and 3.
If I try,
for (int x = 0; x<TotalJobs; x++){
System.out.print("How many jobs have you had?: ");
number = Scanner.nextInt();
I don't know how to get the highest/smallest/average from that stored value which would be 'number'.
Hope this will help You
class SalaryCalculate{
public static void main(String args[]){
int totalJobs,jobcounter,maxSalary,minSalary,averageSalary=0;;
int[] jobsincome;
String name;
Scanner sc= new Scanner(System.in);
System.out.println("Enter your name");
name=sc.nextLine();
System.out.println("How many jobs you had");
totalJobs= sc.nextInt();
jobsincome= new int[totalJobs];
for(int i=0;i<totalJobs;i++){
jobcounter=i+1;
System.out.println("Enter the income for your job "+jobcounter);
jobsincome[i]=sc.nextInt();
averageSalary=averageSalary+jobsincome[i];
}
jobsincome=average(jobsincome);
maxSalary=jobsincome[totalJobs-1];
minSalary=jobsincome[0];
averageSalary=averageSalary/totalJobs;
System.out.println("Hi "+name+" your min salary is "+minSalary+" max salary is "+maxSalary+" average salary is "+averageSalary);
}
public static int[] average(int jobsincome[]){
int length=jobsincome.length;
for(int i=0;i<length;i++){
for(int j=i+1;j<length;j++){
if(jobsincome[i]>jobsincome[j]){
int temp=jobsincome[j];
jobsincome[j]=jobsincome[i];
jobsincome[i]=temp;
}
}
}
return jobsincome;
}
}
Use an array.
Also only capitalize classes, not variables
System.out.print("How many jobs have you had?: ");
int totalJobs = scanner.nextInt();
int[] salaries = new int[totalJobs];
// Loop here
// System.out.print("Enter income from job #"+x);
// salaries[x] = scanner.nextInt();
With this list, you can get the length directly and use separate loops for the sum, min, max. Or streams
With the sum and length, find an average
use an integer arraylist to keep salaries and loop through inputs
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
ArrayList<Integer> sallaries = new ArrayList<>();
int TotalJobs;
double average;
String name;
int largest;
int smallest;
System.out.print("What is your first name?: ");
name = input.nextLine();
System.out.print("How many jobs have you had?: ");
TotalJobs = input.nextInt();
for (int i= 0; i<TotalJobs ; i++){
System.out.print("Enter income from job #"+(i+1)+" : ");
sallaries.add(input.nextInt());
}
average = sallaries.stream().mapToInt(Integer::intValue).average().orElse(-1);
largest = Collections.max(sallaries);
smallest = Collections.min(sallaries);
System.out.println("Hello " + name + "You've had " + TotalJobs + " jobs. " + "The highest paying job paid is " + largest + ". The lowest paying job paid is "+ smallest + ". The average is " + average + ".");
}

How do you incorperate an AVERAGE and LETTERGRADE in a java program which has 2D Array

I have written a program with minimal errors but do not know where I should place the Average or Letter grade function:
package org.education.tutorial;
import java.util.Scanner;
public class GradingScale
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the number of students attending your current session :");
int numberOfStudents = keyboard.nextInt();
System.out.println();
System.out.print("Also, please enter the amount of exams taken during the duration of the course : ");
int examScores = keyboard.nextInt();
AssignValueToArray(numberOfStudents, examScores);
keyboard.close();
}
public static void AssignValueToArray(int amountOfStudents, int amountOfExams)
{
int[][] overallScore = new int[amountOfStudents][amountOfExams];
Scanner keyboardArray = new Scanner(System.in);
int numberValue = 1;
for (int index = 0; index < amountOfStudents; index++)
{
System.out.println ("\n" + "Please submit Student #" + numberValue + " 's score :" );
for(int indexOfHomeWork=0; indexOfHomeWork < amountOfExams; indexOfHomeWork++)
{
overallScore[index][indexOfHomeWork] = keyboardArray.nextInt();
}
numberValue++;
}
DisplayvalueInArray(overallScore);
keyboardArray.close();
}
public static void DisplayvalueInArray(int[][] overallScoreArray)
{
System.out.println ("The students' scores are posted below : " + "\n");
int studentCount = 1;
for (int index = 0; index < overallScoreArray.length; index++)
{
System.out.print("Grades for student " + studentCount +": ");
for (int indexOfHomeWork = 0; indexOfHomeWork < overallScoreArray[index].length;
indexOfHomeWork++)
{
System.out.print(overallScoreArray[index][indexOfHomeWork]+"\t");
}
System.out.println();
studentCount++;
}
}
I would highly recommend learning how to use variable scope and possibly objects before doing something such as this.
You never declare any variables in the class's scope.
Most of your functions don't affect anything outside their own scope, and therefore shouldn't be functions. Instead use comments to encapsulate.
Many of your variables are named poorly, instead of keyboardArray, which is not an array at all, do something like kb, or keyboardScanner
For computing average and lettergrades, think 'what am i averaging' and use that as your parameter, with the average as your return type, so something like static int average(int[] scores)

Categories

Resources