Array initialization error - java

I am doing java programming practice from a website. I have to display this out put using arrays.
Enter the number of students: 3
Enter the grade for student 1: 55
Enter the grade for student 2: 108
Invalid grade, try again...
Enter the grade for student 2: 56
Enter the grade for student 3: 57
The average is 56.0
This is my source code so far, it is raising error The local variable grades may not have been initialized. How do I recover this? I have to make this program using arrays.
package array;
import java.util.Scanner;
public class GradesAverage {
public static void main(String[] args) {
int numStudents = 0;
int[] grades;
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students : ");
numStudents = Integer.parseInt(in.next());
for (int i = 0; i < numStudents; i++) {
System.out.print("Enter grade of student "+i+" :");
grades[i] = Integer.parseInt(in.next());
}
}
}

When you write
int[] grades;
you declare a variable called grades, that can hold a value of type int[]. However, before you can use it you also have to initialize it, eg create the actual data structure. This is done like this:
int[] grades = new int[numStudents];
Note that you need to know the size beforehand when you declare an array, so you will have to move the creation of the array to just before the for loop.

All variables declared in methods have to be assigned a value before you read them to avoid trash values.
Also in java arrays are objects, that means that you have to create an array instance with new and assign it to grades before you can store anything in it.
grades = new int[numStudents];

An array doesn't have a constant memory allocation, therefor you must allocate memory to the new array.
for example
int[] grades = new int [numStudents]
This of course should be written only after you know the value of numStudents

There's not much to add to what Keppil already said, but I'd like to add a little 'why'.
You see, when int[] grades is created, it is nothing but an 'empty pointer', pointing to a random location in memory.
By assigning the return value of 'new int[numGrades]', the value of the pointer points to the location in memory, which has been assigned. This memory is in the exact size of 'size of an integer multiplied by the number of grades', and can be accessed safely.
If this array is dimensioned too small (or not at all), a memory violation exception usually gets triggered, because you're writing memory you have no access to, often causing your program to crash or other undefined behavior.
Please remember: Arrays are different from normal variables.
So yeah, to make it short:
grades = new int[numGrades]; is what you're looking for.
Straight below the line, where you're parsing the the input number of students.
As an additional advice: User input is ALWAYS a source for error.
Make sure to include error handling for invalid output. (For example if some wiseguy decides to input 'John Smith' instead of a grade.

You have to initialise variable before its usage.
Please see one of correct version of your code:
package array;
import java.util.Scanner;
public class GradesAverage {
public static void main(String[] args) {
int numStudents = 0;
int[] grades;
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students : ");
numStudents = in.nextInt();
// this line was added
grades = new int[numStudents];
for (int i = 0; i < numStudents; i++) {
System.out.print("Enter grade of student "+i+" :");
grades[i] = Integer.parseInt(in.next());
}
// closing used resources is a good practice
in.close();
}
}

Related

how to print Scanner element using parallel arrays in java?

I am new to learning about parallel arrays and want to know how to effectively print content/elements using parallel array only, I tried but couldn't get it to work and function the way I want.
The task is: The program inputs an integer from the user representing how many peoples’ information will be entered. Then, the program inputs the information one person at a time (name first, then age), storing this information in two related arrays.
Next, the program inputs an integer representing the person on the list whose information should be displayed (to get information for the first person, the user would enter ‘1’). The program makes a statement about the person’s name and age.
Although I got the name and age to work until the integer the user inputs, but after that I am not sure how to do
Sample input:
4
Vince
5
Alexina
8
Ahmed
4
Jorge
2
2 // I am confused about this part, how would I make it so that it prints the desired name,
//for example with this input, it should print:
Sample output:
Alexina is 8 years old
My code:
import java.util.Scanner;
class Example {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[keyboard.nextInt()];
for (int x = 0; x < num.length; x++){
String[] name = {keyboard.next()};
int[] age = {keyboard.nextInt()};
}
int num2 = keyboard.nextInt();
System.out.println(); // what would I say here?
}
}
You need to rewrite your code so your arrays aren't being assigned within the loop. You want to add values to the arrays, not reset them each time, and you want to be able to access them afterwards. Below is a modified version of your code:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
keyboard.nextLine(); //you also need to consume the newline character(s)
String[] name = new String[num]; //declare the arrays outside the loop
int[] age = new int[num];
for (int x = 0; x < num; x++){
name[x] = keyboard.nextLine(); //add a value instead of resetting the array
age[x] = keyboard.nextInt();
keyboard.nextLine(); //again, consume the newline character(s) every time you call nextInt()
}
int num2 = keyboard.nextInt() - 1; //subtract one (array indices start at 0)
System.out.println(name[num2] + " is " + age[num2] + " years old"); //construct your string with your now-visible arrays
}
As I think you have to think about the local and global variable usage in java.In brief,
Local variables can only use within the method or block, Local variable is available only to method or block in which it is declared.
For example:
{
int y[]=new Int[4];
}
this y array can be accessed within the block only.
Global Variable has to be declared anywhere in the class body but not inside any method or block. If a variable is declared as global, it can be used anywhere in the class.
In your code you try to create arrays and use them out of the For loop. But your arrays are valid only inside the For loop. After every loop runs all info is lost.there will be new array creation for every iteration of For loop.
therefore, In order to access and save the information you have to declare your arrays before the For loop and access and store data using iteration number as the index. finally, to print the data you gathered, you have to scan new input as integer variable.then you can access your arrays as you wanted.
//For example
int [] age=new int[4]; //global -Can access inside or outside the For loop
int[] numbers = new int[keyboard.nextInt()];
for (int x = 0; x < 4; x++){
age[x] = keyboard.nextInt(); //Local
}
int num2 = keyboard.nextInt();
System.out.println(age[num2]); // Here you have to access global arrays using num2 num2
}
}

