How to calculate sum of elements of an array - java

I have this code where I'm able to calculate the average of marks but unable to calculate the sum and percentage.
And I want to print the name of the student under student name but I'm getting only the student number.
I tried understand more about these, but was unable to get through.
Could you please help me out?
package cube;
import java.io.*;
import java.util.Scanner;
public class ReportCard {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int DB[][], nos = 0;
String arrayOfNames[] = new String[nos];
String S = "";
Scanner s = new Scanner(System.in);
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
DB = new int[nos + 1][6];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter " + arrayOfNames[i] + "'s English Score : ");
DB[i][0] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Science Score : ");
DB[i][1] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Maths Score : ");
DB[i][2] = Integer.parseInt(br.readLine());
DB[i][3] = (int) (DB[i][0] + DB[i][1] + DB[i][2] / 3); //calculating the Average Marks of Each Student
DB[i][4] = (int) (DB[i][0] + DB[i][1] + DB[i][2]);
}
}
void PrintReport() {
System.out.println("\nGenerated Report Card :\n\nStudent Name. English Science Maths Average Total\n");
for (int i = 0; i < nos; i++) {
Padd("Student Name. ", (i + 1));
Padd("English ", DB[i][0]);
Padd("Science ", DB[i][1]);
Padd("Maths ", DB[i][2]);
Padd("Average", DB[i][3]);
Padd("Total", DB[i][4]);
System.out.println(S);
S = "";
}
}
void Padd(String S, int n) {
int N = n, Pad = 0, size = S.length();
while (n != 0) {
n /= 10;
Pad++;
}
System.out.print(" " + N);
for (int i = 0; i < size - Pad - 5; i++)
System.out.print(" ");
}
public static void main(String args[]) throws Exception {
ReportCard obj = new ReportCard();
obj.Input();
obj.PrintReport();
}
}

You are initializing your arrayOfNames array to a length of zero always. You should be initializing it once you get the value of the variable nos ( similar to your initialization of 2d array DB)

You are creating the array of names, i.e, arrayOfNames as an array of length 0 because nos is initially zero.
Observe this:
int DB[][],nos=0; //nos is initialized to 0
String arrayOfNames[] = new String[nos]; //arrayOfNames is of size = nos,which is in turn equal to 0, hence arrayOfNames is basically an array which can't hold anything.
instead do this: just declare arrayOfNames and don't initialize it. ==> String arrayOfNames[];
define the string size after you accept the size, i.e, nos. So it should be as follows:
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
arrayOfNames[] = new String[nos]; //now define the size
...
This would ensure that the string is accessible outside the Input() function as well as is defined with a valid size.

Following corrections can make your code run..
package testProgram;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class ReportCard {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int DB[][], nos = 0;
//here initaialise reference will null
String arrayOfNames[] = null;
String S = "";
Scanner s = new Scanner(System.in);
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
DB = new int[nos + 1][6];
//create string array object here
arrayOfNames = new String[nos];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter " + arrayOfNames[i] + "'s English Score : ");
DB[i][0] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Science Score : ");
DB[i][1] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Maths Score : ");
DB[i][2] = Integer.parseInt(br.readLine());
//take extra variable that holds total, it increases the readability of the code
int total = DB[i][0] + DB[i][1] + DB[i][2];
DB[i][3] = (total) / 3; //calculating the Average Marks of Each Student
DB[i][4] = total;
}
}
void PrintReport() {
System.out.println("\nGenerated Report Card :\n\nStudent Name. English Science Maths Average Total\n");
for (int i = 0; i < nos; i++) {
Padd("Student Name. ", (i + 1));
Padd("English ", DB[i][0]);
Padd("Science ", DB[i][1]);
Padd("Maths ", DB[i][2]);
Padd("Average", DB[i][3]);
Padd("Total", DB[i][4]);
System.out.println(S);
S = "";
}
}
void Padd(String S, int n) {
int N = n, Pad = 0, size = S.length();
while (n != 0) {
n /= 10;
Pad++;
}
System.out.print(" " + N);
for (int i = 0; i < size - Pad - 5; i++)
System.out.print(" ");
}
public static void main(String args[]) throws Exception {
ReportCard obj = new ReportCard();
obj.Input();
obj.PrintReport();
}
}

