Getting information out of a whole array to a variable? - java

I'm new to Stack Overflow So please go easy on me :D
I'm having some problems solving this problem, because of my data is stored inside of an array I need a way to be able to put the same data inside of a variable because I need to do some operation to get the average score, the first thing that I try to do was making a variable and giving it the array as the value but it was not allowing me to do anything, I've spent quite a lot of times on it and I still cannot like understand how to fix it, so if you could please help me out with this problem.
So to summarise what I'm trying to do is get the number of students that I have stored in i and the percentage Of the students that should be in array[i], this is to obtain the average score for the number of students, so the Sum Of Percentages / number of Students * 100 = Average Percentage of Score.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
System.out.println("Hello MJ ");
Scanner sc= new Scanner(System.in);
System.out.println("Insert number of students: ");
String student = sc.nextLine();
int studenti = Integer.parseInt(student);
int[] array = new int[studenti];
for (int i = 0; i<studenti;i++)
{
System.out.println("Insert a score in procentage: ");
String score = sc.nextLine();
array[i]= Integer.parseInt(score);
}
System.out.println("\nProcentages are: ");
for (int i=0; i<studenti;i++)
{
System.out.println((array[i])+"%");
}
System.out.println("\nThe Average Score is: " + average + "%");
int average = (persentegesOfStudents)/students;6
}

Note that in order to get the average, you need to sum the scores, and then to divide by the number of students. Your second for loop looks like the right place to handle the sum, and in addition you need to declare the average variable before printing it. Here is some suggestion (see my comments):
public static void main(String args[]) {
System.out.println("Hello MJ ");
Scanner sc = new Scanner(System.in);
System.out.println("Insert number of students: ");
String student = sc.nextLine();
int studenti = Integer.parseInt(student);
int[] array = new int[studenti];
for (int i = 0; i < studenti; i++) {
System.out.println("Insert a score in procentage: ");
String score = sc.nextLine();
array[i] = Integer.parseInt(score);
}
System.out.println("\nProcentages are: ");
int sum = 0; // Added a variable for sum
for (int i = 0; i < studenti; i++) {
System.out.println((array[i]) + "%");
sum += array[i]; // maintaining sum
}
int average = sum / array.length; // calculating the average
System.out.println("\nThe Average Score is: " + average + "%");
}
Note that you can make the average more accurate if you work with it as float and not integer.

Use a stream to process data. Convert your array to intSream
IntStream stream = Arrays.stream(arr);
intSream have many funtions like average, min , max, sum etc.

Related

Using loops for both input and output

import java.util.Scanner;
public class basic{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter raduis : ");
for(int i=0;i<=2;i++)
float num = sc.nextFloat();
for(int i=0;i<=2;i++){
System.out.println(num[i]);
}
}
}
How can we take input from the user using loops and add all the user input and show's the output, for example, I have to take 3 user inputs (54, 6, 432), add all of them, and then show the output(432). I have tried but then I stuck.
You can use a variable (sum). You first initialize it to 0. And in the loop immediately after you get the input from the user for each value, add the input to this variable. Such a variable is sometimes referred to as an accumulator and the operation can be termed as an accumulation or reduce. If you want to store the values to display them later, you can use an array to store the values while they are being input and being summed. Also, in Java, the usual naming convention for class names is PascalCase, so consider naming it Basic:
import java.util.Scanner;
public class Basic {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
float sum = 0;
float[] array;
System.out.println("Enter the number of values: ");
int count = sc.nextInt();
array = new float[count];
for(int i=0;i< count;i++) {
System.out.println("Enter value " + i+1 + ": ");
float num = sc.nextFloat();
array[i] = num;
sum += num;
}
System.out.print("You have entered: ");
for(int i = 0; i < count;i++) {
System.out.print(array[i] + " ");
}
System.out.println("The sum of these numbers is " + sum);
}
}
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter raduis : ");
int num[],sum=0;
num = new int[3];
for(int i=0;i<=2;i++){
num[i] = sc.nextInt();
sum=sum+num[i];
}
System.out.println(sum);
}
}
You can do this in too many ways, it depends on the case, etc.
Keep it simple solution
A simple solution could be creating a new variable sum to make the sum of everything, and just iterate the loop once:
System.out.println("Enter raduis : ");
float sum = 0; // create a new variable to make the sum later
for(int i=0; i<=2; i++) {
float num = sc.nextFloat();
sum += num; // sum the current 'sum' value and 'num'
}
System.out.println("Result is: " + sum); // show the result
Keep it clean solution
If for some reason you are required to execute this logic into separated parts, you can use an array of values to collect the raduis and then, make the sum operation over the values of that array.
I suggest you use a method for that cause it will help you to uncouple the logic of asking numbers and make the sum operation very easy.
float[] askRaduis(int size) {
System.out.println("Enter raduis :");
float[] result = new float[size]; // create an array of floats
for(int i=0; i<=size; i++) { // Iterate until reaching 'size'
float num = sc.nextFloat();
result[i] = num; // save the iteration number at the array
}
return result;
}
Then, with this method, you can ask the numbers and later process the sum operation. Something like this:
float[] raduis = askRaduis(3); // Specify the amount of 'raduis' you want to ask.
float sum = 0; // create a new variable to make the sum later
for(float number : raduis ) { // this is a foreach loop it will iterate values of an array
sum += num; // sum the current 'sum' value and 'num'
}
System.out.println("Result is: " + sum); // show the result

