I'm trying to understand the different parts of the code but I need to ask for individual help at this point. So here's my issue: I'm building a simple grade average program for my first java programming class. I want to save 4 grade inputs, then display an average. Eventually I am going to display letter grades based on that average. I think this error is saying I am not initializing finalGrade.
But I'm lost. An explanation of what is happening would be great so I can actually learn this.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class GradeAverage{
public static Double gradeQ1; //gradeQ are grades for the respective quarters
public static Double gradeQ2;
public static Double gradeQ3;
public static Double gradeQ4;
public static String studentName;
public static Double finalGrade = ((gradeQ1 + gradeQ2 + gradeQ3 + gradeQ4) / 4);
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
studentName = JOptionPane.showInputDialog(null, "Please enter your first and last name.");
JOptionPane.showMessageDialog(null, "Thanks " + studentName + ", let's get started!");
gradeQ1 = Double.parseDouble(JOptionPane.showInputDialog(null, "What was your grade in the first quarter?")); // gets grade and saves it as a double gradeQ1
JOptionPane.showMessageDialog(null, "You entered " + gradeQ1);
//double gradeQ1 = input.nextDouble();
gradeQ2 = Double.parseDouble(JOptionPane.showInputDialog(null, "What was your grade in the second quarter?"));
JOptionPane.showMessageDialog(null, "You entered " + gradeQ2);
gradeQ3 = Double.parseDouble(JOptionPane.showInputDialog(null, "What was your grade in the third quarter?"));
JOptionPane.showMessageDialog(null, "You entered " + gradeQ3);
gradeQ4 = Double.parseDouble(JOptionPane.showInputDialog(null, "What was your grade in the fourth quarter?"));
JOptionPane.showMessageDialog(null, "You entered " + gradeQ4);
JOptionPane.showMessageDialog(null, "Thanks " + studentName + ", Your average was " + finalGrade);
}
}
JGRASP error:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at GradeAverage.<clinit>(GradeAverage.java:15)
Your program fail on:
public static Double finalGrade = ((gradeQ1 + gradeQ2 + gradeQ3 + gradeQ4) / 4);
because grade* are object and they haven't got initialization. The program could work only in case you use double instead Double. The different is that the first isn't an object and its default value is 0.0 , while Double is an object with default value null. This create the nullPointerException.
Second your finalGrade will be 0, you must before read the value and then set the finalGrade's value.
...
JOptionPane.showMessageDialog(null, "You entered " + gradeQ4);
finalGrade = ((gradeQ1 + gradeQ2 + gradeQ3 + gradeQ4) / 4);
JOptionPane.showMessageDialog(null, "Thanks " + studentName + ", Your average was " + finalGrade);
Related
I've been trying to figure the problem in my code for hours is there any way to solve this? If so please help me fix this problem. It runs but the code inside while doesn't work the way it is intended to even though the condition make sense or I just don't know how while works??? Anyways, thank you for the people that will help. That's all the details
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
//imported JoptionPane for a basic UI
//Don't mind the comments
public class Calculator {
public static void main(String[] args) {
DecimalFormat format = new DecimalFormat("0.#####");
//Used this class to trim the zeroes in whole numbers and in the numbers with a trailing zero
String[] response = {"CANCEL", "Addition", "Subtraction", "Multiplication", "Division", "Modulo"};
//Used array to assign reponses in the response variable(will be used in the showOptionDialog())
//CANCEL is 0, Addition is 1, Subtraction is 2 and so on. Will be used later in switch statement
int selectCalculation = JOptionPane.showOptionDialog(null,
"SELECT CALCULATION THAT YOU WANT TO PERFORM:",
"SELECT CALCULATION",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
response,
null);
String numberInput1 = JOptionPane.showInputDialog(null, "ENTER THE FIRST NUMBER:");
//Used the class String instead of the data type double because I will be using a String method in while condition
while (numberInput1.matches("[a-zA-Z]"))
//Used regex here basically saying if numberInput1 does contain letter then start the loop until user inputs number
{
JOptionPane.showMessageDialog(null, "Make sure to enter numbers ONLY", "INVALID", JOptionPane.WARNING_MESSAGE);
//Shows warning message so user will know what the accepted input is
numberInput1 = JOptionPane.showInputDialog(null, "ENTER THE FIRST NUMBER:");
}
String numberInput2 = JOptionPane.showInputDialog(null, "ENTER THE SECOND NUMBER:");
//Same reason as stated previously
while (numberInput2.matches("[a-zA-Z]")) {
JOptionPane.showMessageDialog(null, "Make sure to enter numbers ONLY", "INVALID", JOptionPane.WARNING_MESSAGE);
numberInput2 = JOptionPane.showInputDialog(null, "ENTER THE SECOND NUMBER:");
}
double firstNumber = Double.parseDouble(numberInput1);
double secondNumber = Double.parseDouble(numberInput2);
//Converts the numberInputs to double so Java will add numbers instead of String later
switch (selectCalculation)
//Used switches instead of if else because it will be a longer process if I used if else
{
case 1:
double sum = firstNumber + secondNumber;
JOptionPane.showMessageDialog(null, format.format(firstNumber) + " and " + format.format(secondNumber) + " is equals to " + format.format(sum), "The sum of:", JOptionPane.INFORMATION_MESSAGE);
break;
case 2:
double difference = firstNumber - secondNumber;
JOptionPane.showMessageDialog(null, format.format(firstNumber) + " and " + format.format(secondNumber) + " is equals to " + format.format(difference), "The difference of:", JOptionPane.INFORMATION_MESSAGE);
break;
case 3:
double product = firstNumber * secondNumber;
JOptionPane.showMessageDialog(null, format.format(firstNumber) + " and " + format.format(secondNumber) + " is equals to " + format.format(product), "The product of:", JOptionPane.INFORMATION_MESSAGE);
break;
case 4:
double quotient = firstNumber / secondNumber;
JOptionPane.showMessageDialog(null, format.format(firstNumber) + " and " + format.format(secondNumber) + " is equals to " + format.format(quotient), "The quotient of:", JOptionPane.INFORMATION_MESSAGE);
break;
case 5:
double remainder = firstNumber % secondNumber;
JOptionPane.showMessageDialog(null, format.format(firstNumber) + " and " + format.format(secondNumber) + " is equals to " + format.format(remainder), "The remainder of:", JOptionPane.INFORMATION_MESSAGE);
break;
default:
JOptionPane.showMessageDialog(null, "MADE BY: GABRIEL POTAZO", "CALCULATION CANCELLED",JOptionPane.ERROR_MESSAGE);
break;
}
}
}
Hi your question was unclear in many places, but I believe you just need to validate the input value to have only numbers/alphabets/alpha-numeric.
String numberInput1 = JOptionPane.showInputDialog(null, "ENTER THE FIRST NUMBER:");
//If its not Numbers matching
if (!Pattern.matches("[0-9]*", numberInput1)){
JOptionPane.showMessageDialog(null, "Make sure to enter numbers ONLY", "INVALID", JOptionPane.WARNING_MESSAGE);
//Clear your Input Box
}
For Matching Only Alphabets
Pattern.matches("[a-zA-Z]*", numberInput1)
For matching alphanumeric
Pattern.matches("[a-zA-Z0-9]*", numberInput1)
I'm not convinced validating with Loops, but I recommend checking out the Swing tutorial on Dialogs, and how to use JOptionPane easily so you don't need to validate the input.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I copy and paste this code into my Intellij and the result came out with the system does not allow the user to answer(input) the question "What is the three-letter currency symbol of your destination?" and it directly skip to the next question. May i know what is the issues and what is the solutions? Thank you for your teaching first.
This code I get from the link for my practice and study for Java : How to fix the error <identifier> expected?
package com.Test3;
import java.util.Scanner;
public class Example1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
intro(input);
time(input);
}
public static void intro(Scanner input) {
System.out.println("Welcome");
System.out.println("What is your name");
String name = input.nextLine();
System.out.println("Nice to meet you, " + name + " where are you travelling to?");
String dest = input.nextLine();
System.out.println("Great! " + dest + " sounds like a great trip");
}
public static void time(Scanner input) {
int hours, minutes;
float perd, perdc, change;
System.out.println("How many days are you going to spend travelling?");
int days = input.nextInt();
hours = days * 24;
minutes = hours * 60;
System.out.println("How much money in USD are you going to spend?");
float money = input.nextFloat();
perd = money / days;
System.out.println("What is the three letter currency symbol of your destination?");
String curr = input.nextLine();
System.out.println("How many " + curr + " are there in 1USD?");
float ex = input.nextFloat();
change = money * ex;
perdc = perd * ex;
System.out.println("If you are travelling for " + days + " that is the same as " + hours + " or " + minutes + " minutes");
System.out.println("If you are going to spend " + money + " $USD that means per day you can spend upto $" + perd + " USD");
System.out.println("Your total budget in " + ex + " is " + change + ex + " ,which per day is " + perdc + curr);
}
}
Do not use nextLine. It does what the docs say it does, but it's not what you want, hence, 'broken'.
Instead, properly configure your scanner; after making it, invoke: scanner.useDelimiter("\\R"); (which tells the scanner that tokens are separated by newlines), and use .next() to read a line of text.
I am very new to java and am trying to learn how to program it while working remotely which is very difficult for me. The assignment is to create an "ingredient" class that will ask for ingredients, validate the input, and then at the end print a list of ingredients. I have written and re-written this code about a dozen times and it never prints out correctly. It takes one too many loops through to get a correct output, and when the values stored in the variables during the execution print out incorrectly. This group is my last ditch effort as I am struggling so hard even though I'm putting in the work! Thanks again and take care.
package Stepping_Stones_Lab_2;
import java.util.Scanner;
import java.util.ArrayList;
public class MilestoneOne {
/**
*
*/
public static void main(String[] args) {
ArrayList<String> ingredientList = new ArrayList();
ArrayList<String> recipeList = new ArrayList();
//variable declaration
double ingredientAmount = 0.0;
double totalCalories = 0.0;
int numberCaloriesPerUnit = 0;
String recipeName;
String nameOfIngredient;
String unitMeasurement;
Scanner scnr = new Scanner(System.in);
boolean addMoreIngredients = true;
//recipie creation
System.out.print("Please enter your new recipe name: ");
recipeName = scnr.nextLine();
recipeList.add(recipeName);
//This do-while loop is requesting ingredients until such time the user terminates the requests by typing n. If neither y or n is
//used the program will return an Invalid value error
do {
System.out.print("Would you like to enter an ingredient: (y or n): ");
String reply = scnr.next().toLowerCase();
scnr.nextLine();
//the notes says use a switch but I have not been able to get a switch to work successfully despite many tries.
if(reply.equals("y")) {
System.out.print("Enter ingredient name: ");
nameOfIngredient = scnr.nextLine();
while (!nameOfIngredient.matches("[a-zA-Z_]+")){ //Validates input and loops until there is acceptable input for name
System.out.print("Error: Please enter valid name of ingredient: ");
nameOfIngredient = scnr.next();
}
ingredientList.add(nameOfIngredient);
System.out.println("Good job! The ingredient you entered is " + nameOfIngredient);
//Unit of measurement input and data validation
System.out.print("Please enter the unit of measurement (cups, ounces, etc.): ");
unitMeasurement = scnr.next();
while (!unitMeasurement.matches("[a-zA-Z_]+")){ //Validates input and loops until there is acceptable input for unit measurement
System.out.print("Error: Please enter valid unit of measurement: ");
unitMeasurement = scnr.next();
}
System.out.println("Good job! The unit of measurement for " + nameOfIngredient + " is " + unitMeasurement);
//Amount of ingredient input and data validation
System.out.print("Please enter the number of " + unitMeasurement + " of " + nameOfIngredient + " we'll need: ");
while (!scnr.hasNextDouble()){//Validates input and loops until there is acceptable input for amount
System.out.print("Error: Please enter the number of " + unitMeasurement + " of " + nameOfIngredient + " we'll need using numbers only: ");
scnr.next();
}
ingredientAmount = scnr.nextDouble();
System.out.println("Good job! The number of " + unitMeasurement + " of " + nameOfIngredient + " needs is " + ingredientAmount);
//Number of calories per cup of ingredient input and data validation
System.out.print("Please enter the number of calories per " + unitMeasurement + " of " + nameOfIngredient + ": ");
while (!scnr.hasNextInt()){
System.out.print("Please enter the number of calories per " + unitMeasurement + " of " + nameOfIngredient + " using numbers only: ");
scnr.next();
}
numberCaloriesPerUnit = scnr.nextInt();
System.out.println("Good job! The number of calories per " + unitMeasurement + " of " + nameOfIngredient + " is " + numberCaloriesPerUnit);
totalCalories = ingredientAmount * numberCaloriesPerUnit;
System.out.println(recipeName + " uses " + ingredientAmount + " " + unitMeasurement + " and has " + totalCalories + " calories.");
}
else if(reply.equals("n")){
addMoreIngredients = false;
System.out.println("Your ingredients for " + recipeName + " are as follows: ");
}
else {
System.out.println("Invalid value!!");
}
}
while (addMoreIngredients);
for (int i = 0; i < ingredientList.size(); i++) {
String ingredient = ingredientList.get(i);
System.out.println(ingredient);
}
}
}
It works for me. Look at the following transcript.
Please enter your new recipe name: recipe name
Would you like to enter an ingredient: (y or n): y
Enter ingredient name: a
Good job! The ingredient you entered is a
Please enter the unit of measurement (cups, ounces, etc.): b
Good job! The unit of measurement for a is b
Please enter the number of b of a we'll need: 2
Good job! The number of b of a needs is 2.0
Please enter the number of calories per b of a: 3
Good job! The number of calories per b of a is 3
recipe name uses 2.0 b and has 6.0 calories.
Would you like to enter an ingredient: (y or n): y
Enter ingredient name: a2
Error: Please enter valid name of ingredient: aa
Good job! The ingredient you entered is aa
Please enter the unit of measurement (cups, ounces, etc.): bb
Good job! The unit of measurement for aa is bb
Please enter the number of bb of aa we'll need: 4
Good job! The number of bb of aa needs is 4.0
Please enter the number of calories per bb of aa: 8
Good job! The number of calories per bb of aa is 8
recipe name uses 4.0 bb and has 32.0 calories.
Would you like to enter an ingredient: (y or n): n
Your ingredients for recipe name are as follows:
a
aa
I'm really new to java and i'm taking an introductory class to computer science. I need to know how to Prompt the user to user for two values, declare and define 2 variables to store the integers, and then be able to read the values in, and finally print the values out. But im pretty lost and i dont even know how to start i spent a whole day trying.. I really need some help/guidance. I need to do that for integers, decimal numbers and strings. Can someone help me?
this is what ive tried
import java.util.Scanner;
class VariableExample
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer value");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println("Please enter an integer value");
double c = scan.nextDouble();
double d = scan.nextDouble();
System.out.println("Please enter an integer value");
string e = scan.next();
string f = scan.next();
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
}
i told you... im really new
You forgot to declare entry point i.e. main() method, String S should be capital and in System.out.println() you used wrong variables:
class VariableExample {
public static void main(String... args) { // Entry point..
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer value");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println("Please enter an integer value");
double c = scan.nextDouble();
double d = scan.nextDouble();
System.out.println("Please enter an integer value");
String e = scan.next(); // String S should be capital..
String f = scan.next();
System.out.println("Your integer is: " + a + " " + b + ", your real number is: " + c + " " + d
+ " and your string is: " + e + " " + f); // here you used wrong variables
}
}
If still your problem not clear then let me know where you actually stuck.
There are a couple of issues.
(1) You need to declare an "entry" point for your program. In Java, you must create a method with the exact signature:
public static void main(String args) {
// Your code here
}
(2) The "string" type in Java is capitalized.
(3) You are referencing variables that have been neither declared nor defined:
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
In this case, you've never told Java what the value of intValue, etc is. It seems like you want to use the variables you have declared and defined like:
System.out.println("Your integer is: " + a + ", your real number is: "
+ c + " and your string is: " + e);
(4) It looks like you're reading in two sets of variables for each prompt. Based on your prompt "Please enter an...", you really are expecting one input.
Altogether, I think your code should look like this:
class VariableExample {
public static void main(String args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer value: ");
int a = scan.nextInt();
System.out.println("Please enter a double value: ");
double c = scan.nextDouble();
System.out.println("Please enter a string: ");
String e = scan.next();
System.out.println("Your integer is: " + a + ", your real number is: "
+ c + " and your string is: " + e);
}
}
import java.util.Scanner;
public class RentalDemo
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
String cnumber;
String outnumber;
Rental first=new Rental();
System.out.print("Enter the contract number: ");
cnumber = input.next();
first.setContractNumber(cnumber);
outnumber=first.getContractNumber();
System.out.println("The contract number is: "+outnumber);
Rental Hours = new Rental();
double Hourss = Hours.getHours();
Rental Minutes = new Rental();
double Minutess = Minutes.getMinutes();
SammysRentalPriceWithMethods motto = new SammysRentalPriceWithMethods();
motto.companyMotto();
}
****public static void AlmostThere(double Minutess, double Hourss)
{ double Total_Cost = Hourss * 40 + Minutess;
System.out.println("You rented our equipment for " + Hourss + "complete hours and "+ Minutess + " extra minutes!");
System.out.println("The total cost of a " + Hourss + " hour rental, with " + Minutess + "extra minutes is " + Total_Cost + "at a $40 rate/hr with a $1 rate/extramin!");**
}
This last section here is the part that isn't printing out when I run it, any ideas why? I'm sorry if I wasn't thorough,** I was expecting it to take the correct numbers and show it to the reader but it just gets through the Main method and stops.
You're never calling the AlmostThere() method. That's what's going to print out everything for you.
At the end of your main() method do something like:
AlmostThere(Hourss, Minutess);
You need to call the AlmostThere method or it will never be run.
Try adding
AlmostThere(Minutess,Hourss);
at the end of your Main method.
Its because you are not calling the method AlmostThere. Any method after the main method has to be called in order for you to see the output.
For example, to call you method you could write.
AlmostThere(45.0, 7.0));