Arrays are not dynamic. either you declare its size before hand or you use Arraylist..
boolean loopNaming = true;
int i = 0;
//you are creating array of zero size, use ArrayList instead
// String[] name = new String[i];
ArrayList<String> nameList = new ArrayList<>();
while (loopNaming == true) {
System.out.printf("Enter name of student or done to finish: ");
String name = keyboard.nextLine();
//check if name is 'done'
if (name.equals("done")) {
loopNaming = false;
} else {
nameList.add(name);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
//nextLine positions cursor to next line
keyboard.nextLine();
}
i = i + 1;
}
System.out.println(nameList);

Related

Want to print my stored names in array by JoptionPane, JAVA

public static void main(String[] args) {
i got to enter the amount of names i want, then input them by scanner in console, and after print the longest one, it's mostly done, but i want to print it by JoptionPane aswell
Scanner wczytanie = new Scanner(System.in);
System.out.println("ENTER THE AMOUNT OF NAMES");
int size = wczytanie.nextInt();
String[] array = new String[size];
System.out.println("ENTER THE NAMES");
String name = wczytanie.nextLine();
for (int i = 0; i < array.length; i++) {
array[i] = wczytanie.nextLine();
if (name.length() < array[i].length()) {
name = array[i];
}
}
// System.out.println("LONGEST NAME: " + name);
String name1 = new String();
if(name == name1) {
JOptionPane.showMessageDialog(null, " THE LONGEST NAME IS " + name1);
}
}
You have a lot of problems here: you're reading from the scanner before the loop when reading names and you're doing a raw object equality on a new string for some reason that will never work. You want something more like this:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("How many names? ");
int num = scanner.nextInt();
List<String> names = new ArrayList<>(num);
System.out.println("Enter names: ");
for (int i = 0; i < num; i++) {
names.add(scanner.next());
}
String longest = names.stream().reduce((a, b) -> a.length() > b.length() ? a : b).get();
System.out.println("The longest name is: " + longest);
JOptionPane.showMessageDialog(null, "The longest name is: " + longest);
}
}

My Java program refuses to take a string input [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 4 years ago.
I have an array of strings - name[]. When I try to take an input from the user using the Scanner class the program seems to ignore the statement and go on to the next.
import java.util.Scanner;
class Student { //start of class
public static void main(String[] args) { //start of method main
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + totalmarks[i]; //calculating total marks
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++) {
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
} //end of method main
} //end of class
That's because the sc.nextInt() method does not read the newline character in your input and so you need to call sc.nextLine()
From the docs
Advances this scanner past the current line and returns the input that
was skipped.
This method returns the rest of the current line, excluding any line
separator at the end. The position is set to the beginning of the next
line.
Since this method continues to search through the input looking for
a line separator, it may buffer all of the input searching for the
line to skip if no line separators are present.
You code will now look like :
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
sc.nextLine(); // <----- observe this
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
sc.nextLine(); // <----- observe this
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + totalmarks[i];
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++) {
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
}
Try this.. Your sc.nextLine() is reading empty String after you input integer value
import java.util.Scanner;
class Student
{//start of class
public static void main(String[] args)
{//start of method main
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
String emp = sc.nextLine();
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i=0;i<n;i++)
{
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
emp = sc.nextLine();
}
int sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + totalmarks[i];//calculating total marks
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++)
{
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
}//end of method main
}//end of class

Name and age application with specific output using arrays and output

