"Cannot resolve symbol" of my declared variable? [duplicate] - java

This question already has answers here:
Scope of variable declared inside a for loop
(5 answers)
Closed 8 years ago.
The solution to my problem is probably something really obvious, but I have yet to find it. If you're at all wondering what this code is suppose to do, it's suppose to take 10 user-inputted numbers, add them together, and output the average. My only error thus far is that where I have double average = sum / 10;
it doesn't read the variable sum and I'm at a total loss as to why.
import java.io.*;
class Average
{
public static void main (String args[]) throws IOException
{
// declare some variables
int count = 0;
String inInput;
// declare array constructer
double[] userInput = new double[9];
// declare a reader
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(inStream);
// print out the array
while (count >= 9)
{
if (count != 10)
{
System.out.println ("Please enter a value");
}
else
{
System.out.println ("Please enter another value");
}
inInput = reader.readLine();
double inInputDouble = Double.parseDouble(inInput);
userInput[count] = inInputDouble;
double sum = sum + userInput[count];
count++;
}
double average = sum / 10;
System.out.println ("The average of all the numbers you have entered is" + average);
}
}

A variable can only be used inside the scope of which it is declared. Your sum variable is declared inside the while body and can thus only be used inside that scope.
Move the declaration of sum outside of the while loop as follows:
double sum = 0;
// print out the array
while (count >= 9)
{
...
sum = sum + userInput[count];
...
}
...
You probably also want to change count >= 9 to count < 9 to avoid ArrayIndexOutOfBounds.

int count is always 0, so it never goes into while(count >= 9) and when sum is called it won't be defined at all, change it for while(count <= 9)

You are declaring you variable sum inside the while loop block. Once that block finishes the variable goes out of scope and is no longer defined.
Put your double sum declaration before the while and you should be fine.

The scope of sum is the block it's declared in which is the block of the while loop.
Declare sum outside the while loop.
It doesn't make too much sense to redeclare this variable over and over again, because you want to sum up all numbers.
Take a look at this question:
Scope of variable declared inside a for loop