Passing arrays as parameters and make calculations

I have to make a Java Program, where a user type in the total numbers of students, so I made this code:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
Now, after adding the total number of students, we should add their names into an array:
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
After that, we should add correspondingly the age of each name, so I made this portion of code:
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
After making this code, I tested it using Ideone and Command Prompt and it works properly:
Now, I need to call method according to selection of the user:
if he typed 'a' a method should be called to specify the name and the age of the oldest student.
If he typed 'b' a method called to see how many students have an age specified by the user and If he typed 'c', a function called to calculate the average age of them all.
I am new to methods so I don't know how to add arrays into methods and make statements.
Here is the full code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
//Choosing a statistic
//if a:
System.out.println("Please choose a, b or C:");
Scanner stat = new Scanner(System.in);
char X;
X = stat.next().charAt(0);
if(X=='a')
System.out.println(X+X);
else if(X=='b')
//System.out.println(X);
//Scanner newAge = new Scanner(System.in);
//int ageToSearchFor = newAge.nextInt();
//maxAge(ageToSearchFor);
else
System.out.println(X);
}
}
Right, so to start with your user enters an input, for example 'a', so let's go with this:
Firstly, you need to create the method where the name of the oldest student is displayed, so let's call it 'getOldestStudent' - when naming methods this is the typical naming convention, starting lowercase and then moving to uppercase for each new word - try and make them as intuitive as possible.
When making the method signature, you need to give it its visibility and also what it is going to return. In this case, as you are only using one class, we will give it private, so it is only visible by this class.
Now we need to return 2 things, so we can either put these into a string or put them into an array, which is what I would recommend, so we are going to return an array. However, you want to input an array to search through, so this goes in tbe brackets as parameters (or arguments). Therefore our method signature is the following:
private String[] getOldestStudent(String[] students, int[] ages)
Then inside this method, you can simply do the code you need to find the oldest student, add their name and age to the array and then return this.
Need anymore help just drop a comment.
On a side note, you would have been better off creating a 'Student' object and then giving this object a 'name' property and an 'age' property and then simply making an array of students and getters and setters (or accessors and mutators) for these properties.
James Lloyd's covers your question pretty well, I thought I might add some input as I think you are struggling with some principles.
At first, I would do as James advised and create a class Student that stores the values for each person.
public class Student {
public String name;
public int age;
// Constructors allow you to create a new Object and set some variables
// when you create it.
public Student (String name) {
this.name = name;
}
}
I used public to avoid getters and setters for this explanation, but I'd use private most had I to write it by myself.
Anyways, that way you only have to use one instead of two arrays (and name and age are connected with each other, e.g., you know the age of a student you know the name of, whereas with two different arrays it could happen that you don't know if nameArray[0] belongs to ageArray[0].
So you have an array Student[] students = new Student[numReaders]; and you can set each Student after reading the input, i.e., after reading the name you call students[i] = new Student(name); If you want to set the age of a Student afterwards you can do so by using student[i].age = age.
Now that we have filled our array, we can advance to your actual question.
char method;
method = stat.next().charAt(0);
// I think switch is a little easier to read for such cases
switch(method) {
case 'a': Student oldest = getOldestStudent(students);
if (oldest != null)
System.out.println(oldest.name);
break;
case 'b': //another method
break;
default: // equals to else as if none of the other cases was fulfilled
break;
}
Now you can write your own method for each scenario you have to cover.
public Student getOldestStudent(Student[] students) {
// at first we check some cases that do not require further checks
if (students.length == 0) {
System.out.println("No students have been specified");
return null; // this might lead to a NullPointerException so check the return Object whether it is null before doing anything with it
} else if (students.length == 1)
return students[0];
// no we have to see which students if the oldest in the regular case
// the first student will be used for comparison
Student oldestStudent = students[0];
for (int i = 1; i < students.length; i++) {
// see if our current student is older
if (oldestStudent.age < students[i].age)
oldestStudent = students[i];
}
return oldestStudent;
}
This way you can easily access the Students name afterwards (see above in the switch). You can build all your methods like this by passing the array to the methods and iterating through it. Depending on whether you want to return one or more Students (as it might vary between the different methods) you have to change the return type from Student to Student[].

Increase Array Size Based on Total Numbers Entered

I have an issue for creating an array based on the total amount of numbers entered into the array.
Essentially the program is expected to work as the following: the user is prompted for n numbers to enter into an array. So until the user types '000' as their input, the user will be prompted for a new number.
Note: for this array, I do not want the user to input the amount of numbers they want to enter for the array size. Instead, I want the user to continue inputting random numbers until '000' has been inputted, then, the total amount of numbers that has been entered into the array, is the size of such array.
For example: this would work if we have int array[] = {1, 2, 4, 6}, this will automatically set array size to 4, without actually explicitly declaring the array size as 4 elements. Similarly, with my code, I want it where the numbers that the user enters is added to the array, and then the array size is automatically given from the amount of numbers the user has entered like above.
It is important to note that we do not know the length of the array until the user has entered all n numbers.
I have attempted a skeleton, but it returns a cannot find symbol error:
Code:
//Array Code
import java.util.*;
class setArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int stopInput = 000;
int number;
System.out.print("Enter a number: ");
number = input.nextInt();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
int array[] = {number};
}
System.out.print("Array size: " + array.length);
} // Main brace
} // Class brace
setArray.java:19: error: cannot find symbol
System.out.print("Array Size: " + array.length);
symbol: variable array
location: class setArray
1 error
You have a few errors here. The first is understanding why you get your immediate error. The variable array is declared within the scope of the while loop. It can not be seen outside of this loop. That is why the compiler is complaining.
The second is that the size of the array (if declared outside of the loop) will always be 1. From my understanding of what you have written as an attempt to solve the problem you have describe shows that you are not tackling the problem correctly.
While you don't known the the final length of the array to be entered; you do need to store the values entered (my inference) to populate the final array. To store the value entered by the user you need a list that will grow with the input.
List<Integer> values = new ArrayList<>();
while (number != stopInput) {
System.out.print("Enter a number: ");
values.add(Integer.valueOf(input.nextInt()));
}
Integer[] array = values.toArray(new Integer[values.size()]);
Firstly, the compilation error is because the array variable is not visible from the System.out.println line. This is because it's declared inside the while loop, so is only visible inside the while loop.
To make it visible to the whole method, declare it before the while loop.
Secondly, arrays cannot be resized. You declare an array to be a certain size, and you cannot add or remove elements.
My suggestion would be to use an ArrayList. Declare one before your loop, and add the new number inside the loop. After the loop, the size should be how many numbers were entered.
Finally, there's no difference between 000 and 0. Is 0 a valid input number?
You can use
List<Integer> array=new ArrayList<Integer>();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
array.add(number);
}
This sounds like a job for java.util.ArrayList - this is the array that doesn't have a fixed size and is growing as you add values to it automatically under the covers.
The error is caused because you are creating the array only within the scope of the while loop. You need to create it outside the loop. Secondly, standard arrays are not dynamic, so you would need to either set the size and increase it as needed, or just simply use an ArrayList.
Psuedo:
ArrayList<Integer> list = new ArrayList<Integer>()
...
while(not stop number)
list.add(number)
...
print(list.size())
If you really want to use an Array, here is how you can do it
public static void main(String[] args){
STOP_ENTRY = "000";
scan = new Scanner(System.in);
entry = "";
while(true){
System.out.print("Enter #: ");
String tempS = scan.nextLine();
if(tempS.equals(STOP_ENTRY)) break;
else entry += tempS + ":";
}
String[] split = entry.split(":");
int[] intArray = new int[split.length];
System.out.println("Length of created intArray = " + intArray.length); //length of created array
for(int i = 0; i < intArray.length; i++){
intArray[i] = Integer.parseInt(split[i]);
System.out.println("intArray[" + i + "] => " + String.valueOf(intArray[i]));
}
}
I would recommend an ArrayList, as it dynamically changes is size when you add an element, but do whatever you'd like.
An important note, this does not handle any malicious entry that you might not want (characters, symbols), and will error if they are entered, something you can easily add if you need