For my university lab work we have to finish 4 tasks. I'm currently on 6 of 9 and have for the most part completed it, but I'm having difficulty in completing the final parts of it. This is the description of what we must do:
Write a program that defines two arrays - one of strings and one of integers, both of size 10.
Your program should then ask the user to enter the a string representing a persons name,
and an integer representing their age. It should continue to do this until either the user
enters ‘done’ instead of a name, or until the array is full (that is, 10 pairs of names and ages
have been entered). It should then print out the names and ages as well as the names of the
youngest and oldest.
Hint: One tricky part is making sure that once you’ve typed ‘done’ to Finish entering names,
your program does not then ask you for the age of the person with name ‘done’ - be careful
about this.
I've highlighted the issues I'm having above in bolded text. Below is the code I currently have, but I'm not sure how to properly accomplish the bolded text.
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
public class nameAge {
public static void main(String[] args){
String[] name = new String[10];
int[] age = new int[10];
Scanner in = new Scanner(System.in);
String NAME_REQUEST = ("Please enter name");
String AGE_REQUEST = ("Please enter age");
System.out.println("Please enter the name of a person and then their age. Do this for up to 10 people and once finished, type 'done'");
name[0] = in.nextLine();
System.out.println(AGE_REQUEST);
age[0] = in.nextInt();
System.out.println(NAME_REQUEST);
name[1] = in.next();
System.out.println(AGE_REQUEST);
age[1] = in.nextInt();
System.out.println(NAME_REQUEST);
name[2] = in.next();
System.out.println(AGE_REQUEST);
age[2] = in.nextInt();
System.out.println(NAME_REQUEST);
name[3] = in.next();
System.out.println(AGE_REQUEST);
age[3] = in.nextInt();
System.out.println(NAME_REQUEST);
name[4] = in.next();
System.out.println(AGE_REQUEST);
age[4] = in.nextInt();
System.out.println(NAME_REQUEST);
name[5] = in.next();
System.out.println(AGE_REQUEST);
age[5] = in.nextInt();
System.out.println(NAME_REQUEST);
name[6] = in.next();
System.out.println(AGE_REQUEST);
age[6] = in.nextInt();
System.out.println(NAME_REQUEST);
name[7] = in.next();
System.out.println(AGE_REQUEST);
age[7] = in.nextInt();
System.out.println(NAME_REQUEST);
name[8] = in.next();
System.out.println(AGE_REQUEST);
age[8] = in.nextInt();
System.out.println(NAME_REQUEST);
name[9]= in.next();
System.out.println(AGE_REQUEST);
age[9] = in.nextInt();
System.out.println(NAME_REQUEST);
int size = name.length;
int sizeN = age.length;
for (int i=0; i < size; i++) {
System.out.println("Name: " + name[i]);
System.out.println("Age: " + age[i]);
}
int smallest = age[0];
int largetst = age[0];
for(int i=1; i< age.length; i++)
{
if(age[i] > largetst)
largetst = age[i];
else if (age[i] < smallest)
smallest = age[i];
}
System.out.println("Largest Number is : " + largetst);
System.out.println("Smallest Number is : " + smallest);
}
}
You have to take a look on loop doc in java
this code may help you
public static void main(String[] args) {
int youngest =0,older=0;
String[] name = new String[10];
int[] age = new int[10];
String NAME_REQUEST = ("Please enter name");
String AGE_REQUEST = ("Please enter age");
for(int i=0 ; i< 10;i++){
Scanner in = new Scanner(System.in);
System.out.println(NAME_REQUEST);
String tmpName = in.nextLine();
if(tmpName.equalsIgnoreCase("done"))
break;
name[i] = tmpName;
System.out.println(AGE_REQUEST);
age[i] = in.nextInt();
if(age[i] > age[older])
older = i;
if(age[i] < age[youngest])
youngest = i;
}
System.out.println("OLDER is : " + name[older]);
System.out.println("Younger : " + name[youngest]);
}
Try this out, I have tested it and it's working fine. Hope that helps. Happy coding.
package com.pearson.nextgen.aggregatedsessionservice;
import java.util.Scanner;
public class NameAgeTest {
public static void main(String[] args) {
String[] name = new String[10];
int[] age = new int[10];
Scanner in = new Scanner(System.in);
String NAME_REQUEST = "Please enter name";
String AGE_REQUEST = "Please enter age";
int count = 0;
while (count < 10) {
System.out.println(NAME_REQUEST);
String nameInput = in.next();
if (nameInput.equalsIgnoreCase("done")) {
break;
}
name[count] = nameInput;
System.out.println(AGE_REQUEST);
age[count] = in.nextInt();
count++;
}
int[] minAndMaxIndex = findMinAndMaxIndex(age, count);
System.out.println("Youngest Person: " + name[minAndMaxIndex[0]]);
System.out.println("Oldest Person: " + name[minAndMaxIndex[1]]);
}
private static int[] findMinAndMaxIndex(int[] inputArray, int count) {
int min, max = 0;
int minIndex = 0, maxIndex = 0;
max = min = inputArray[0];
for (int i = 0; i < count; i++) {
if (inputArray[i] > max)
maxIndex = i;
else if (inputArray[i] < min)
minIndex = i;
}
return new int[] { minIndex, maxIndex };
}
}

Taking same output twice times

