beginner java, help me fix my program? - java

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.

Related

Using Scanner to scan through a predefined list of strings in another class, and parse them to Ints in java

Quite a few labs have passed since my previous request for some advice and we are nearing midterms quite quickly! I am currently working on another lab right now and have ran into some slight difficulty that a little advice or guidance might help! Anyways here is whats going on!
I must have 3 classes in total:
(StationRecordMain, StationRecord, and TemperatureData)
He gave us the TemperatureData class pre-written and not able to modify it in anyway. This class holds a huge array of Strings all looking like this
"14762 20180829 89 70 80 9.6" . These are some junk number in the beginning we must throw away, the year month and day, the high temp, the low temp, avg, and difference.
This prewritten class also holds 2 methods in it, (hasNextTempRecord, getNextTempRecord).
My StationRecord class holds the following instance variables:
private int yearMonthDay = 0;
private int max = 0;
private int min = 0;
private int avg = 0;
private double dif = 0;
Finally, my MainStationRecord class holds the Scanner Object:
Scanner scan = new Scanner(tempdata.getNextTempRecord());
, an attempt to use the scanner to read through the predefined strings in the other class.
Anyways, I can supply more code that I have written but didnt want to flood this page with all of it, but those are the basics. I believe I am at a points where I know what I need to do, just need some guidance.
I need to use the Scanner to scan through all of those Strings on the other class (there are like 100 of them, so i'm assuming some sort of loop somewhere)
Then, I need to piece out each one of those strings and store their values in those private instance variables. Finally parsing them to ints and printing them out in the main class. That is where I am lost. Ive never used a scanner in such a way to do a preset of defined strings in a different class, moreover I have no experience on how to chop them up or parse them really.
Thus, if anyone could guide me in the right direction, It would be greatly appreciated! As I said before I can post the rest of my code I have written to make things easier if need be!
Until then thank you for looking!
I think if I understand it, You can easily do something like this: (I don't have complete code of yours, so this is just a suggestion)
class StationRecord {
private int yearMonthDay = 0;
private int max = 0;
private int min = 0;
private int avg = 0;
private double dif = 0;
public StationRecord(int yearMonthDay, int max, int min, int avg, double dif) {
this.yearMonthDay = yearMonthDay;
this.max = max;
this.min = min;
this.avg = avg;
this.dif = dif;
}
// rest of your code
}
public class Main
{
public static void main(String[] args) {
// rest of your codes
while (tempdata.hasNextTempRecord()) {
Scanner scan = new Scanner(tempdata.getNextTempRecord());
scan.next(); // read until a space and I don't save it for throw it away
new StationRecord(scan.nextInt(), scan.nextInt(), scan.nextInt(), scan.nextInt(), scan.nextDouble());
}
// rest of your codes
}
}
Thanks Andreas for comments too. This is what I understand and write it.

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 Method Call Array

How do I pass an array from my main method to another method? I'm having an error with the parameters. Do I use the return value from main? And since the return value from main is an array, should the parameters for the call of main have brackets? Should there be a value between those brackets?
public class arraysAndMethods {
public void printArray(double[] arr) {
int x = arraysAndMethods.main(double[i] arr);//error with paremeters
for (int i = 0; i < studGrades.lenght; i++)
System.out.print(studGrades[i] + " ");
}// end of printArray method
public static double[] main(String args[]){// double array
java.util.Scanner input = new java.util.Scanner(System.in); // input scanner
System.out.println("What is the size of the class?");
int n = input.nextInt();
double[] arr = new double[n];// declare and initialize array to have n many elements
for (int i = 0; i < arr.length;i++) {// input grades for each students
System.out.println("What is the grade of student #" + (i+1));
arr[i] = input.nextDouble();
} // end of for loop
return arr;
}// end of main method
}// end of class
Just pass the name, not the type.
int x = arraysAndMethods.main(arr);
EDIT:
Besides that, your code shows a few other problems.
main(...) is the entry point to your application. It doesn't make sense to call main(...) from the other method. It should be the other way around.
main(...) HAS TO have the following signature: public static void main(String[] args). You cannot declare it to return an array of double.
This whole thing doesn't make much sense. If you're hoping to have this as the main method of a Java program, this won't work because the main method must have a void return type. Regardless, you have a syntax error here:
int x = arraysAndMethods.main(double[i] arr);//error with paremeters
Instead it should be
int x = arraysAndMethods.main(arr);//error with paremeters
as the variable has already been declared. I'm not sure what you were trying to do with double[i], but that syntax is more like a declaration, i.e.
double[] someArrayName = new double[5];
Your main method is where the program begins execution. In other words you should be calling printArray() from within main, not the other way around
I think I see where the confusion is. Perhaps this will help.
First I think you should understand something very important about Java.
Your main method is the FIRST method that is run.
So let's give a short walk through of how a Java program is created without an IDE.
First, you write your code in a text file and rename it to arraysAndMethods.java when you're done. Next we need to take your code and put it into a form that is usable by the computer it is first compiled down to bytecode with the following from the command line:javac arraysAndMethods.java
After it is compiled you can run the program with this command: java arraysAndMethods
Your program will run if there are no problems.
You say that you want to pass variables things into the main method? Here is how you do that from the command line: java arraysAndMethods 45.6 38.2 5.5 105.3
Looking at your main method, it takes the following arguments: (String args[])
So in your case, the 45.6 38.2 5.5 105.3 would be passed into your main method as an array of strings. With the first entry being 45.6, followed by 38.2, then 5.5 and finally 105.3.
It would look like this in the array: ["45.6"],["38.2"],["5.5"],["105.3"] but they are all Strings and not doubles.
All of this is to say that if you want to pass something in to your main method, you'll either need to do it through the command line, or look up how your individual IDE (i.e. Eclipse, Netbeans, etc.) handles that.
So to recap: The parameters in the main method are coming in from the console unless other specifications are made, and in your case it is returning an array of type double.
I know this is quite verbose, but bear with me, I'm almost done.
When a Java program is run(I'm simplifying a bit here), it comes into the main method and executes the first line it sees. When it's done with that one, it goes onto the next line, and so forth until it gets to the end of the main method. Then the program is done.
So everything MUST be done in the main method. Although you can call other Classes and methods from the main method.
Now that you have the explanation, here is what I would do to fix your code:
public class arraysAndMethods {//Changed from arraysAndMethods to ArraysAndMethods because classes are always capitalized
public static void printArray(double[] arr) {//Added static so this could be used within the same class as the main method.
//int x = arraysAndMethods.main(double[i] arr); No need for this line
for (int i = 0; i < arr.length; i++)// Changed "studGrades.lenght" to arr.length
System.out.print(arr[i] + " ");//Changed "studGrades" to arr
}// end of printArray method
public static void main(String args[]){// Changed the return type to "void". No need to return the double array.
java.util.Scanner input = new java.util.Scanner(System.in); // input scanner
System.out.println("What is the size of the class?");
int n = input.nextInt();
double[] arr = new double[n];// declare and initialize array to have n many elements
for (int i = 0; i < arr.length;i++) {// input grades for each students
System.out.println("What is the grade of student #" + (i+1));
arr[i] = input.nextDouble();
} // end of for loop
printArray(arr);
//return arr; No need for this line
}// end of main method
}// end of class
Please be sure to mark the best answer when you're ready and up-vote any answers or comments you feel helped. Not just for this question, where you are the original poster, but for other question threads as well.

How do I fix my scanner input that is null?

Hi I am new at java programming and ran into a problem on my latest project. I am making a score generator for bowling and finished the code, except when I went to test it, it said
"Exception in thread "main" java.lang.NullPointerException
at Bowling_Score.main(Bowling_Score.java:34)"
I tried everything to fix it, and looked through tons of websites, but no solutions solved my problem. It's probably something really easy to fix, but I can't seem to find the answer. The line that has the problem is the second line here.
System.out.println("Frame 1, Throw 1");
Frame1Throw1 = sc.nextInt();
This is the only way I know how to use a scanner with variables, so if there is a better way please tell me. It also may be a problem because the variable Frame1Throw1 is the first variable on the list.
The variable is correct, and my scanner's name is sc
Please be specific with your answer, because as I said, I am new at java, and am just learning the basics now. This is my first big project.
Thank You!
P.S. I use eclipse to code I don't know if that matters or not
* I got one answer, and it was helpful, but It didn't work. Here is some more of the beginning of the code which may be helpful in answering.
import java.util.Scanner;
public class Bowling_Score {
private static Scanner sc;
public static void main(String[] args) {
//All Variables
int Frame1Throw1 = 0;
int Frame1Throw2 = 0;
int Frame2Throw1 = 0;
int Frame2Throw2 = 0;
int Frame3Throw1 = 0;
int Frame3Throw2 = 0;
int Frame4Throw1 = 0;
//Then I have one variable for each throw of the game, and one for the final total score.
//Directions
System.out.println("To put in your score, put the number of pins you knocked down in the throw specified. If you get a strike, enter a 10 in the first throw of the frame and a 0 in the second throw of the frame. If you get a spare, Ener a 0 in the first throw of the frame and 10 in the second throw of the frame.");
//Frame 1
System.out.println("Frame 1, Throw 1");
Frame1Throw1 = sc.nextInt();
if (Frame1Throw1 == 10){
Frame1Throw1 = Frame1Throw1 + Frame2Throw1 + Frame2Throw2;
Frame1Throw2 = 0; }
A NullPointerException means that the object you are referencing hasn't been initialised. So in this case I imagine that your sc hasn't been created previously in your code.
Look for something like
Scanner sc;
and change it to
Scanner sc = new Scanner(System.in);
Otherwise it could be a scope problem (you created the object somewhere that can't be seen by that method) you'll need to provide more code if the first solution doesn't work.

For Loop Not Terminating

I'm trying to get back into Java - it's been about 5 years since I studied the basics and I've been lost in the .Net world since.
I'm trying to create a student class below, however the for loop for reading in the integers into the array gets stuck when the program runs.
From my previous knowledge, and from research, the loop seems to be constructed properly and I can't seem to figure out where it's going wrong.
I'm sure it's something silly - as always but I was wondering if someone could point me in the right direction? :)
import java.util.*;
import acm.io.*;
public class Student {
// instance variables
private int studNumber; //Must be between (and including) 0 and 99999999. If input value invalid default to 0.
private String studName;
private int marks[];
/*
* Constructor Student Class
*/
public Student(int studNumber, String StudName, int marks[]) {
// initialise instance variables
if (studNumber >=0 && studNumber<= 99999999) {
this.studNumber= studNumber;
} else {
this.studNumber = 0; //default value
}
this.studName= StudName; // no validation
this.marks = marks;
IOConsole console = new IOConsole();
for (int i = 0; i <= 6; i++) {
marks[i] = console.readInt();
}
}
}
I think that the problem lies here:
for (int i = 0; i <= 6; i++)
{
marks[i] = console.readInt();
}
The only instance where I found a reference to IOConsole was here and it does not seem to be something which is part of the standard Java framework.
If you just need to scan numbers from console, you can use the Scanner class and the use the nextInt() method like below:
Scanner input = new Scanner(System.in);
for (int i = 0; i <= 6; i++)
{
marks[i] = input.nextInt();
}
The loop seems correct. Is it possible the console.readInt() call is blocking, which keeps you stuck in the loop (the IOConsole class is not part of the standard JDK, and I am not familiar with it)
readInt() is waiting for user input
from http://jtf.acm.org/javadoc/student/acm/io/IOConsole.html#readInt%28%29:
Reads and returns an integer value from the user
The problem is with console.readInt(), where another non-stop loop is executing or some other problem with that method
I believe the problem lies in the readInt() part. It's unusual to read input from the Console in a constructor for initializing the attributes, delegate that task to another part of your code and move it outside the constructor.

Categories

Resources