How to correctly outprint this array in java?

I'm trying to take an input from the user for the array size and then ask the user for the array contents. This part seems to work fine but the outprint isn't working. It out prints 0's for the marks. Thanks for any help provided.
public static void getExamMarks()
{
int x,mark;
System.out.println("Please enter the number of exam marks: ");
x=Keyboard.readInt();
int javastudents[]=new int[x];
for (int i=0;i<javastudents.length;i++)
{
System.out.println("Please enter an intiger for the mark: ");
mark=Keyboard.readInt();
}
printArray(javastudents);
}
public static void printArray(int [] javastudents)
{
for (int i=0;i<javastudents.length;i++)
{
System.out.println(javastudents[i]);
}
}
You are reading the value from the keyboard into the mark variable, but you are not using the mark variable anymore afterwards. At the same time, you are not storing anything into your javastudents array, so all array elements remain at their initial value of 0. Hence, when printing the array later, you get all 0's.
You need to store the read value into your array, like
...
mark = Keyboard.readInt();
javastudents[i] = mark;
...
In fact, you do not need the mark variable at all and you can do
...
javastudents[i] = Keyboard.readInt();
...

Array setting length and storing information

This is homework. I'm trying to work with arrays and this is the first project working with them. My book shows all kinds of examples but the way they code the examples doesn't do any justice to what the assignment calls for.
I am trying to write a program that asks a user to enter students into the system. The program first asks how many you will enter then it will prompt you for the first name, last name, and score.
What I am trying to accomplish with this section of code is to ask the user how many students they will enter. The line of code that says
getStudentCount();
is a method that collects that information and then returns studentCount
I tried to code this to where the length of the array is going to be the number the user enters but it's not working so I wanted to ask for guidance. Ideally if this works and the user enters 3 then you will be prompted to enter the information 3 times. If the user enters 0 then the program doesn't ask you anything.
public static void main(String[] args)
{
System.out.println("Welcome to the Student Scores Application.");
int studentCount = 1;
getStudentCount();
studentCount = sc.nextInt();
String [] students = new String[studentCount];
for (int i = 0; i < students.length; i++)
{
Student s = new Student();
String firstName = getString("Enter first name: ");
s.setFirstName(firstName);
String lastName = getString("Enter last name: ");
s.setLastName(lastName);
int score = getScore("Enter score: ");
s.setScore(score);
}
}
Everything I had in the program worked up until I tried to code
String [] students = new String[studentCount];
for (int i = 0; i < students.length; i++)
which tells me there is something wrong with the way I am doing this.
Also the assignment asks that I store the information in the array. I'm not clear on how to call it or I guess store it.... I have another class with setters and getters. Is that enough to store it? How would I call it?
Again this is homework so any guidance is appreciated.
Thanks!
Well that's at least a homework example that shows some work on the part of the askee (and nicely written), so here's some help:
You set the studentCount to 1 and then call getStudentcount(), but never assigns the return value to your variable, hence the variable stays 1 (though you're overwriting it afterwards with sc.nextInt() which is probably not what you want if you already have a nice method for it). The fix is just to assign the return value of your method to the variable [1]
[1] Yes I know I shouldn't answer homework questions completely, but I really saw no way whatsoever to answer that only partially - proposals welcome though :)
My hints:
Look carefully at how you are getting the student count, and where you are putting it. You seem to be getting the count in two different ways, and that is at best redundant, and probably a bug.
Presumably there is a stack trace. Read it!!
The stack trace will tell you what exception was thrown, what its diagnostic message is, where it was thrown, and where in your code it was executing when the problem happened.
If you are having difficulty visualizing what is going on, use your Java IDE's debugger and single step the program.
Based on your follow-up comments, there isn't a stack trace. But if there was one, you should read it :-)
I don't understand your lines
getStudentCount();
studentCount = sc.nextInt();
if getStudentCount() "returns" the number they input (as you describe in your text), seems like you should be doing
int studentCOunt = getStudentCount();
I'm trying not to completely do your homework for you, but take a look at the code below for a glimpse of how to do this:
/* Some Declarations You're Going to Need */
private static Scanner scan = new Scanner(System.in); //Private, only need it in here
public static Student[] students; //Public, access it from any class you may need
public static void main(String[] args) {
System.out.println("Welcome to the Student Scores Application.");
System.out.print("Amount of students:");
int studentCount = scan.nextInt();
students = new Student[studentCount];
for (int i = 0; i < students.length; i++) {
students[i] = new Student();
System.out.print("Enter first name:");
String firstName = scan.next();
students[i].setFirstName(firstName);
System.out.print("Enter last name:");
String lastName = scan.next();
students[i].setLastName(lastName);
System.out.print("Enter score:");
int score = scan.nextInt();
students[i].setScore(score);
}
scan = null; //Done with scanner
}

Categories