As said above, the sum must be declared befor the for loop.
Scopes are like brackets in programs,
int a ..
{
int b ...
{
int c ...
}
}
if the instruction evaluated is on line with a, it cannot know about the state of b and c, since they are not declared yet.
if instuction pointer evaluates line with int c , it know about all the variables because it allready got into the 3rd level of scoping. but since c is declared on 3rd level, after the instuction pointer goes outer from the brackets, if you did not saved the value of c in an upper leveled variable, the value gets lost, since c gets cleaned, and it is not accessible(outer scope). It is the same like you would want to read a variable from another file... you cant, scopes are like sticky notes which start from outer and append new smaller stickynotes, which after iot has been worked with , they get removed
scope: class definitions > method definitions > block definitions(for, while, if)
visible everywhere - visible under the method > visible in the block only
after it exits method all (eg: for (int i;..)
is gone i is not visible outer the for / brackets
another bug:
new double[9]; ?
you said it is supposed to take 10 ints...
at initialistion you dont count 0... 0 is used at 0 based indexing (a[0],a[1],a[2] needs a new int[3])... set it to new double[10];

Related

Values are not initializing under try block?

trying to make program rotation of array, it was giving an Exception by user misinput so I use try block but now, under try block it is not initializing values....
Can some one tell the reason or solution for this....
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
ArrayRotation ar = new ArrayRotation();
System.out.println("Enter T : ");
int t = sc.nextInt();
sc.nextLine();
while(t!=0){
System.out.println("\nEnter N D : ");
String s = sc.nextLine();
s.trim();
String st[] = s.split(" ");
int n,d;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}catch(Exception e){ System.out.println("Exception"+e.getMessage()); }
System.out.println("Enter Element : ");
s=sc.nextLine();
st = s.split(" ");
ar.rotateArray(st,n,d);
t--;
}
}
If you need valid input and you did not get valid input, the thing to do is to try again to get valid input, after telling the user the input was invalid. Don't just proceed with the invalid data. You therefore need an inner loop:
while (t!=0) {
boolean validInput = false;
while (!validInput) {
System.out.println("\nEnter N D : ");
String s = sc.nextLine().trim();
String[] st = s.split(" ");
int n,d;
try {
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
validInput = true;
}
catch (Exception e) {
System.out.println("Invalid input");
}
}
… process n and d as before …
}
For my taste the loop to get the valid input would be better off being a subroutine in its own right - for clarity.
Variable in local scope should be initialized , that is what error , so do initialize the variables n and d to some integer value say as below
int n = 0 ,d = 0;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}
When a method throws an exception, that method never returns.
This means that if n = Integer.parseInt(st[0]); throws an exception, it does not return a value, which means n will not be assigned a value (since there is no return value to assign to it).
You are ignoring the exception and trying to continue as if nothing went wrong. But something did go wrong—n was never assigned a value. So the compiler tells you that it is not safe to use n in any subsequent code.
To solve this, you first must decide what to do if the user provides invalid input. You can’t just ignore the exception. If the input doesn’t represent two integers, you don’t have any values to work with. You can’t continue in any meaningful way.
The best course of action is to remove your try and catch. This will cause the program to terminate if Integer.parseInt fails, which is almost certainly what you want (unless your assignment requires you to do something different). Remember that it is not possible to continue in any meaningful way without values assigned to n and d.
In other words, change this:
int n,d;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}catch(Exception e){ System.out.println("Exception"+e.getMessage()); }
to this:
int n = Integer.parseInt(st[0]);
int d = Integer.parseInt(st[1]);
As a side note, this line does nothing:
s.trim();
…because Strings cannot be changed. s.trim() returns a new String which you must capture in a variable. You probably want to do this:
s = s.trim();
Your image is quite misleading and really doesn't point to the actual problem, it only points to what you perceive to be the problem. Your mistake was placing the initialization of variables n and d into a try block which takes your call to the rotateArray() method out of scope for that initialization of those variables.
The bigger problem is... What in the world are you rotating? Where is the Array to rotate? Is it actually a String Array or is it suppose to be an Integer Array? Please don't tell me it's the st[] String Array (which is what you're trying to do) because according to your code that array is used to establish the array size (n) portion to work with and the number of elements (d) the User wants to rotate by. No rocket science to rotate an Array with only two elements. Give the rotateArray() method an array to actually rotate.
Let's provide an Integer Array and a way to do this without a try/catch mechaism:
// The Array to carry out rotations on.
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
String ls = System.lineSeparator();
Scanner sc = new Scanner(System.in);
ArrayRotation ar = new ArrayRotation();
int t = 0;
String value = "";
while (value.equals("")) {
System.out.print("Enter Number of times to Rotate Array: --> ");
value = sc.nextLine().trim();
/* Make sure a String representation of a Integer value is supplied.
The regular Expression "\\d+" in the String#matches() method
ensures the a numerical integer string is supplied. */
if (!value.matches("\\d+" || value.length() > 9) {
/* Will handle situations where nothing is supplied, alpha
characters might be supplied, or the supplied numerical
value is outrageously large. */
System.out.println("Invalid integer numerical value supplied!" + ls);
value = "";
}
}
t = Integer.parseInt(value);
while (t != 0) {
System.out.println();
System.out.print("Enter the Size (portion) of the Array to consider and the" + ls
+ "number of elements to rotate (separated with a space): --> ");
String s = sc.nextLine().trim();
// Quit if anything starting with the letter "Q"
// (like "q" or "quit") is supplied.
if (s.substring(0, 1).equalsIgnoreCase("q")) {
System.out.println("\"Quit\" Supplied!");
System.exit(0);
}
String st[] = s.split(" ");
/* Make sure two values were supplied and that
they are both numerical integer strings. */
if (st.length != 2 || !st[0].matches("\\d+") || !st[1].matches("\\d+")) {
System.out.println("Invalid Input! Try again and make sure 'both' "
+ "values are numerical Integers.");
continue;
}
// Declare and initialize the n and d variables.
int n = Integer.parseInt(st[0]);
int d = Integer.parseInt(st[1]);
/* If the number of elements to rotate is greater
than the portion of array to rotate in. */
if (d >= n) {
System.out.println("Invalid Input! The size of the Array portion to rotate" + ls
+ "must be greater than the number of elements to rotate.");
}
/* If the supplied Array size to deal with is
out of bounds of the Array itself. */
else if (n < 1 || n > array.length) {
System.out.println("You have supplied an invalid Array Size! (" + n
+ ") Size must be between 1 and " + array.length + "!"
+ ls);
}
/* If the supplied number of elements to rotate
is less than 1 or greater than the total number
of elements - 1. */
else if (d < 1 || d > (array.length - 1)) {
System.out.println("You have supplied an invalid number of elements to rotate! (" + d
+ ") Value must be between 1 and " + (array.length - 1) + "!" + ls);
}
// All is good - Do the rotation.
else {
ar.rotateArray(array, n, d); // Rotate the Array
// Display the current rotation...
System.out.println("Current Rotation: --> " + Arrays.toString(array));
t--;
}
}
// Done
The error you outline in your image is a general compilation error and is relatively generic for all data types. This error occurs when you are trying to use a local variable without first initializing it. You won't get this error if you use a uninitialized class or instance variable because they are initialized with their default value (for example: Reference types are initialized with null and integer types are initialized with zero), but if you try to use an uninitialized local variable in Java, you will get this error. This is because Java has the rule to initialize the local variable before accessing or using them and this is checked at compile time. If the compiler believes that a local variable might not have been initialized before the next statement which is going to use it, you will receive this error. You of course will not get this error if you just declare the local variable but don't use it but then, why declare it in the first place.
Everyone is stating to initialize the local variables n and d because in reality, in order to successfully compile your code that is exactly what needs to be done in order for the rotateArray() method (which uses these uninitialized variables) to function. Again in reality, you do initialize them however your code does it within a try{} block which alters scope and the compiler is smart enough to know that if the initialization fails within the try{} block then the catch{} block could let that failure be ignored. In fact, if you were to place the call to the rotateArray() method within that try{} block then you would not get this compile time error since the call is within the scope of of where the variables n and d are actually initialized. You know, a decent IDE (line Eclipse, NetBeans, InteliJ, etc) should catch this error for you long before you try to compile.
According to your code, the actual intent of the try/catch blocks would be to handle the case of invalid input whereas a non-numerical integer value was supplied by the User. In this case it would be up to your catch{} block to handle that particular situation which should be to inform the User of the invalid input and then continue to re-prompt for proper input. At compile time the compiler really doesn't care about this mechanism since this would be a Runtime Error unless of course it is syntax related.
Nothing wrong with try/catch, I just like to avoid them if I can.

How to make Java ignore previous instructions if specified sum is given?

Literally started with Java today, and my professor has given my class the task of modifying some very basic code.
I want to modify the code to make it print a message if the sum of n1 and n2 is 666, but I don't want it to print the actual sum or the message that would normally go attached to it. I saw somewhere around here that a similar question was asked, but the solution doesn't seem to work for me. I have no idea why. Please help.
import java.io.Console;
import java.util.Scanner;
public class FirstProgram{
Console t = new Console();
public static void main(String[] args)
{
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
int n1, n2;
Scanner keyboard = new Scanner(System.in);
n1 = keyboard.nextInt( );
n2 = keyboard.nextInt( );
//This should print normally when the sum is anything BUT 666
System.out.println("The sum of those two numbers is");
System.out.println(n1 + n2);
//If the sum IS 666, I don't want it to print the above lines, just the one below.
if (n1 + n2 == 666);
t.println("Nice try, Satan");
}
}
It gives two major errors: the constructor Console() is not visible, and that I cannot make a static reference to a non-static field t. I have no idea what any of that means or how to fix it.
You should learn how to make conditional statements. Java will not "ignore" and pass to another thing if you don't tell it how to do that. Remeber: computer can't do anything if one do not tell it to do and how to do that.
You are not initializing n1 and n2, they should be initialized after getting the value from the input.
And as said in the comments, always wrap loops, conditional statements within curly braces{} to make sure the code that will be executed be the one inside braces.
import java.util.Scanner;
public class FirstProgramm{
public static void main(String[] args){
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
Scanner keyboard = new Scanner(System.in);
int n1 = keyboard.nextInt( );
int n2 = keyboard.nextInt( );
//See? the result is stored inside this variable
int sum = n1 + n2;
//If the sum is equal 666 then print the message
if(sum == 666) {
System.out.println("Nice try, Satan");
}else {
//Else if the sum is something else, print it
System.out.println("The sum of those two numbers is");
System.out.println(sum);
}
}
}
You can even play with the operator that the if uses to evaluates the condition:
if(sum != 666) { //If sum is `not equal to` 666... if the sum is anything else than 666, print it
System.out.println("The sum of those two numbers is");
System.out.println(sum);
}else {// But if it is 666, print what is inside the parentheses
System.out.println("Nice try, Satan");
}
I will try to help you out here.
Firstly: the constructor Console() is not visible
I think this is in reference to the fact that Console was not really meant to be accessed like that. The constructor of Console is private, meaning that outside classes cannot access it. To remedy this issue, when you want to print to the console, use System.console.
Secondly: I cannot make a static reference to a non-static field t
This one is a bit difficult to explain to someone new. Your main function is static, which means it can be accessed without having to instantiate the class that contains it. Your variable t is a instance variable, meaning that it can be accessed by every function in the class when the class has be initialized. However, because the main function is static, you cannot access a non-static variable, because it may not be initialized yet. If you want to access a instance variable in a static function, you need to make that variable static as well, making it a class variable, which will always be accessible.
Lastly
To getting your code working, you need to read up on if statements. This is a conditional statement that is basically asking if this statement is true, do this. There is an else if and else statements as well that say else if this statement is true, do this and else do this.
Example of proper if/else if/else statement:
if(iAmTrue == true)
{
//do this
}
else if(theOtherIAmTrue == true)
{
//do this
}
else
{
//do this because everything else was not true
}
So to fix your code, you would need to do this:
if(n1 + n2 == 666)
{
System.out.println("Nice try, Satan");
}
else
{
//Put your other print message(s) here.
}
I have rewritten the code for you with a few recommendations to achieve what you need.
import java.util.Scanner;
public class FirstProgram {
// I have removed the Console variable, you don't need that.
// System.out.println prints to the console.
// Use constants for any number or string used to give them meaning
private static final int DEVILS_NUMBER = 666;
public static void main(String[] args) {
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
Scanner keyboard = new Scanner(System.in);
// declare variables next to where they are used.
// additionally, never declare more than one variable per line.
// never do this: int n1, n2;
int n1 = keyboard.nextInt();
int n2 = keyboard.nextInt();
// store the sum in a variable so you can refer to it without doing the sum many times
int sum = n1 + n2;
//If the sum IS DEVILS_NUMBER, I don't want it to print the above lines, just the one below.
// always test the positive possibility first, never the negation
if (DEVILS_NUMBER == sum) {
System.out.println("Nice try, Satan");
} else {
//This should print normally when the sum is anything BUT DEVILS_NUMBER
System.out.println("The sum of those two numbers is");
System.out.println(n1 + n2);
}
}
Last but not least, have a look at Java Google Style for tips on how to properly format your code. If you are using an IDE like Eclipse, Intellij or NetBeans it can automatically format the code for you.

Why is there no output from the While loop in my code, despite everything else working?

I made this program in java, on the BlueJ IDE. It is meant to take a number in the decimal base and convert it into a base of the users choice, up till base 9. It does this by taking the modulus between two numbers and inserting it into a string. The code works till the input stage, after which there is no output. I am sure my maths is right, but the syntax may have a problem.
My code is as follows:
import java.util.*;
public class Octal
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int danum = 0;
int base = 0;
System.out.println("Please enter the base you want the number in (till decimal). Enter as a whole number");
base=in.nextInt(); //This is the base the user wants the number converted in//
System.out.println("Enter the number you want converted (enter in decimal)");
danum=in.nextInt(); //This is the number the user wants converted//
while ( danum/base >= base-1 && base < danum) {
int rem = danum/base; //The number by the base//
int modu = danum % base;//the modulus//
String summat = Integer.toString(modu);//this is to convert the integer to the string//
String strConverted = new String();//Making a new string??//
StringBuffer buff = new StringBuffer(strConverted);//StringBuffer command//
buff.insert(0, summat); //inserting the modulus into the first position (0 index)//
danum = rem;
if ( rem <= base-1 || base>danum) {//does the || work guys?//
System.out.println(rem + strConverted);
}
else {
System.out.println(strConverted);
}
}
}
}
I am very new to Java, so I am not fully aware of the syntax. I have done my best to research so that I don't waste your time. Please give me suggestions on how to improve my code and my skill as a programmer. Thanks.
Edit (previous answer what obviously a too quick response...)
String summat = Integer.toString(modu);
String strConverted = new String();
StringBuffer buff = new StringBuffer(strConverted);
buff.insert(0, summat);
...
System.out.println(strConverted);
Actually, strConverted is still an empty string, maybe you would rather than display buff.toString()
But I don't really understand why making all of this to just display the value of modu. You could just right System.out.println(modu).
I assume that you want to "save" your value and display your whole number in one time and not each digit a time by line.
So you need to store your number outside of while loop else your string would be init at each call of the loop. (and print outside)
So, init your StringBuffer outside of the loop. you don't need to convert your int to String since StringBuffer accept int
http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#insert-int-int-
(You could even use StringBuilder instead of StringBuffer. It work the same except StringBuffer work synchronized
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html)
Your if inside the loop is a specific case (number lower than base) is prevent before the loop since it's the opposite condition of your loop. (BTW : rem <= base-1 and base>danum are actually only one test since rem == danum at this place)
so :
StringBuffer buff = new StringBuffer();
if(base > danum) {
buff.append(danum);
} else {
while (danum / base >= base - 1 && base < danum) {
int rem = danum / base;
int modu = danum % base;
buff.insert(0, modu);
danum = rem;
}
if(danum > 0) {
buff.insert(0, danum);
}
}
System.out.println(buff.toString());
I would also strongly recommand to test your input before running your code. (No Zero for base, no letters etc...)
2 Things
do a lot more error checking after getting user input. It avoids weird 'errors' down the path
Your conversion from int to String inside the loop is wrong. Whats the whole deal summat and buff.... :: modifying the buffer doesnt affect the strConverted (so thats always empty which is what you see)
try to get rid of this. :)
error is logic related
error is java related
Your code has the following problems:
Firstly, you have declared and initialized your strConverted variable (in which you store your result) inside your while loop. Hence whenever the loop repeats, it creates a new string strConverted with a value "". Hence your answer will never be correct.
Secondly, the StringBuffer buff never changes the string strConverted. You have to change your string by actually calling it.
You print your result inside your while loop which prints your step-by-step result after every repetition. You must change the value of strConverted within the loop, nut the end result has to be printed outside it.