How do you use a method to calculate 1 array parameter of grades and returns the total of the array?

My schoolwork is asking me to write a Java program. I'm not getting something quite right.
Basically I have to create a Java method that gets a user to enter x amount of grades (users choice), store the grades in an array and then add the grades in the array up to be called in the main method.
Here's my code:
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int [] storeGrades = new int[numberOfGrades];
}
public static int getTotalScore(int numberOfGrades[]) {
Scanner keyboard = new Scanner(System.in);
int getTotalScore;
int []storeGrades;
for (int i = 0; i < getTotalScore; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
int userGradeNumbers = keyboard.nextInt();
storeGrades[i] = userGradeNumbers;
sum += userGradeNumbers;
}
}
}
I'm getting an error at "sum" that it hasn't been resolved to a variable? It won't let me initialize sum within the for loop, nor the getTotalScore method. Why not?
First, get the grades. Then call the method to get the sum. Declare the sum and initialize it to 0 before your loop. Return it after. Like,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int[] storeGrades = new int[numberOfGrades];
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
storeGrades[i] = keyboard.nextInt();
}
System.out.println(getTotalScore(storeGrades));
}
public static int getTotalScore(int[] storeGrades) {
int sum = 0;
for (int i = 0; i < storeGrades.length; i++) {
sum += storeGrades[i];
}
return sum;
}
Your code has the right intent about it, but some of the ordering of things is a little off and there are syntactical issues at the moment.
I would advocate splitting up your code into two methods (unless you're specifically prohibited from doing so based on the assignment). One method to get the grades from the user, and another to sum the grades. The reason for this, is that you end up trying to both store and sum the grades at the same time (which is technically more efficient), but that doesn't teach you how to calculate a running total by iterating over an array (which is likely the point of the lesson).
One other thing that I would call out (which may be beyond where you are in the course right now), is that when you're using a Scanner, you need to validate that the user has typed what you think they've typed. It's entirely plausible that you want the user to type a number, and they type "Avocado." Because Java is strongly typed, this will cause your program to throw an exception and crash. I've added in some basic input validations as an example of how you can do this; the general idea is:
1) Check that the Scanner has an int
2) If it doesn't have an int, ask the user to try again
3) Else, it has an int and you're good to proceed. Store the value.
One last thing about Scanners. Remember to close them! If you don't, you can end up with a memory leak as the Scanner continues to run.
Below is how I would have revised your code to do what you want. Shoot me a comment if something doesn't make sense, and I'll explain further. I left comments inline, as I figured that was easier to digest!
package executor;
import java.util.Scanner;
public class StudentGrades {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Initial prompt to the user
System.out.println("Hello Drews, how many total grades do you want to process?");
// This loop validates that the user has actually entered an integer, and prevents
// an InputMismatchException from being thrown and blowing up the program.
int numberOfGrades = 0;
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
// If the program makes it through the while loop, we know that the Scanner has an int, and can assign it.
numberOfGrades = keyboard.nextInt();
// Creating the array using the method getGrades().
int[] storedGrades = getGrades(numberOfGrades, keyboard);
// Calculating the total score using the method getTotalScore().
int totalScore = getTotalScore(storedGrades);
System.out.println("Total Score is: " + totalScore);
keyboard.close();
}
/**
* Asks the user to provide a number of grades they wish to sum.
* #param numberOfGrades the total number of grades that will be requested from the user.
* #param keyboard the scanner that the user will use to provide the grades.
* #return the summed grades as an int.
*/
public static int[] getGrades(int numberOfGrades, Scanner keyboard) {
int[] grades = new int[numberOfGrades];
// Asking the user i number of times, to enter a grade to store.
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ":");
// More input validation to ensure the user can't store "Cat."
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
int userEnteredGrade = keyboard.nextInt();
// Storing the user's entry.
grades[i] = userEnteredGrade;
}
return grades;
}
/**
* Sums all of the grades stored within an integer array.
* #param storedGrades the grades to be summed.
* #return the total value of summed grades.
*/
public static int getTotalScore(int[] storedGrades) {
int totalScore = 0;
for (int i = 0; i < storedGrades.length; i++) {
totalScore += storedGrades[i];
}
return totalScore;
}
}

