Using a loop to print output of arrays? - java

import java.io.*;
import java.util.*;
public class AP_ExamArray
{
//User Input AP Exam Scores Using For Loops
public static void main(String args[])
{
int [] scores = new int[5];
int j;
int sum_exam=0;
for (j=0; j<scores.length; j++)
{
Scanner kbReader = new Scanner(System.in);
System.out.println("Please enter AP Exam Score (1-5): ");
scores[j]=kbReader.nextInt();
sum_exam+=scores[j];
}
//Initializer List Final Percentage
double [] final_percent = {97.3, 89.8, 96.2, 70.1, 93.0};
double sum_percent=0;
int k;
for(k=0; k<final_percent.length;k++)
{
sum_percent+=final_percent[k];
}
// String array containing last name (while loop)
String [] last_name = new String[5];
int i=0;
while (i<last_name.length)
{
Scanner kbReader = new Scanner(System.in);
System.out.println("Please enter last name: ");
last_name[i]=kbReader.next();
i++;
}
//Average Exam Scores
double avg_exam = (double) sum_exam/scores.length;
//Average Final Percentage
double avg_percent = (double) sum_percent/final_percent.length;
}
}
The directions are:
"For your output use a loop to print the student names, percentages, and test score, and be sure to include appropriate data below each column heading:
Student Name Student Percentage Student Test Score."
I'm not sure how to do this!

How about:
for(i=0; i<scores.length; i++)
System.out.println(last_names[i] +"\t"+ final_percent[i] +"\t"+ scores[i]);
A for loop is used because you want to loop through the entire
array of a known size.
If, instead, you wanted to loop only while a certain condition holds
you would use a while loop: (e.g. while(condition) loop;).
System.out.println() will print a new line after each call, and \t will add a tab.
For better formatting check out this Oracle doc on using printf and format

Related

Getting information out of a whole array to a variable?

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.

Questions about one dimensional arrays and sorting in Java

I'm currently in the second half of a computer science class but I wasn't able to take the second one right after the first one. So I've forgot a large portion of my coding knowledge. I'm trying to re learn it all but it's quite tough without just going all the way back to the basics.
An assignment I'm working on currently is asking me to do the following:
Design a solution that requests and receives student names and an exam score for each. Use one-dimensional arrays to solve this.
The program should continue to accept names and scores until the user inputs a student whose name is “alldone”.
After the inputs are complete determine which student has the highest score and display that student’s name and score.
Finally sort the list of names and corresponding scores in ascending order.
I wasn't really sure how to organize and start this but I went ahead and just started writing some code to at least make some progress and maybe figure something out.
The way I've set up my program doesn't exactly respond to the prompt as I was experimenting with array lengths and for loops to get reacquainted.
SO MY QUESTION IS, How would I make it so when users type "alldone" the program stops taking inputs and calculates the highest grade with the person who had it only using 1D Arrays.
Is it possible to take the names as a string and then insert the strings into an array?
Here is my code so far, It's not what the assignment is looking for but I just want to get some inspiration on some things I could do:
public static void main(String[] args) {
int studentcount;
Scanner input = new Scanner(System.in);
Scanner sc= new Scanner(System.in);
//Input to set array length
System.out.println("How many students are you grading? ");
studentcount=sc.nextInt();
//One dimensional array to hold student names/grades
String [] names = new String [studentcount+1];
int [] grades = new int [studentcount];
//Input to record student names/grades
System.out.println("Please enter the name of the students ");
for (int i = 0; i < names.length; i++) {
names[i] = sc.nextLine();
}
System.out.println("Please enter the grades of the students ");
for (int i = 0; i < grades.length; i++) {
grades[i] = sc.nextInt();
}
// For loop to display student names and grades
for (int i = 0; i < studentcount; i++) {
System.out.println(names[i+1] + " " + grades[i]);
}}}
The output looks like this:
How many students are you grading?
3
Please enter the name of the students
John
Brett
Wendy
Please enter the grades of the students
10
20
30
John 10
Brett 20
Wendy 30
It doesn't make sense to enter the number of students and also signal the end of input with a keyword. Since you must key in on "alldone" to stop taking input, it is implied (to me) you must initially over allocate you arrays. I chose 3 for demo purposes. If more input is required the arrays can be adjusted as demonstrated. This example simply explains how to take in the data and populate the arrays. It does not deal with the mechanics of sorting as that was not part of your question.
int studentCount = 0;
Scanner input = new Scanner(System.in);
// allocate space for three students
String[] names = new String[3];
int[] grades = new int[3];
int maxInput = names.length;
System.out.println(
"Please enter name and grade of student (e.g. john 23)\non each line.");
// now enter the student and their grade
for (int i = 0; i < maxInput; i++) {
String name = input.next();
// this is where you check for the keyword to signal
// end of input
if (name.equals("alldone")) {
break;
}
names[studentCount] = name;
grades[studentCount++] = input.nextInt();
// if you have maxed out your arrays you need to copy
// the contents to a larger array
if (studentCount == maxInput) {
// increase array size
maxInput += 3; // increase by 3.
names = Arrays.copyOf(names, maxInput);
grades = Arrays.copyOf(grades, maxInput);
}
}
// once here, the input part is over. This displays the entered data
for (int i = 0; i < studentCount; i++) {
System.out.println(names[i] + " " + grades[i]);
}
Note, at this point it is possible that your arrays will contain extra spaces that could affect your sort (and possibly cause an error). You can trim the excess space using Arrays.copyOf as before, specifying the number of students.
Or if you sort using your own routine, you can ignore the excess spaces by using studentCount instead of the length of the arrays.
You should create a class and implement the Comparable interface like this. The way I have it set up here, it sorts by name. If you want to sort by the score, just comment out the name compare and uncomment the grade compare.
public class Student implements Comparable<Student> {
private String name;
private int grade;
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public int getGrade() {
return grade;
}
#Override
public int compareTo(Student o) {
//sorting by name
return name.compareTo(o.name);
//Compare by grade -- reversed so it's highest first
//return Integer.compare(o.grade, grade);
}
#Override
public String toString() {
return "Student [name=" + name + ", grade=" + grade + "]";
}
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
Student [] students = new Student[0];
while(true) {
System.out.println("Please enter the name of the student or \"alldone\" if complete: ");
String name = input.next();
if (name.contentEquals("alldone")) {
break;
}
System.out.println(String.format("Please enter %s's grade: ", name));
int grade = input.nextInt();
input.reset();
students = Arrays.copyOf(students, students.length+1);
students[students.length-1] = new Student(name, grade);
}
Arrays.sort(students);
for (Student student : students) {
System.out.println(student);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

I want to calculate the sum of ages of the enteries, I am not sure of how to do it?

This is a program that takes in entries of a group of people asks them for data such as age and name... it then should calculate the mean of the ages of the entries.
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) {
int person;
String nameOfPerson;
double ageOfPerson;
double standardDeviation;
double total = 0;
Scanner scan = new Scanner(System.in);
System.out.println("How many entries?");
person = scan.nextInt();
String[] names = new String[person];
for(int counter =0; counter < person; counter++) {
System.out.println("Enter the name of person"+(counter+1));
names[counter]= scan.next();
if (person==1);
System.out.println("Please enter the age of person"+(counter+1));
ageOfPerson = scan.nextDouble();
}
}
}
if (person==1);
System.out.println("Please enter the age of person"+(counter+1));
First of all - here you have empty "if" expression, fix it.
If you need to calculate the sum, you just need to use
ageOfPerson += scan.nextDouble();
Each iteration this double will be increased