Java recursion class variable value is reset to 0

I was trying to implement the coin change problem using recursion. I have written the following code and am facing a problem with the static class variable. 'answer' is a class variable and i am trying to add the return value to it in the loop. This works fine within the while loop but after the while loop ends the answer is reset to 0;
while (i * currentCoin <= sum) {
System.out.println("inside while; answer is " + answer);
answer = answer
+ findCombinations(
sum - i * currentCoin,
new ArrayList<Integer>(denominations.subList(1,
denominations.size())));
i++;
}
Below is all the code that I have written. You can copy and run it to check.
import java.util.ArrayList;
import java.util.Collections;
public class CoinChangeHashMap {
static int answer = 0;
public static void main(String[] args) {
int[] array = new int[] { 7, 3, 2 };
ArrayList<Integer> input = new ArrayList<Integer>();
getList(array, input);
findCombinations(12, input);
System.out.println(answer);
}
private static void getList(int[] array, ArrayList<Integer> input) {
for (int i : array) {
input.add(i);
}
}
public static int findCombinations(int sum, ArrayList<Integer> denominations) {
if (denominations.size() == 1) {
if (sum % denominations.get(0) == 0) {
return 1;
}
return 0;
}
int i = 0;
int currentCoin = denominations.get(0);
while (i * currentCoin <= sum) {
System.out.println("inside while; answer is " + answer);
answer = answer
+ findCombinations(
sum - i * currentCoin,
new ArrayList<Integer>(denominations.subList(1,
denominations.size())));
i++;
}
return 0;
}}
**The output that I get is 0. but the expected output is 4. While debugging the output that I got is **
inside while; answer is 0
inside while; answer is 0
inside while; answer is 1
inside while; answer is 1
inside while; answer is 2
inside while; answer is 2
inside while; answer is 0
inside while; answer is 0
inside while; answer is 0
0
Any Help is appreciated.
The problem is related to your odd code structure, in which you convey the outcome of your recursive call sometimes by modifying static variable answer, and sometimes via the method's return value.
If you analyzed the problem more closely, you would discover that it is not upon exit from the loop that the partial results are lost, but rather some time after return from the method. Therefore, consider carefully the way you update the answer:
answer = answer + findCombinations( /* ... */ );
At the top-most level of your recursion, answer is initially 0. When Java evaluates the above expression, it evaluates first the left operand and then the right operand, then it adds them. That is, it evaluates answer, getting the result 0, before it performs the recursive call. The value of answer may be updated in the course of the recursive call, but those changes come too late. Only the bottom-most level of the recursion ever returns a value different from zero, so if the recursive call itself recurses at least one level deeper then it will return zero. In that case, the sum is computed as 0 + 0, and assigned to answer, clobbering any update the method performed.
You could resolve the problem by swapping the order of the operands in your sum, but it would be better, and not much harder, to get rid of the static variable altogether. Use a local variable within the method to accumulate results, and in all cases convey the total back to the caller via the method's return value.

