How do I fix my scanner input that is null? - java

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.

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.

Problems with calling a method using an array

I'm relevantly new to Java and just started my first semi serious assignment. I'm confident most of my code is working, the only problem is because I've been using classes I can't seem to call a method which uses an array into my main class. Every other method I want to call seems to work. I wonder if anyone has any explanation or easy solution to this?
Thanks in advance for taking time looking into, really appreciate it!
import java.util.Scanner;
public class GeographyQuizMain
{
public static void main(String[] args)
{
takeQuiz();
}
public static void takeQuiz(Question[][] questions)
{
int score = 0;
RandomNumber randomQuestion = new RandomNumber();
//user chooses catergory
int cat = pickCatergory();
//ask 10 questions
for(int i = 0; i < 10;)
{
Scanner answerChoice = new Scanner(System.in);
randomQuestion.dice();
int q = (randomQuestion.dice() - 1);
//checks to see if question as been asked before
if (!questions[cat][q].beenAsked)
{
questions[cat][q].beenAsked = true; //changes question status to beenAsked
System.out.println(questions[cat][q].promt);
String answer = answerChoice.nextLine();
System.out.println("\nYou picked: " + answer + "\nThe correct answer was: " + questions[cat][q].answer + "\n");
if(answer.equals(questions[cat][q].answer))
{
score++;
}
i++;
}
}
System.out.println("That is the end of the quiz!\n"
+ "You got " + score + "/10");
}
Your problem is with the call itself,
This line public static void takeQuiz(Question[][] questions) states that the method will accept a two dimensional array ([][]) of an object named Question.
On the other hand, your call - takeQuiz(); passes no array of such.
You should initialise an array of such to make this compile and pass it to the function. i.e.
Question[][] questionArray = GenerateQuestionArray(); //you should write this method
takeQuiz(questionArray);
Like you stated, it's clearly you're new to Java and I strongly suggest you to read the instructions and the information provided to you in class about that. I bet the details of Object initialisation, methods and arrays are covered there.
It seems that problem with your method call, in your method takeQuiz(); is taking 2 dimensional array for questions but at the calling time you are not providing that parameter so, compiler not able to found the method.
That's the problem.
try to use like this, this is simple an example for you. replace this with your actual values.
String[][] questions= new String[3][3];
takeQuiz(questions);
this will work.
You have called your method takeQuiz() without actually supplying its arguments Question[][] questions

Extend below program for acute and obtuse angle triangle | using Sine cos functions

so I want to know how to make a program that will ask multiple questions and lead to multiple values or other questions to build on.
So I was building a "missing side of right triangle" program. Successful after a couple tries I wondered why not make the program solve obtuse or acute triangles. Well, I could program the law of sines and cosines. The problem is I don't know how. I learned the basics of java through 2-3 videos off youtube. I tried to make an if-else nested inside an if-else statement. But this is my code I tried to build upon:
import java.util.*;
import java.lang.Math;
public class MissingSide {
static java.util.Scanner userInput = new Scanner(System.in);
public static void main(String[] args){
int firstSideGiven = 0;
int hypotenuseGiven = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("Are you trying to figure out a missing side given the hypotenuse and another side?");
System.out.println("Then this is the place :)");
System.out.print("What is the value of the first side, other than the hypotenuse?");
if (userInput.hasNextInt()) {
firstSideGiven = userInput.nextInt();
}else{
System.out.println("Give me somthing else to work with!");
}
System.out.println("What is your hypotenuse?");
if (userInput.hasNextInt()){
hypotenuseGiven = userInput.nextInt();
}else{
System.out.print("Wait, I want you to think about what you are doing with your life.");
}
System.out.println("Your missing side is: " + (Math.sqrt((Math.pow(hypotenuseGiven, 2)-Math.pow(firstSideGiven, 2)))));
}
}
And now I want to know what to do next, when I attempted to nest everything inside another if statement, it gave me an error I did not understand.
Well It would be great if you can share the problem and/or errors faced during the change.
Here is a basic logic to solve your issue -
You can use Math.cos and Math.sin functions to calculate function value.
These values can be used to calculate the missing side.
Note - Above functions accept value in radian, So change your degree value to radian before usage. i.e. -
double angleInDegree = 354;
double angleInRadian = Math.toRadians(angleInDegree);
double cos = Math.cos(angleInRadian);
Hope it helps. :)

How to make cards in array?

public void readFile() {
while (x.hasNext()) {
try {
String name = x.next();
int magic = x.nextInt();
int cunning = x.nextInt();
int courage = x.nextInt();
int wisdom = x.nextInt();
int temper = x.nextInt();
Card card = new Card(name, magic, cunning, courage, wisdom, temper);
for(int i=0;i<cardArray.length;i++){
cardArray[card];}
} catch (Exception e) {
}
}
}
I'm just making this code reading attribute from text file. The problem is how to gather all cards in one array? I try but it's not working.
I highly advise you to go thorough the basic tutorial. See the Arrays section and read it carefully.
You should assign the card this way:
cardArray[i] = card;
Note that you're using the same Card object in the loop, you'll end up with array full of the same card. Is this what you want? If not, you should create a new instance on each iteration.
Also please note that it's not a good practice to catch an exception and do nothing with it. The least you should do is print it to the console, otherwise you might get silent errors.
More questions you should ask yourself:
Do you want to declare the variables inside the while loop?
Is it worth to make a custom class that wraps magic, wisdom and all other variables? I think your code will be more modular and readable.
The full tutorial is available here, it's really worth reading. Give it a try!

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