How do I fix the "float cannot be converted into float[]" error in the below code?

I have written a small program to take number of elements from user and the price of those elements and then print the price.
But the 12th line of this code giving error "float cannot be converted into float[]", and I am not able to figure out how to resolve this. Please provide some help or any modification in the code if needed.
import java.util.Scanner;
public class Main{
public static void main( String args[]){
System.out.println("enter the number of elements :" );
Scanner s1= new Scanner(System.in);
int N = s1.nextInt();
System.out.println("enter the price of all the elements in ascending
order: ");
float[] price =new float[N];
for(int i=0; i<N;i++){
price=s1.nextFloat();
System.out.println(price);
}
}
}
In your code, price is an array
float[] price = ...
And an array of type T consists of elements, each of type T. So you need to assign an element of the array to a float e.g.
price[i] = myFloat;
Formatting and nomenclature are a must when you write code as it makes your code more readable and easy to understand. I have formatted your code and also updated for proper inputs.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
System.out.println("enter the number of elements :");
Scanner s1 = null;
try {
s1 = new Scanner(System.in);
int totalElements = s1.nextInt();
System.out.println("enter the price of all the elements in ascending order :");
float[] price = new float[totalElements];
for (int i = 0; i < totalElements; i++) {
price[i] = s1.nextFloat();
System.out.println(Arrays.toString(price));
}
} finally {
if (s1 != null) {
s1.close();
}
}
}
}
Please take care of below things:
Variable names should start with small case and follow camel casing.
Scanner whenever used needs to be closed.
Your error is resolved by assigning float to one position in array and not to the array. E.g. price[i] = s1.nextFloat();
To print an array, use the Arrays.toString() function.
Happy Coding
import java.util.Scanner;
public class Main{
public static void main( String args[]){
System.out.println("enter the number of elements :" );
Scanner s1= new Scanner(System.in);
int N = s1.nextInt();
System.out.println("enter the price of all the elements in ascending
order :");
float[] price =new float[N];
for(int i=0; i<N;i++){
price[i]=s1.nextFloat();
System.out.println(price[i]);
}
}
}
It should be like this because in the printing statement you've called the whole array that won't give you the element but the some numbers and alphabets thing and also the statement where you're reading the prices by scanner you are not telling the computer to put your price at which index of the array that's why it's giving this error.

need scanner input for array

does anyone know how to set a user input for an array, I cant find the command anywhere. my array 'grades' have 20 locations. im not so sure about 'grades.length' function but I think it prompts 20 times. BUT I added a while statement to override BUT ITS TOTALLY IGNORING THE FOR STATEMENT. if I could set user input for array I could get rid of the while statement...
program has to accept grade for number of students the user inputs btw..
import java.util.Scanner;
public class gradesaverage {
public static void main(String[] args) {
int [] grades = new int [20];
int i;
int numStudents;
System.out.print("Enter number of students: ");
Scanner scanint = new Scanner (System.in);
numStudents = scanint.nextInt();
for ( i = 1; i <= grades.length; ++i)
{
System.out.println("Enter grade: ");
grades[i] = scanint.nextInt();
}
while(i <= numStudents );
}
}
Not sure what you mean, but assuming all input is correct,
int [] grades = new int [numStudents ];
Should work if you move this line after declaration and assignment of numStudents. There is no problem in java with variable length arrays.
Also note - your iterator i starts from 1, while in java arrays start from 0.
public static void main(String[] args) {
int i;
int numStudents;
System.out.print("Enter number of students: ");
Scanner scanint = new Scanner (System.in);
numStudents = scanint.nextInt();
int [] grades = new int [numStudents]; //the size we wanted
for ( i = 0; i < grades.length; ++i) //starting from 0, not 1.
{
System.out.println("Enter grade: ");
grades[i] = scanint.nextInt();
}
//print the array - for checking out everyting is ok
System.out.println(Arrays.toString(grades));
}

Categories

Resources