This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
// Inventory.java part 1
// this program is to calculate the value of the inventory of the Electronics Department's cameras
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Inventory
{
public void main(String[] args)
{
// create Scanner to obtain input from the command window
Scanner input = new Scanner (System.in);
int itemNumber; // first number to multiply
int itemStock; // second number to multiply
double itemPrice; //
double totalValue; // product of number1 and number2
while(true){ // infinite loop
// make new Camera object
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
System.out.print("Enter Department name: "); //prompt
String itemDept = input.nextLine(); // read name from user
if(itemDept.equals("stop")) // exit the loop
break;
while(true){
System.out.print("Enter item name: "); // prompt
String name = input.nextLine(); // read first number from user
input.nextLine();
if(name != ("camera"))
System.out.print("Enter valid item name:"); // prompt
name = input.nextLine(); // read first number from user
input.nextLine();
break;
}
System.out.print("Enter number of items on hand: "); // prompt
itemStock = input.nextInt(); // read first number from user
input.nextLine();
while( itemStock <= -1){
System.out.print("Enter positive number of items on hand:"); // prompt
itemStock = input.nextInt(); // read first number from user
input.nextLine();
} /* while statement with the condition that negative numbers are entered
user is prompted to enter a positive number */
System.out.print("Enter item Price: "); // prompt
itemPrice = input.nextDouble(); // read second number from user
input.nextLine();
while( itemPrice <= -1){
System.out.print("Enter positive number for item price:"); // prompt
itemPrice = input.nextDouble(); // read first number from user
input.nextLine();
} /* while statement with the condition that negative numbers are entered
user is prompted to enter a positive number */
totalValue = itemStock * itemPrice; // multiply numbers
System.out.println("Department name:" + itemDept); // display Department name
System.out.println("Item number: " + camera.getItemNumber()); //display Item number
System.out.println("Product name:" + camera.getName()); // display the item
System.out.println("Quantity: " + camera.getItemStock());
System.out.println("Price per unit" + camera.getItemPrice());
System.out.printf("Total value is: $%.2f\n", camera.getTotalValue()); // display product
} // end while method
} // end method main
}/* end class Inventory */
class Cam{
private String name;
private int itemNumber;
private int itemStock;
private double itemPrice;
private String deptName;
private Cam(String name, int itemNumber, int itemStock, double itemPrice, double totalValue) {
this.name = name;
this.itemNumber = itemNumber;
this.itemStock = itemStock;
this.itemPrice = itemPrice;
this.totalValue = totalValue;
}
public String getName(){
return name;
}
public double getTotalValue(){
return itemStock * itemPrice;
}
public int getItemNumber(){
return itemNumber;
}
public int getItemStock(){
return itemStock;
}
public double getItemPrice(){
return itemPrice;
}
}
This is the output when I try to compile this code:
C:\Java>javac Inventory.java
Inventory.java:25: error: cannot find symbol
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
^
symbol: variable name
location: class Inventory
Inventory.java:98: error: cannot find symbol
this.totalValue = totalValue;
^
symbol: variable totalValue
2 errors
I don't understand why I keep getting these errors. I feel like I am close to finishing the problem, but find that I need help getting over this bit of the problem.
Okay, I have made a few changes, but now I get these errors:
C:\Java>javac Inventory.java
Inventory.java:68: error: variable itemNumber might not have been initialized
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
^
Inventory.java:68: error: variable totalValue might not have been initialized
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
^
2 errors
You have declared a variable totalValue inside the main function of the Inventory class. It is not available for class Cam as an instance (this) variable.
Your missing declaration for the variable name in main.
// create Scanner to obtain input from the command window
Scanner input = new Scanner (System.in);
String name; //missing declaration
int itemNumber; // first number to multiply
int itemStock; // second number to multiply
double itemPrice; //
double totalValue; // product of number1 and number2
Also:
class Cam{
private String name;
private int itemNumber;
private int itemStock;
private double itemPrice;
private String deptName;
private double totalValue; //missing field
private Cam(String name, int itemNumber, int itemStock, double itemPrice, double totalValue) {
The constructor is private.
Your are also missing static in your main method.
The two errors are pretty simple:
First:
Inventory.java:25: error: cannot find symbol
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
^
symbol: variable name
location: class Inventory
This sais it cannot find the variable called name, which is true. There is no name variable in the scope when you try to construct the Cam. We know you have a name variable a bit further, but that does not work, because the variable isn't in the scope of the newstatement.
Second:
Inventory.java:98: error: cannot find symbol
this.totalValue = totalValue;
^
symbol: variable totalValue
It sais it can't find a value called totalValue in the Cam class, which is true as well. Check out the member list of Cam and you will see that there is no totalValue. I guess you want to remove it from the constructor, because you are calculating total value depending on itemStock and itemPrice.
Notes:
If you solved this, (and probably more compilation errors) you will notice that your application will compile, but not run. This is because of you forget to declare your main-method static.
If you have solved this you will notice that all the Cam objects you constructed, will contain the data you entered for the previous Cam. This is because of you are constructing the Cam before prompting the data. You started good: Declare fields for the data you want to prompt. When the user entered all the data of one Camera, construct the Camera.
There are two classes in your file
Inventory
Cam
You need to define
variable name in Class Inventory
variable totalValue in Class Cam
Also your in Inventory.java the call to Cam constructor seems to be at a wrong place, you might want to make it the last line of While loop
Related
This part of code is not in a function as I am declaring all values before they can get used by future functions.
Here is a snippet that I'm struggling with
validate if user input is correct
if (userinput.equals(x.indexOf("1234")) && userinput.equals(pinA.indexOf("1223")) ){
{System.out.println(x);
int bal = 500;
System.out.println("your balance is: " + bal);
MainMenu();
}
// that if statement is giving me errors
//here is my variable declaration
public class SimpleBankingApp {
//declare the pins
String pinA = "1223";
int pinB = 1227;
int pinC = 7643;
int pinD = 8554;
// have the users details in strings
public String x = "1234 500";
public String b = "3546 50000";
public String d = "4253 6000";
public String t = "7722 804";
//get user input from user
static {System.out.println("enter your choice");}
Scanner a = new Scanner(System.in);
String userinput = a.nextLine();
if (userinput.equals(x.indexOf("1234")) && userinput.equals(pinA.indexOf("1223")) ){
{System.out.println(x);
int bal = 500;
System.out.println("your balance is: " + bal);
MainMenu();
}
By the declaration of the pins, I tested to see if a string variable would work hence why one of them is a string
You don't need to use indexOf() here. Just use equals like this userinput.equals(pinA), also use "or"(||) instead of "and"(&&) in your if condition or use 2 user inputs if you want to compare 2 separate fields, because 1 field can't be equals to 2 different strings
I'm self-teaching myself Java and came across this question.
It required the making of multiple methods and also taking user data and making it into an array.
I am confused because wouldn't an array only have to be either a float, or a int or a double or a String, it cant be both a String and a double. But the user is entering multiple flavors of data. I am adding the question below and also the code I have scripted so far.
enter image description here
I have attached an image of the question
import java.util.Scanner;
public class salesRecord {
String Itemname;
int Quantity;
float unitPrice;
static float total;
String status; //for credit or debit
void data() {
Scanner input=new Scanner(System.in);
System.out.println("Enter your Item name: ");
Itemname=input.next();
System.out.println("Enter your Quantity: ");
Quantity=input.nextInt();
System.out.println("Enter your Unit Price: ");
unitPrice=input.nextFloat();
System.out.println("What is your Status: ");
status=input.next();
total=Quantity*unitPrice;
}
void ShowData() {
System.out.println("Item name is: "+Itemname);
System.out.println("Quantity is: "+Quantity);
System.out.println("Price per unit is: "+unitPrice);
System.out.println("Credit or Debit: "+status);
System.out.println("Total Price is: "+ total);
}
public static void main(String[] args) {
salesRecord cus1=new salesRecord();
Scanner inputcashier=new Scanner(System.in);
System.out.println("How many items do you have: ");
int items=inputcashier.nextInt();
for (int i = 0; i < items; i++) {
cus1.data();
cus1.ShowData();
total=total+total;
}
System.out.println("Your grand total is: "+total);
}
}
The problem states that you need to hold data of multiple types, an object is the best way to hold this data. You would first need to create the SalesRecord.
class SalesRecord{
String itemName;
double unitPrice;
double total;
String status;
// constructor
SalesRecord(String _itemName,double _unitPrice,double _total,String _status){
this.itemName = _itemName;
this.unitPrice = _unitPrice;
this.total = _total;
this.status = _status;
}
}
Once you have created this object the problem then states to store them in an array size 10 called salesRecord
SalesRecord[] salesRecord = new SalesRecord[10];
This array will now hold the SalesRecord objects. Thus has the type SalesRecord rather than your typical int,string or double.
Here's a good intro to creating and storing objects.
I have looked through some of the other questions asking about a similar issue, but I am trying to call the double 'thirdPrice' from calculationMethod() to main(). The purpose of this program is to request data in main(), pass some of the info to calculationMethod() and then return that data back to main() for final output. I am using DrJava, here is my code so far.
import java.util.Scanner; //Imports input device
public class CraftPricing
{
public static void main(String[] args)
{
Scanner inputDevice = new Scanner(System.in); //Sets up input device
String productName; //Used for naming product
double costMaterials, hoursWorked; //Gives variables decimal format
System.out.println("Enter the name of the product "); //Enter product name
productName = inputDevice.nextLine(); //Passes variable for calculation
System.out.println("Enter the cost of materials prior to discount "); //Enter cost of materials
costMaterials = inputDevice.nextDouble(); //Passes variable for calculation
System.out.println("Enter the number of hours worked "); //Enter hours worked
hoursWorked = inputDevice.nextDouble(); //Passes variable for calculation
System.out.printf("The cost of " + productName + " is %.2f\n" , thirdPrice);
//Output product name and cost
}
public static void calculationMethod() //Method used to calcualte price
{
double itemDiscount = 0.75; //Gives decimal format to variable
double payRate = 14.00; //Gives decimal format to variable
double shipHandle = 6.00; //Gives decimal format to variable
double firstPrice = payRate * 7; //Calculates fisr portion of equation
double secondPrice = 7 + firstPrice; //Calculates second portion of equation
final double thirdPrice = itemDiscount * secondPrice + shipHandle;
//Calculates final portion of equation
return thirdPrice; //Returns double to main() for output
}
}
The errors I receive when trying to compile are as follows:
2 errors found:
File: C:\Users\unkno\DrJava\Java\CraftPricing.java [line: 18]
Error: cannot find symbol
symbol: variable thirdPrice
location: class CraftPricing
File: C:\Users\unkno\DrJava\Java\CraftPricing.java [line: 28]
Error: incompatible types: unexpected return value
Why do you need a variable at all?
Call the method.
System.out.printf("The cost of %s is %.2f\n" , productName, calculationMethod());
Or learn about variable scope.
And also fix the return type.
public static double calculationMethod()
when my program gets to the part where it asks for the name of the fruit, it will output the string asking for the name, then immediately go to the next string output without waiting for the user input.
This seems to automatically assign a value of null to my name variable.
Fruit.java
public class Fruit {
String Name;
int Quantity;
double Mass;
public Fruit(String Name, int Quantity, double Mass) {
this.Name = Name;
this.Quantity = Quantity;
this.Mass = Mass;
}
public void Information() {
System.out.println("This fruit is an " + Name + ", there's " + Quantity
+ " of it and it weighs " + Mass + " grams");
}
}
Fruits.java
import java.util.Scanner;
public class Fruits {
public static void main(String[] args) {
Fruit menu[];
int number;
String name;
int quantity;
double mass;
System.out
.print("How many fruits would you like to add to the menu?: ");
Scanner input = new Scanner(System.in);
number = input.nextInt();
input.nextLine();
menu = new Fruit[number];
for (int i = 0; i < menu.length; i++) {
System.out.println("What would you like to name the fruit?: ");
name = input.nextLine();
System.out.println("How much fruits are there?: ");
quantity = input.nextInt();
System.out.println("What is the mass of the Fruit in grams?: ");
mass = input.nextDouble();
menu[i] = new Fruit(name, quantity, mass);
menu[i].Information();
}
input.close();
}
}
instead of input.nextInt(); use Integer.parseInt(input.nextLine()). it might solve your issue.
When you use input.nextInt() there is a %n char in hub. You need to use a input.nextLine() after to remove the line-break charcater. You can also use input.nextLine() for each variables and then parse it yourself.
Warning! In java convention the method name, attribute name and parameter name must begin by an lower case character.
the problem is scanning for ints, then nextLine. When you run .nexInt() I believe there is a newline character not scanned in, so this immediately messes with the following .nextLine(), as it only takes in the newline and nothing after
The easiest fix I am aware of is
number = input.nextInt();
input.nextLine();
menu = new Fruit[number];
And then the rest of the code should work
As an aside, usually you would start the loop from 0, because arrays start from 0, and you will have a blank first entry, but I don't think it matters in this particular piece of code
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
To practice my basic programming skills over the summer I decided to write a 1dimensional motion physics problem solver. I am getting a java.lang.Nullpointerexception error whenever I try to run the program. I can't figure out what I've written incorrectly to give me the error. NOTE: Right now I am assuming the input for the solveFor variable will be "acceleration" for the sake of fixing this error:
import java.util.Scanner;
public class PhysicsProblem
{
private double vI; // initial velocity
private double vF; // final velocity
private double t; // time
private double deltaX; // change in the x value
private double accel;
private String missingVar;
public PhysicsProblem (double acceleration, double initialV, double finalV, double time, double changePosition)
{
acceleration = accel;
initialV = vI;
finalV = vF;
time = t;
changePosition = deltaX;
}
Scanner scan = new Scanner(System.in);
public void getUnknownsAccel()
{
//-----------
// checks for another unknown value that is not accel
//-----------
if (missingVar.equalsIgnoreCase("time"))
{
System.out.println("Please enter the value for time: ");
t = scan.nextDouble();
while (t <= 0 || !scan.hasNextDouble())
{
System.out.println("That is not an acceptable value!");
t = scan.nextDouble();
}
}
if (missingVar.equalsIgnoreCase("initial velocity"))
{
System.out.println("Please enter the value for initial velocity: ");
vI = scan.nextDouble();
while (!scan.hasNextDouble())
{
System.out.println("That is not an acceptable value!");
vI = scan.nextDouble();
}
}
if (missingVar.equalsIgnoreCase("final velocity"))
{
System.out.println("Please enter the value for final velocity: ");
vF = scan.nextDouble();
while (!scan.hasNextDouble())
{
System.out.println("That is not an acceptable value!");
vF = scan.nextDouble();
}
}
if (missingVar.equalsIgnoreCase("delta X"))
{
System.out.println("Please enter the value for delta X: ");
deltaX = scan.nextDouble();
while (!scan.hasNextDouble())
{
System.out.println("That is not an acceptable value!");
deltaX = scan.nextDouble();
}
}
}
This is the class file for the program. I'm getting an error in the line 36:
"if (missingVar.equalsIgnoreCase("time"))"
As well as getting an error in line 40 of the main program body:
"problem1.getUnknownsAccel();"
public static void main (String[] args)
{
String missingVar; // other missing variable
double vI = 0;
double vF = 0;
double t = 0;
double deltaX = 0;
double accel = 0;
Scanner scan = new Scanner(System.in);
PhysicsProblem problem1 = new PhysicsProblem (accel, vI, vF, t, deltaX);
System.out.println("Which variable are you solving for? ");
String solveFor = scan.nextLine();
// after receiving solveFor input, assesses data accordingly
if (solveFor.equalsIgnoreCase("acceleration"))
{
System.out.println("Solving for Acceleration!");
System.out.println("Are there any other unknowns? (enter 'none' or the name " +
"of the variable)");
missingVar = scan.nextLine();
do
{
problem1.getUnknownsAccel();
System.out.println("Are there any other unknowns? (enter 'none' or the name " +
"of the variable)");
missingVar = scan.nextLine();
}
while (!missingVar.equalsIgnoreCase("none") || !missingVar.equalsIgnoreCase("acceleration"));
if (missingVar == "none");
{
// Write code for finding solutions
System.out.println("Assuming you have given correct values, the solution is: ");
}
}
Why is it throwing an exception?
missingVar is obviously null. Look back in the code to find out why. And doing this, ask yourself where do you ever give the variable a String in the PhysicsProblem class?
Answer: you don't!
Note that two variables with the same name declared in different scopes are not the same variable. Just because your two classes have a missingVar String variable does not mean that they share the same variable, and as you're finding out, they in fact don't. The solution: set the missingVar variable in the PhysicsProblem class before trying to use it. Give the class a setter method for this.
i.e.,
public void setMissingVar(String missingVar) {
this.missingVar = missingVar;
}
And then call the method before using the variable.
You never initialize missingVar to anything, so it's null. You need to assign it something so it's not null.
Incidentally, you can switch the order in your call to avoid a NullPointerException here:
while (!"none".equalsIgnoreCase(missingVar) ||
!"accelmissingVar".equalsIgnoreCase(missingVar));
Also, on this line
if (missingVar == "none");
Remove the semicolon, because that semicolon is interpreted to be the body of the if block, causing your actual block below to not be associated with if (it would then always be executed, regardless of the condition in your if).
Don't compare string values with ==, which compares two objects references to see if they refer to the same object. Use the equals method:
if ("none".equals(missingVar))