Can I do a for loop after two consecutive if statements? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
I am working on a program that has to check for certain conditions (and give out an error message if they are not executed) before executing two for loops (one for the sum of grades entered and one for highest and lowest grades)and I'm not sure how to sequence them.
Also my code is getting me this error -->Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 and I'm not sure what to do to fix the error
If anyone can help me with the skeletons of the correct sequence I would truly appreciate it!
Here is my code (I know it looks crazy, sorry I'm learning!):
import java.util.Scanner;
public class Homework {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int numberOfMarks, average, sum, total, mark;
numberOfMarks = 0;
int [] marks = new int[numberOfMarks];
int smallest, largest;
//System.out.println("Enter number of marks: ");
numberOfMarks = input.nextInt();
if(numberOfMarks<0) {
System.out.println("Number of marks must be greater than 0!!");
}
//System.out.println("Enter "+numberOfMarks+"marks: ");
mark = input.nextInt();
if(mark<0) {
System.out.println("Negative marks not allowed!!!");
} else if(mark>100) {
System.out.println("Marks above 100% not allowed!!!");
}
sum = 0;
for(int i = 0; i < marks.length; i++) {
sum += marks[i];
}
smallest=marks[0];
largest=marks[0];
for(int i=1;i<marks.length;i++) {
if(marks[i]>largest) {
largest=marks[i];
} else if(marks[i]<smallest) {
smallest=marks[i];
}
average = sum/numberOfMarks;
System.out.println("Highest Mark = "+largest);
System.out.println("Lowest Mark = "+smallest);
System.out.println("Average = "+average);
}
}
}
You can try this:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int numberOfSubjects, sum;
numberOfSubjects = 0;
System.out.print("Enter the total number of subjects: ");
numberOfSubjects = in.nextInt();
if(numberOfSubjects < 0){
System.out.println("Number of marks must be greater than 0!!");
}
else {
int []marks = new int[numberOfSubjects];
sum = 0;
System.out.print("Enter the marks: ");
// add condition inside for loop for marks not less than 1 or greater than 100
for(int i=0; i<marks.length; i++) {
marks[i] = in.nextInt();
}
// calculate total
for(int i = 0; i < marks.length; i++){
sum += marks[i];
}
// sort marks
Arrays.sort(marks);
System.out.println("Total: " + sum);
System.out.println("Average: " + sum/numberOfSubjects);
System.out.println("Minimum: " + marks[0]);
System.out.println("Maximum: " + marks[marks.length-1]);
}
}
}
Code flow should look like this. Even you can add condition of marks(not less than 1 or greater than 100) while reading marks.
Problem is in the logic, see comments bellow
import java.util.Scanner;
public class Homework {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfMarks, average, sum, total, mark;
numberOfMarks = 0;
/*there you are creating empty array
you told marks should have length of value numberOfMarks, but
numberOfMarks is equal to zero at this time
*/
int[] marks = new int[numberOfMarks];
int smallest, largest;
//System.out.println("Enter number of marks: ");
numberOfMarks = input.nextInt();
/*
not interesting conditions checking...
*/
for (int i = 0; i < marks.length; i++) {
/*
There you are trying to access 1st element of marks
- indexing from zero, as usual
But there is no first element, array has zero length, zero elements
Ok, you told array should have length of numberOfMarks, but it was
when value was zero, so if you will change numberOfMarks later, it
has no impact on the length of array
*/
sum += marks[i];
}
/*
stats computing, not important
*/
}
}
So, once you got user input for number of marks, then you can "recreate" - realloc / redefine the array, as before
marks = new int[numberOfMarks];
In your case bellow
//System.out.println("Enter number of marks: ");
numberOfMarks = input.nextInt();
Using variable in length of array does not means it will be bounded, so if variable in array length (in this case numberOfMarks) will change later after usage, then length of array will be still the same

I need to find specific variables that the user has inputted however I don't comprehend how