beginner java, help me fix my program?

I am trying to make a calculator for college gpa's. I cut out all like 20 if statements that just say what each letter grade is. I fixed my first program for anybody looking at this again. The program now works, but regardless of the letters i type in the gpa it returns is a 2.0 . If anybody sees anything wrong it would be very much appreciated...again. Thanks
import java.util.Scanner;
public class universityGPA {
public static void main(String args[]){
int classes = 4;
int units[] = {3, 2, 4, 4};
double[] grade = new double[4];
double[] value= new double[4];
int counter = 0;
double total = 0;
double gpa;
String letter;
while(classes > counter){
Scanner gradeObject = new Scanner(System.in);
letter = gradeObject.next();
if(letter.equalsIgnoreCase("A+") || letter.equalsIgnoreCase("A")){
grade[counter] = 4;
}
if(letter.equalsIgnoreCase("F")){
grade[counter] = 0;
}
value[counter] = grade[counter] * units[counter];
counter++;
}
for(int i = 0; i < classes; i++ ){
total += value[i];
}
gpa = total/classes;
System.out.println("You gpa is " +gpa);
}
}
You forgot to initialize grade. The NullPointerException is telling you that grade is null. The exception is thrown the first time you try to use grade, in the statment grade[counter] = 4;. Allocate as much space as you need with new.
Initialization of grade can be done statically as well dynamically:
double []grade = new double[4];
or
double []grade = new double[classes];
Do the same for value as well.
Here are a few pointers for cleaning up your code:
Try to be more consistent with your formatting. Make sure everything is properly indented and that you don't have lingering spaces at the beginnings or endings of lines (line 18).
You should declare variables as close to the first spot you use them as possible. This, along with making your code much more readable, minimizes the scope. For instance, on line 18, you initialize letter, but it is never used outside the scope of the while statement. You should declare the variable right there, along with the initializer (String letter = gradeObject.next()).
Declaring arrays in the type name[] form is discouraged. It is recommended to use the type[] name form instead.
Try to separate your program into distinguished sections. For instance, for this program, you can clearly see a few steps are involved. Namely, you first must grab some input, then parse it, then calculate the return value. These sections can be factored out into separate methods to clean up the code and promote reuse. While it may not seem to yield many benefits for such a simple program, once you start working on larger problems this organization will be absolutely mandatory.
NullPointerException means you are trying to access something that does not exist.
Since your grade[] is null, accessing it on line 21 by grade[counter] actually means you are accessing something that has yet to be created.
You need to initialize the array, so it actually has an instance.

Categories

Resources