/*
* (Sort students) Write a program that prompts the user to enter the number of students,
*the students’ names, and their scores, and prints student names in decreasing
*order of their scores.
*/
package homework6_17;
import java.util.Scanner;
public class Homework6_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberOfStudents = input.nextInt();
String[] names = new String[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the name of student: ");
names[i] = input.nextLine();
}
double[] scores = new double[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the score of student: ");
scores[i] = input.nextDouble();
}
String temps = "";
double temp = 0;
double max = scores[0];
for(int i = 0; i<(scores.length-1); i++){
if(scores[i+1]>scores[i]){
temp=scores[i+1];
scores[i]=scores[i+1];
scores[i+1]=scores[i];
temps = names[i+1];
names[i]=names[i+1];
names[i+1]=names[i];
}
}
for(int i = 0 ; i<(scores.length-1); i++)
System.out.println(names[i]+ " " + scores[i]);
}
}
When i run this program;
run:
Enter number of students: 3
Enter the name of student:
Enter the name of student:
a
Enter the name of student:
b
Enter the score of student:
c
Exception in thread "main" java.util.InputMismatchException
// i got " Enter the name of student: " twice times instead of one.
The first thing that comes to mind (not sure if it is correct here) is that you type the number of students and press "enter". It reads the first int (the 3) and reads the "enter" as the first input for the first student.
Maybe try int numberOfStudents = Integer.ParseInt(input.nextLine());?
That way the newline wont be added to the students.
You just have to remove the first System.out.print("Enter number of students: "); as you are printing the phrase in your for loop for every student. Therefore you are printing it twice for the first student (one time before your loop and one time in your loop)
It's not a good idea to answer homework question in SO. But since you have tried some code, It's OK to answer the Q. Take a look:
import java.util.Scanner;
public class Homework6_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberOfStudents = input.nextInt();
String[] names = new String[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the name of student #" + (i + 1) + ":");
names[i] = input.next();
}
double[] scores = new double[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the score of student " + names[i] + ":");
scores[i] = input.nextDouble();
}
String tempName;
double tempScore;
for (int i = 0; i < numberOfStudents; i++) {
for (int k = i + 1; k < numberOfStudents; k++) {
if (scores[k] > scores[i]) {
tempName = names[i];
tempScore = scores[i];
names[i] = names[k];
scores[i] = scores[k];
names[k] = tempName;
scores[k] = tempScore;
}
}
}
for (int i = 0; i < numberOfStudents; i++)
System.out.println(names[i] + " " + scores[i]);
}
}

Changing the variable assigned everytime a loop iterates

I am trying to build a program that allows the user to enter length and width of an object however many times I choose (I would build more code to choose how many times the loop goes). I am having some problems figuring out how to get input and construct an object every time the loop iterates. Thanks!
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
for (int i = 1; i <= 2; i++)
{
System.out.println("Enter length" + i + ": ");
int length i = console.nextInt();
System.out.println("Enter length" + i + ": ");
int width i = console.nextInt();
OBJECT instance1 = new OBJECT(length1, width1);
}
}
You can use ArrayList/LinkList, if your entries are big then only go for LinkList.
Scanner console = new Scanner(System.in);
System.out.println("Enter how many records you want: ");
int j = console.nextInt(); //"Loop will run "+ j +" times"
List<ObjectName> objectList = new ArrayList<ObjectName>();
int length = 0;
int width = 0;
for (int i = 1; i <= j; i++)
{
System.out.println("Enter length" + i + ": ");
length = console.nextInt();
System.out.println("Enter width" + i + ": ");
width = console.nextInt();
ObjectName instance1 = new ObjectName(length, width);
objectList.add(instance1);
}
You need to understand how to use the Collections API, in particular List, LinkedList and ArrayList. So your code would become:
public static void main(String[] args) {
final Scanner console = new Scanner(System.in);
final List<Area> objectList = new ArrayList<Area>();
for (int i = 0; i < 2; i++) {
System.out.println("Enter length" + (i + 1) + ": ");
final int length = console.nextInt();
System.out.println("Enter width" + (i + 1) + ": ");
final int width = console.nextInt();
final Area instance = new Area(length, width);
objectList.add(instance);
}
}
I've choosen ArrayList here because it is normally the better performing one of the two (but for relatively small lists that do not require the functionality of either one, both will do).

Categories