Scanner scan = new Scanner(System.in);
int amount = 0;
int input = 0;
int[] numbers = new int [amount];
for(int i = 0; i<1; i++ )
{
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
if (amount==amount)
{
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
input = scan.nextInt();
input = input + input;
}
}
}
double average = input/amount;
System.out.println(average);
}
}
I want to every number the user inputs, but how would I go about that?
For example, if the input is a 2 then a 3 then a 4 how do i take those and print them out in the next line while stating their averages.
There are a few problems with the code as you have written it.
if (amount == amount) is the same as saying if (true), so you might as well remove it.
You are doubling your input for no particular reason.
You are trying to build an array to store the amount before knowing how big it needs to be.
Your outer for loop is looping exactly once, so you do not need that either.
Here is a working and simplified revision of your code.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
// Now that we know the amount, we can build an array to hold that
// amount.
int[] numbers = new int [amount];
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
numbers[x] = scan.nextInt();
total += numbers[x];
}
double average = total * 1.0 /amount; // Prevent integer division
System.out.println(average);
}
}
Update: The code above will compute the average of the numbers that the user has provide.
The OP seems to hint that he wants the proportion of each input instead. Here is a modification using HashMap to accomplish that.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
// Create a Map to get the count of each input.
Map<Integer,Integer> counts = new TreeMap<Integer,Integer>();
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
int input = scan.nextInt();
if (counts.containsKey(input)) counts.put(input, counts.get(input) + 1);
else counts.put(input,1);
}
// Print out the percentage of each input
for (Integer key : counts.keySet())
System.out.printf("%d\t%.2f%%\n", key, counts.get(key) * 100.0 / amount);
}
}
You can adapt your code to not even have to ask how many numbers you plan to enter.
import java.util.Scanner;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
System.out.println("Please enter some numbers, n to terminate: ");
while(kb.hasNextInt())
values.add(kb.nextInt());
System.out.println("\nYou entered the following values:");
double runningSum = 0;
for(int elem : values) {
runningSum += elem;
System.out.print(elem + " ");
}
System.out.println("\nThe average of the values entered is: "
+ runningSum / values.size());
}
}

Having Trouble Making a for loop with a do-while loop

just started with Java and my assignment this week is to write a program that asks the user how many test scores they want to enter, which the user fills in and then the program asks them to enter test scores up until that counter is met, and display the average amongst the scores.I feel like i have the brunt of it but just need some more help its kind of in a dead loop and I'm stuck. I've moved my for loop around and it either puts my display text into a neverending loop or the program stalls after asking for number of scores to be entered (this is where it is now). Any help is appreciated:
import java.util.Scanner;
public class TestScoreApp
{
public static void main(String[] args)
{
// display operational messages
System.out.println("Please enter test scores that range from 0 to 100.");
System.out.println(); // print a blank line
// initialize variables and create a Scanner object
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int count = 0;
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
while (testScore <= 100)
{
// get the input from the user
System.out.print("Enter the number of scores to be entered: ");
for (scoreCount = 0; count <=100; scoreCount++)
scoreCount = sc.nextInt();
// get the input from the user
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount = scoreCount + 1;
scoreTotal = scoreTotal + testScore;
}
else if (testScore != 999)
System.out.println("Invalid entry, not counted");
// display the score count, score total, and average score
double averageScore = scoreTotal / scoreCount;
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n";
System.out.println(message);
System.out.println("Enter more test scores? ('y' to continue, 'n' to close): ");
choice = sc.next();
System.out.println();
}
}
}
Try something like this:
// put this above main() - this way you can use it without ever defining a `Scanner` object again
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
// store number of scores to enter
int numScores = 0;
// input number of scores to enter
System.out.print("How many scores would you like to enter? ");
numScores = in.nextInt();
// store sum of scores
int scoreTotal = 0;
// input scores
for(int i = 0; i < numScores; i++)
scoreTotal += in.nextInt();
// print count, sum, and average of scores
System.out.printf("\nScore count: %d", numScores);
System.out.printf("\nScore total: %d", scoreTotal);
System.out.printf(\n Average score: %d", scoreTotal/numScores);
}
I think this should run, but it may have a bug or two. I do not have Java any more, but I will be able to help if it produces an error. Just place this in your class and see how it works. You shouldn't need to modify it at all.
it is not a good idea to have so many nested whiles, it is very inefficient.
it is a good idea to surround the code with try/catch blocks, I didn't put it in there since I'm not sure you have learnt it.
I think you should take user input as total amount of scores, instead of using 100 in the for loop.
anyway, this is what I would do, hope this code helps:
import java.util.Scanner;
public class test{
public static void main(String[] args){
int count = 0;//amount of scores entered by user
int total = 0;//total score added up
int current = 0;//current amount of scores entered
System.out.println("How many scores would you like to enter?");
Scanner sc = new Scanner(System.in);
count = sc.nextInt();
do{
System.out.println("current amount of scores entered is "+current+" please enter the next score");
total += sc.nextInt();
current ++;
}
while(current < count);
System.out.println("the average score of "+current+" entered scores is "+total/count);
}
}

Categories

Resources