Inheriting from classes to get outputs. - java

I have been struggling for weeks with this issue. I cannot get a result for my calculations. I have all the methods within my Calculating class and have the user input within the Main class. Additionally At the end of my Main class I have created an object to inherit all the calculations from the Calculating class to get the results based on the inputs. It does not work. Any suggestions is highly appreciated.
//Calculating Class
public class Calculating { //Calculation class
//Declaring fields - Inputs
public double totalImpulse ;
public double averageImpulse;
public double timeEjectionChargeFires;
public double massEmptyVehicle;
public double engineMass;
public double fuelMass;
//Declaring variables for outputs
public double theAverageMassOfTheVehicle;
public Calculating() { //Constructor (inputs)
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires =timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
//Accessors and Mutators
//Methods used to calculate Average mass of the vehicle
public double theAverageMassOfTheVehicle() {
return massEmptyVehicle + ((engineMass + (engineMass - fuelMass) )/ 2); //Formula to calculate Average mass
}
//Setters
public void setTheAverageMassOfTheVehicle(double theAverageMassOfTheVehicle) {
this.theAverageMassOfTheVehicle = theAverageMassOfTheVehicle;
}//method
//Getters
public double getTheAverageMassOfTheVehicle() {
return theAverageMassOfTheVehicle;
}
}
//Master class
public class Master extends Calculating{ //Master class
public static void main( String args[] ) //Standard header for main method
{
UserEntry input = new UserEntry(); //Creating object from UserEntry class
//User entry for Total Impulse with exception handling
Double totalImpulse = null;
while(totalImpulse==null){
System.out.print("\nPlease enter Total impulse delivered: "); //System print line for input
try {
totalImpulse= input.gettotalImpulse(); //Instantiates totalImpulse from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Average Impulse with exception handling
Double averageImpulse = null;
while(averageImpulse==null){
System.out.print("Please enter Average Impulse delivered: "); //System print line for input
try {
averageImpulse= input.getaverageImpulse(); //Instantiates averageImpulse from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Time Ejection charge fires with exception handling
Double timeEjectionChargeFires = null;
while(timeEjectionChargeFires==null){
System.out.print("Please enter Time ejection charge fires: "); //System print line for input
try {
timeEjectionChargeFires= input.gettimeEjectionChargeFires(); //Instantiates timeEjectionChargeFires from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Mass of the empty vehicle with exception handling
Double massEmptyVehicle = null;
while(massEmptyVehicle==null){
System.out.print("Please enter The mass of the empty vehicle: "); //System print line for input
try {
massEmptyVehicle= input.getmassEmptyVehicle(); //Instantiates massEmptyVehicle from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Mass of the engine with exception handling
Double engineMass = null;
while(engineMass==null){
System.out.print("Please enter The mass of the engine: "); //System print line for input
try {
engineMass= input.getengineMass(); //Instantiates engineMass from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//User entry for Fuel mass with exception handling
Double fuelMass = null;
while(fuelMass==null){
System.out.print("Please enter The mass of the fuel: "); //System print line for input
try {
fuelMass= input.getfuelMass(); //Instantiates fuelMass from UserEntry scanner
}
catch(Exception e){ //There was something wrong with the input.
System.out.println("\nInvalid entry, please enter a number !"); //Error message upon wrong input
}
}
//Outputs based on user inputs
Calculating Master = new Calculating(); //Creates object of Calculating class
System.out.println("\nThe average mass of the vehicle: " +Master.theAverageMassOfTheVehicle() /1000);
}
}

The problem is with your constructor.
public Calculating() { //Constructor (inputs)
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires =timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
You are never passing any parameters, so how are you initalizing them?
A better constructor could be:
public Calculating(double totalImpulse, double averageImpulse,
double timeEjectionChargeFires, double massEmptyVehicle,
double engineMass, double fuelMass) {
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires = timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
Your Master class doesn't have to extend Calculating.
All you have to do within your main is to create a Calculating object initialized with the parameters you are taking from input.
Calculating calculations = new Calculating(totalImpulse,averageImpulse,timeEjectionChargeFires,massEmptyVehicle,engineMass,fuelMass);
Then you can call calculations.theAverageMassOfTheVehicle()

Related

initialization of an array of objects in a for loop, this cause all the objects have the same values, help please

I'm trying to initialize an array of objects in a for loop, each object with a different value that comes from the console, I have a for loop to do this and everything is ok until I see the objects, all the objects have the values of the second input, I have tried a lot of different things but I can't see what's wrong, I'm 17 years old and a total beginner, I'm not a native English speaker so sorry if is hard to understand, sorry if the solution is obvious.
Please help me, Thank you.
This is my main class code.
import java.util.Scanner;
public class StockDriver {
static Stocks stockObj[];
static int NumStocks;
static String Symbol;
static String ComName;
static int Shares;
public static void main(String[] args) throws Exception {
Scanner cin = new Scanner(System.in);
System.out.println("How many stocks do you want to create?");
//Stocks input
try { //Try-Catch to handle Imput Mismatch Exeption
NumStocks = cin.nextInt();
cin.nextLine();
System.out.println("You entered: " + NumStocks);
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Stock");
}
System.out.println("You will now enter in the company symbol, name and their share quantity. The price will be randomly generated.");
//Initialitation of stock objects
stockObj = new Stocks[NumStocks];
//For loop to ask for the imput of all stock, forced to a maximum of 10 stocks
for(int i = 0; i < NumStocks && i < 10; i++){
stockObj[i] = new Stocks(Symbol,ComName,Shares);
//Symbol input
System.out.println("Please enter the three character symbol: ");
try { //Try-Catch to handle Imput Mismatch Exeption
Symbol = cin.nextLine();
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Symbol");
}
//Company Name input
System.out.println("Please enter the conpany name:");
try { //Try-Catch to handle Imput Mismatch Exeption
ComName = cin.nextLine();
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Name");
}
//Number of Shares input
System.out.println("Please enter the total shares:");
try { //Try-Catch to handle Input Mismatch Exeption
Shares = cin.nextInt();
cin.nextLine();
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Shares");
}
// stockObj[i] = new Stocks(Symbol,ComName,Shares);
}
for( int i = 0; i < NumStocks;i++){
System.out.println("this is "+i);
System.out.println(stockObj[i].getSymbol());
}
}
}
This a class for my program.
public class Stocks {
private static String Symbol;
private static String ComName;
private static int Shares;
private static double price;
Stocks(String symbol, String comName, int shares) {
Symbol = symbol;
ComName = comName;
Shares = shares;
}
//Method to get symbol
public String getSymbol(){
return Symbol;
}
//Method to get Company Name
public String getComName(){
return ComName;
}
//Method to get the random price between $1.00 and $200.99
public double randomPrice(){
double price = (Math.random() * (200.99 - 1.00)) + 1.00;
Stocks.price = price;
return price;
}
//Method to get Shares
public int getShares(){
return Shares;
}
//Method to get the total value of the stock
public double totalValue(){
return price * Shares;
}
}
In the next for loop I ask for three inputs the number of times that was entered before, what I tried to do is to store the inputs the first time of the loop and create a object with this inputs before the loop ask for the inputs again and the inputs change. I have verified and the program does store different inputs so this is no the problem. The problem is that when a take a look at each object have the same values although there were different inputs, the input that is stored in all objects is one before the last one or the last one. I would like understand what's going on and know a way to store the different inputs in the objects, thank you very much and sorry for the long reading.
for(int i = 0; i < NumStocks && i < 10; i++){
//stockObj[i] = new Stocks(Symbol,ComName,Shares);
//Symbol input
System.out.println("Please enter the three character symbol: ");
try { //Try-Catch to handle Imput Mismatch Exeption
Symbol = cin.nextLine();
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Symbol");
}
//Company Name input
System.out.println("Please enter the conpany name:");
try { //Try-Catch to handle Imput Mismatch Exeption
ComName = cin.nextLine();
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Name");
}
//Number of Shares input
System.out.println("Please enter the total shares:");
try { //Try-Catch to handle Input Mismatch Exeption
Shares = cin.nextInt();
cin.nextLine();
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Shares");
}
stockObj[i] = new Stocks(Symbol,ComName,Shares);
}
All the fields in Stocks class are static, that is, they exist per class -- not per instance, and therefore the same values are shared across all instances when they are created.
To fix the issue, just remove static modifier, and change the field names to be camelCase to comply with Java naming conventions:
public class Stocks {
private String symbol;
private String comName;
private int shares;
private double price;
// ...
// update getters/setters/constructor according to the updated field names
}

Java: Using Try/Catch Exception to check if user input is Double

I am writing a simple program that allows a user to enter two separate doubles for a foot and inch measurement. The program is intended to take these values and convert them to centimeters and output them. Additionally I am to include two exceptions: one to make sure the numeric values are positive and not negative (this one I have completed) and another to make sure the input entered is a double value and not a string value (this one I am having a hard time with). So if a user enters an input... for example 'Bill' instead of a number, it is to display an error message and ask the user to re-enter the input values again.
It seems like perhaps I would be best off gathering the user input as a string (rather than doubles as I currently am), which I convert to doubles and return them as doubles to their corresponding methods: getFootValue() and getInchValue() -- but I am not too sure.
How should I go about implementing this by way of a custom exception? I cannot simply utilize the InputMismatchException, I need to make my own titled NonDigitNumberException().
Here is what I have so far...
import java.util.Scanner;
public class Converter
{
private double feet;
private double inches;
public Converter(double feet, double inches)
{
this.feet = feet;
this.inches = inches;
}
public double getFootValue()
{
return feet;
}
public double getInchValue()
{
return inches;
}
public double convertToCentimeters()
{
double inchTotal;
inchTotal = (getFootValue() * 12) + getInchValue();
return inchTotal * 2.54;
}
public String toString()
{
return ("Your result is: " + convertToCentimeters());
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class TestConverter
{
public static void main(String[] args)
{
/* Create new scanner for user input */
Scanner keyboard = new Scanner(System.in);
do
{
try
{
/* Get the feet value */
System.out.print("Enter the foot value: ");
double feet = keyboard.nextDouble();
if (feet < 0) throw new NegativeNumberException();
/* Get the inches value */
System.out.print("Enter the inch value: ");
double inches = keyboard.nextDouble();
if (inches < 0) throw new NegativeNumberException();
else
{
Converter conversion = new Converter(feet, inches);
/* Print the converted result */
System.out.println(conversion);
break;
}
} catch(InputMismatchException ignore){}
catch(NegativeNumberException error)
{
System.out.println("A negative-numeric value was entered, please enter only positive-numeric values...");
}
}while(true);
/* Close the keyboard */
keyboard.close();
}
}
class NegativeNumberException extends Exception
{
public NegativeNumberException()
{
super();
}
public NegativeNumberException(String errorMessage)
{
super(errorMessage);
}
}
Thanks for any help!
You're over complicating things. You can simply use the Scanner.hasNextDouble() method.
Example:
Assuming this code is inside your main method.
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter value");
double myValue = 0;
if(scanner.hasNextDouble()){
myValue = scanner.nextDouble();
}else{
System.out.println("Wrong value entered");
}
}
}
you can then go on and use myValue with your Converter class.
UPDATE
It seems that you must create your own exception class according to what you have told me within the comments. So, I have decided to implement that for you and hopefully, you can be able to carry on from here.
Custom Exception Class
public class NonDigitNumberException extends InputMismatchException {
public NonDigitNumberException(String message){ // you can pass in your own message
super(message);
}
public NonDigitNumberException(){ // or use the default message
super("input is not a digit");
}
}
Negative Number Exception Class
public class NegativeNumberException extends IllegalArgumentException {
public NegativeNumberException(String message){ // you can pass in your own message
super(message);
}
public NegativeNumberException(){ // or use the default message
super("negative number is not valid");
}
}
Validator Method
public static double inputValidator(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter a value"); // prompt user for input
String getData = scanner.next(); // get input
if(getData.length() >= 1){
if(!Character.isDigit(getData.charAt(0)) && getData.charAt(0) != '-') throw new NonDigitNumberException();
}
for (int i = 1; i < getData.length(); i++) {
if(!Character.isDigit(getData.charAt(i))) throw new NonDigitNumberException();
}
return Double.parseDouble(getData); // at this point the input data is correct
}
Negative Number Validator
public static boolean isNegative(double value){
if(value < 0) throw new NegativeNumberException();
return false;
}
Main method
public static void main(String[] args) {
try {
double myValue = inputValidator();
System.out.println(isNegative(myValue)); // check if number is negative
}catch (NegativeNumberException e){
e.printStackTrace();
}
catch (NonDigitNumberException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}
Do you really need a custom exception? Because keyboard.nextDouble() already throws InputMismatchException if the input is not a double.
Instead of ignoring the exception, you should show an error message (saying the user didn't type a number).
I guess, you are mixing things up:
You have to validate the input of the user first, if it is a double. If it is not, then you are getting an InputMismatchException.
Then you have to validate the input, if it is valid for your converter (is it positive?). Here you can throw your custom exception.
And then you call your Converter, which might also throw your custom exception.
So my solution would be:
import java.util.Scanner;
import java.util.InputMismatchException;
public class TestConverter {
public static void main(String[] args) {
/* Create new scanner for user input */
Scanner keyboard = new Scanner(System.in);
do {
double feet = -1, inches = -1;
Exception exception;
do {
exception = null;
/* Get the feet value */
System.out.print("Enter the foot value (positive-numeric): ");
try {
feet = keyboard.nextDouble();
} catch (InputMismatchException e) {
keyboard.next();
exception = e;
}
} while (exception != null);
do {
exception = null;
/* Get the inches value */
System.out.print("Enter the inch value (positive-numeric): ");
try {
inches = keyboard.nextDouble();
} catch (InputMismatchException e) {
keyboard.next();
exception = e;
}
} while (exception != null);
try {
if (feet < 0) throw new NegativeNumberException();
if (inches < 0) throw new NegativeNumberException();
Converter conversion = new Converter(feet, inches);
/* Print the converted result */
System.out.println(conversion);
break;
}
catch(NegativeNumberException error) {
System.out.println("A negative-numeric value was entered, please enter only positive-numeric values...");
}
} while (true);
/* Close the keyboard */
keyboard.close();
}
}
Output
Enter the foot value (positive-numeric): test
Enter the foot value (positive-numeric): 1234
Enter the inch value (positive-numeric): test
Enter the inch value (positive-numeric): 1234
Your result is: 40746.68

java having trouble with multiple classes

so I'm trying to use a switch so that when i click on a range of 1 to 4, each one is directed to a class and performs its function. The choice "1" should asks for the user to input the id, name, other name and marks, then calculate it's average. The second class should then display all the information and I'm not sure how to do it.
Here is my main code:
public class lab3q1 {
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
Entries entriesobject = new Entries(); //object declaration
display displayobject = new display(); //object declaration
displayall displayallobject = new displayall(); //object declaration
sortdata sortdataobject = new sortdata();
System.out.println("1. Add new entries: ");
System.out.println("2. Display an entry: ");
System.out.println("3. Display all entries: ");
System.out.println("4. Sort Data: ");
System.out.println("5. Exit: ");
int s = sc.nextInt();
switch(s){
case 1:{
if(s==1)
try{
entriesobject.method0();
}
catch(Exception e){
System.out.println("You can't do that");
}
}
case 2:{
if(s==2){
try{
displayobject.method();
}
catch(Exception e){
System.out.println("You can't do that");
}
}
}
case 3:{
if(s==3){
try{
displayallobject.method2();
}
catch(Exception e){
System.out.println("You can't do that");
}
}
}
case 4:{
if(s==4){
try{
sortdataobject.method3();
}
catch(Exception e){
System.out.println("You can't do that");
}
}
}
case 5:{
if(s==5){break;}
}
}
}
}
Here is the first class:
public class Entries {
public void method0(){
int total=0,total2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the student id: ");
int id = sc.nextInt();
sc.nextLine();
System.out.println("Enter the student name: ");
String name = sc.nextLine();
System.out.println("Enter the student other names: ");
String othername = sc.nextLine();
for(int i=1;i<=4;i++){
System.out.println("Enter the student marks" +(i));
int mark = sc.nextInt();
total += mark;
total2 =total/4;
System.out.println("The average marks is: "+total2);
}
}
}
And here is my second class:
public class display {
public void method() {
int n;
Scanner sc = new Scanner(System.in);
System.out.println("Here is the student id: ");
}
}
As you can see i can't seem to link them.
To answer your question: when different classes want to know about data in other classes (aka fields of other objects), you need ways to access that, like:
public class Student {
private int id;
... methods to put a value into id
public int getId() { return id; }
and then some other class that has one more Student objects can do.
Beyond that: you are getting your "separation of concerns" wrong. You should have one class that uses a scanner to "collect" data from the user. This class creates various other objects; and puts the data from the user into those objects.
All your other classes do not have / need a scanner object. They get their data, for example as parameters to their constructor.
System.out.println("The id is: " + someStudentObject.getId());

Calling a method adding input

I'm having problems finding out how to get the output based on the user inputs for my Main class. I already have keyboard entry where the users can enter a value, which will be held. I'm guessing I will need to use that e.g. (input.input1());. However I also need to include the method which calculates the result e.g calculations.theAverageMassFfTheVehicle from the CalculatingRocketFlightProfile class, I'm just not sure how to combine the two to get the result.
//Calculations class
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
public double averageImpulse;
public double timeEjectionChargeFires;
public double massEmptyVehicle;
public double engineMass;
public double fuelMass;
//Declaring variables for outputs
public double theAverageMassOfTheVehicle;
public double theVehiclesMaximumVelocity;
public CalculatingRocketFlightProfile(double totalImpulse, double averageImpulse, double timeEjectionChargeFires, double massEmptyVehicle,
double engineMass, double fuelMass) { //Constructor for this class
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires = timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
//Mutators and Accessors
//Accessors
//Methods for calculations - Calculating outputs, using inputs.
public double theAverageMassOfTheVehicle() {
return massEmptyVehicle + ((engineMass + (engineMass - fuelMass) )/ 2); //Formula to calculate Average mass
}//method
public double theVehiclesMaximumVelocity() { //Formula to calculate Maximum velocity
return totalImpulse / getTheAverageMassOfTheVehicle();
}//method
//Returns - GET
public double getTheAverageMassOfTheVehicle() {
return theAverageMassOfTheVehicle;
}//method
public double getTheVehiclesMaximumVelocity() {
return theVehiclesMaximumVelocity;
}//method
}//class
//Main class
public class Main { //Master class
public static void main( String args[] ) //Standard header for main method
{
kbentry input = new kbentry();
System.out.print("\nPlease enter a number for Total Impulse: " );
System.out.println("You have entered : " +input.input1());
System.out.print("\nPlease enter a number for Average Impulse: " );
System.out.println("You have entered : " +input.input2());
System.out.print("\nPlease enter a number for Time ejection charge fires: " );
System.out.println("You have entered : " +input.input3());
System.out.print("\nPlease enter a number for the Mass of the vehicle: " );
System.out.println("You have entered : " +input.input4());
System.out.print("\nPlease enter a number for the Mass of the engine: " );
System.out.println("You have entered : " +input.input5());
System.out.print("\nPlease enter a number for the Mass of the fuel: " );
System.out.println("You have entered : " +input.input6());
//Output
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile();
System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() +
"\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity());
}
}
//kbentry
public class kbentry{
double input1(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//Total Impulse entry
String strTotalImpulse = null; // These must be initialised
int intTotalImpulse = 0;
//System.out.print("Please enter a number for Total Impulse: ");
//System.out.flush();
// read string value from keyboard
try {
strTotalImpulse = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intTotalImpulse = Integer.parseInt(strTotalImpulse);
}
catch (NumberFormatException nfe) {
System.out.println("Error! Please enter a number!" + nfe.toString());
}
The problem is that you're CalcultingRocketFlightProfile class needs parameters, but you're creating calculations without passing any parameters to the new CalcultingRocketFlightProfile.
You should store those inputs in variables, then pass those variables to the constructor in your new CalcultingRocketFlightProfile that you declare.
Well, first off you are not actually passing any of your input to the Calculations class. I am not sure what input.input1() is or if you have an input class that you did not post. Either way you can do this a couple different ways.
First off give your input variables a meaningful name so you know which ones you are dealing with. Then pass all of your input.
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile(input1, input2, etc..)
or
Place all your input variables into your calculations class. Then store user input as calculations.totalImpulse, etc... Then you call your calculation methods to display answers.
-EDIT-
Just have 2 classes, your main and calculations class. There is no need for another class just to handle keyboard input.
Example
Main class
public class Main {
public static void main( String args[] ) {
Scanner keyboard = new Scanner(System.in);
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile();
System.out.print("\nPlease enter a number for Total Impulse: " );
calculations.totalImpulse = keyboard.nextDouble();
System.out.println("You have entered : " + calculations.totalImpulse);
}
}
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
// Do all of your maths, and methods for answer return
}
You were not actually taking the keyboard input and assigning it to anything. Using a scanner object you can assign the input to a variable in your calculations class. If you do that for all of them, you dont actually need a constructor in your calculations class, you just use it to do all that math and return answers.

string whitespace throwing errors in a object array

i am trying to enter a book title "hoopa doopa"into my object array. when i try it throws a java.util.InputMismatchException.If i enter a string that has no spaces like"hoopa" the code will run fine all of the way through. What is causing this and how can I fix it? please help thanks
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int counter = 0;
int numberOfProducts=0; //variable for when the user is asked to enter input the number of products to be entered
do { //this will validate the user input
System.out.println("How many products would you like to enter");
while (!input.hasNextInt()) {
System.out.println("That's not a number!");
input.next(); // this is important!
}
numberOfProducts = input.nextInt();
} while (numberOfProducts <= 0);
//end of the do while loop
Products[] products;
products = new Products[numberOfProducts+4];//create a array the size of the user input that was gathered
for (int i=0;i<numberOfProducts;i++)
{
products[i+4]= new Products(); // create each actual Person
System.out.println("What is the product #: ");
products[i+4].setItemNumber(input.nextInt());
System.out.println("What is the book name: ");
products[i+4].setNameOfProduct(input.next());
System.out.println("How many are in stock: ");
products[i+4].setUnitsInStock(input.nextInt());
System.out.println("What is the cost of the Item: ");
products[i+4].setPrice(input.nextDouble());
counter++;
}
products[0] = new Products(0001,"The Red Rose",1,29.99);
products[1] = new Products(0002,"The Bible",3,11.99);
products[2] = new Products(0003,"End of the Programm",2,29.99);
products[3] = new Products(0004,"WHAT!!! the....",1,129.99);
//____________________________________________________________4 products that are already made
for (int i=0;i<numberOfProducts+4;i++)
{
System.out.println(products[i].toString());
input.nextLine();
}
}
}
this is the other class
import java.text.NumberFormat;
public class Products
{
private int itemNumber;
private String nameOfProduct;
private int unitsInStock;
private double unitPrice;
public Products()
{
itemNumber = 0;
nameOfProduct = null;
unitsInStock = 0;
unitPrice = 0.0;
}
public Products(int num,String name,int inStock,double price)
{
itemNumber = num;
nameOfProduct = name;
unitsInStock = inStock;
unitPrice = price;
}
public int getItemNumber()
{
return itemNumber;
}
public void setItemNumber(int newValue)
{
itemNumber=newValue;
}
//----------------------------------------------
public String getNameOfProduct()
{
return nameOfProduct;
}
public void setNameOfProduct(String newValue)
{
nameOfProduct=newValue;
}
//----------------------------------------------
public int getUnitsInStock()
{
return unitsInStock;
}
public void setUnitsInStock(int newValue)
{
unitsInStock = newValue;
}
//-----------------------------------------------
public double getPrice()
{
return unitPrice;
}
public void setPrice(double newValue)
{
unitPrice = newValue;
}
//_______________________________________________
public double calculateTotalItemValue() //method that uses quantity on hand and price part3 1.A
{
return getUnitsInStock()* getPrice();
}//end of method
#Override
public String toString()
{
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
return"\nItem Number: "+getItemNumber() +
"\nItem Name: "+getNameOfProduct()+
"\nItem Quantity: " +getUnitsInStock()+
"\nItemPrice:" +currencyFormat.format(getPrice())
+"\nValue of Inventory: " +currencyFormat.format(this.calculateTotalItemValue());//part3 1.B
}
}
The Scanner sees the space in the book name as a delimiter since you are using the next() method. So when you go to read the nextInt() for the stock amount, the Scanner index is after the space in the book name String, and pulls in the remaining String data, which doesn't convert to an int. Instead, try something like this:
System.out.println("What is the book name: ");
input.nextLine();
products[i+4].setNameOfProduct(input.nextLine());
If you do not add the input.nextLine();, then it will appear as though the book name prompt gets skipped.
Scanner input = new Scanner(System.in);
Actually you are using scanner to get input and by default scanner delimiter is space. So you have to change the default delimiter of your code.
I think this is your problem:
products[i+4].setNameOfProduct(input.next());
What input.next() does is it reads the input from the user, until it reaches white space (the space between hoopa doopa). The function then passes hoopa to the setNameOfProduct method, and then passes doopa to the nextInt function, which gives a runtime error.
To fix your problem I would code
products[i+4].setNameOfProduct(input.nextLine());
Edit:
nextLine() function passes all characters up to the carriage return
Problem :
products[i+4].setNameOfProduct(input.next());
Solution 1 :
Just create another Scanner object for reading input with spaces
Scanner sc1=new Scanner(System.in);
products[i+4].setNameOfProduct(sc1.nextLine());
Solution 2 :
Or to use same scanner object
input.nextLine(); //Include this line before getting input string
products[i+4].setNameOfProduct(input.nextLine());

Categories

Resources