Access a variable across multiple classes JAVA - java

I am new to JAVA and am writing a program that passes a variable between two separate classes. I cannot seem to figure out how to send the data of a variable from one class to the other and then back? Is such a thing possible?
for example:
Public Class A {
Scanner input = new Scanner(System.in);
System.out.println("Please input the weight:");
bagWeight=input.nextDouble();
System.out.println("The total weight is: "+total);
}
Public Class B {
double number = 3;
public method(double number, double bagWeight)
{
total = bagWeight*number;
return total;
}
}

Sure this is possible :D There are many ways to do so.
For example you can easily do this:
//Obviously pseudo Code...u need a constructor..or method
Public Class A{
Scanner input = new Scanner(System.in);
System.out.println("Please input the weight:");
bagWeight=input.nextDouble();
B b = new B();
double total = b.method(1337, bagWheight);
System.out.println("The total weight is: "+total);
}

Related

Java Method isn't implementing what it is supposed to

Hey everyone very new to coding!
So I was trying to make a calculator program using object oriented programming in Java however when I try to call my method for addition it doesn't do the job entirely so what am I doing wrong here ?
Thanks in advance :)
import java.util.Scanner;
public class CalculatorOOP {
Scanner input = new Scanner(System.in);
public static double currentValue;
public double valueInput;
public CalculatorOOP(double valueTyped){
valueTyped = currentValue;
}
public double addToValue(){
System.out.println("Type the value you want to add:");
double valueToAdd = input.nextDouble();
double valueAfterAddition = CalculatorOOP.currentValue + valueToAdd;
return valueAfterAddition;
}
public double substractToValue(){
System.out.println("Type the value you want to substract:");
double valueToSubstract = input.nextDouble();
double valueAfterSubstraction =
CalculatorOOP.currentValue - valueToSubstract;
return valueAfterSubstraction;
}
public double multiplyValue(){
System.out.println("Type the factor value:");
double factor = input.nextDouble();
double valueAfterMultiplication = CalculatorOOP.currentValue * factor;
return valueAfterMultiplication;
}
public double divideValue(){
System.out.println("Type the divisor value:");
double divisor = input.nextDouble();
double valueAfterDivision = CalculatorOOP.currentValue / divisor;
return valueAfterDivision;
}
}
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Type a value:");
double valueInput = input.nextDouble();
CalculatorOOP obj = new CalculatorOOP(valueInput);
System.out.println("Enter the calculation option (1, 2, 3, or 4):");
int optionEntered = input.nextInt();
switch (optionEntered){
case 1 : obj.addToValue();
}
}}
Here this is what I get when running the code however it is not performing the addition it is just asking for values
Type a value:
2
Enter the calculation option (1, 2, 3, or 4):
1
Type the value you want to add:
4
Process finished with exit code 0
Your addToValue method seems to perform the addition correctly and return the calculated sum. Where you call the method, you are not picking up the return value — so it just disappears, is discarded. I believe you want to assign it back into CalculatorOOP.currentValue and/or print it. Either from inside the method or from where you called it.

loops! infinite inputs and keeping track of how many inputs were made

Write a java program to accept an unlimited # of double type (variable) expense records with description.
Mean time list in console O/P of the same, and accumulate the total # of entries.
heres my code I have so far
public class Quizz {
public double expense;
public double totalExpenses;
public static void main(String[] args) {
Quizz expenses = new Quizz();
Scanner intScan = new Scanner(System.in);
do
{
System.out.println("Enter an expense");
expenses.expense = intScan.nextInt();
}
while (proceed);
System.out.println("done counting");
}
}
The class definition here is rather weird. You don't really need a class, just a main method to do what you want:
Scanner doubleScan = new Scanner(System.in);
double runningTotal = 0;
do {
System.out.print("Enter an amount (-1 to exit): ");
double expense = doubleScan.nextDouble();
if (expense != -1) runningTotal += expense;
} while (expense != -1);
System.out.println("Total: " + runningTotal);

Input variable created at Main is a different value to that created in Method

I have created a method that gets input from the user. However, my issue is that when I attempt to return the value of the method, it continuously asks for a new number as input. Instead, I want it to ask for a number once, then return it.
For example: the following code illustrates what I want to achieve without a method, but including it within a method causes difficulties:
Working Code Inside Main:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int age;
System.out.print("Enter Age: ");
age = input.nextInt();
System.out.print("/nYou're " + age + " years of age.");
}
However, when I try to do this within a method, I have difficulties:
Code Inside Method:
public static int getAge() {
Scanner input = new Scanner(System.in);
int number;
number = input.nextInt()
return number;
}
The issue is, whenever I try print System.out.print(getAge()); it asks for a number each time. Why does the first code allow me to print age without asking for a new number, but calling the method to print the number causes issues and continues to ask for a new number.
Effectively, I just want to call that method, ask for a number to input once, then call that method to return the number that the user has entered.
Its not just about having code to do job, but also about design. I would recommend below approach, features are:
A utility class and a generic method promptUserInput to prompt the user for input, passing your message
It will return a String object, convert it into other objects as required.
If you want to access it from other methods/classes, then store as instance variable, else simply use it to print or whatever is your plan.
You can handle the Scanner object to close it once everything is done, and parent thread is ready to die, for that you will need some change.
P.S.: My intention is not simply providing chunk of codes but make you think how to design. So, you may need to some change as per your requirement, scenarios and as you test.
Code:
public class UserTest {
public static void main(String[] args) {
User user = new User();
user.promptUserAge();
user.printUserAge(user.getUserAge());
//DO something.
user.printUserAge(user.getUserAge());
user.promptUserAge();
user.printUserAge(user.getUserAge());
}
}
public class User {
private int userAge = 0;
public void promptUserAge() {
String userInput = AppUtils.promptUserInput("Enter Age: ");
userAge = new Integer(userInput);
}
public int getUserAge(){
return userAge;
}
public void printUserAge(int age){
System.out.print("\nYou're " + age + " years of age.");
}
}
public class AppUtils {
public static String promptUserInput(String message) {
Scanner input = new Scanner(System.in);
System.out.println(message);
String userInput = input.next();
return userInput;
}
}
Your issue is that every time you call getAge() it is going to create a new scanner and try to get input again. Instead, when you return your number from getAge() the first time, save the value in a variable that you can reuse.
Something like this:
int age = getAge();
System.out.print("your age is " + age + " years of age");
You could store the user input in a class member variable, and reuse it later on.
import java.util.Scanner;
public class MyClass {
private int age = -1;
public static void main(String[] args) {
MyClass o = new MyClass();
o.getAge();
System.out.print("\nYou're " + o.getAge() + " years of age.");
}
public int getAge() {
if (age == -1) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Age: ");
age = input.nextInt();
}
return age;
}
}

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.

input 2 variables(user input by "Buffered Reader") to be pass to a class?

i am a beginner at java language and i use "text pad". i have a problem with my simple program. my task is to input 2 values and show the "sum","difference","product" and "quotient" altogether. (simple right?) in which , here below is the class that supposed to be doing the job of arithmetic. in which is "correct" as i compiled.
public class mathclass
{
int x;
int y;
int total;
void add ()
{
total = x+y;
}
void sub ()
{
total = x-y;
}
void multi ()
{
total = x*y;
}
void div ()
{
total = x/y;
}
}
And here is the main program that supposed to be the input and output of the program.
my problem here is that i can't pass the 2 variables (num1 and num2) to "mathclass"
i did research on how to pass 2 variables to a another class. but there is nothing same to mine that i have. i did use some like the putting "private or public" on the variables.
my teacher said to use the BufferedReader for input. and i am having a hard time how to get this program right. (sorry if i had wrong english(if i am wrong. ))
import java.io.*;
public class mathmain
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[]args)throws IOException
{
mathclass math1 = new mathclass();
System.out.print("Enter 1st Number :");
num1 = Integer.parseInt(br.readLine());
System.out.println(" ");
System.out.print("Enter 2nd Number :");
num2 = Integer.parseInt(br.readLine());
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
math1.add();
{
System.out.print("Sum : ");
System.out.println(math1.total);
}
System.out.println(" ");
math1.sub();
{
System.out.print("Difference : ");
System.out.println(math1.total);
}
System.out.println(" ");
math1.multi();
{
System.out.print("Product : ");
System.out.println(math1.total);
}
System.out.println(" ");
math1.div();
{
System.out.print("Quotient : ");
System.out.println(math1.total);
}
}
}
It's really not clear what you're trying to do here. (Why doesn't add take two arguments for instance?)
Perhaps your after something like this:
// Set up arguments
math1.x = num1;
math1.y = num2;
// Perform the add.
math1.add();
// { <-- brace completely useless.
// Print the result
System.out.print("Sum : ");
System.out.println(math1.total);
// } <-- brace completely useless.
However, I would encourage you to use return values and use parameters:
class MathClass {
public int add(int a, int b) {
return a + b;
}
...
}
and then use the class like
int sum = math1.add(num1, num2);
System.out.println("Sum: " + sum);
You should take some look on how to code in Java because you're going the wrong way.
Either you create a constructor to initialize x & y either you put them in the method add(x,y) which would lead you to make the method static and remove references of x & y from the class. Same goes for the total that should be the return of your function.
Try this,
Use Two Parameter Constructor for mathmain class...
public mathmain(int x, int y){
this.x = x;
this.y = y;
}
Please use Uppercase for the Fist alphabet of the class name (eg: MathMain),
and yes, use Camel Case for writing Class, Variables, Method,etc Names in java.
Since you're beginning, I will not point out the design flaws. Your problem comes from how you are using your read values. You read values into num1 and num2, but you never set them in your mathclass object:
math1.x = num1;
math1.y = num2;
As per what aioobe said, you should look at java design rules to help you create robust, useful classes. I would also encourage you to encapsulate your classes and use parameters and return values whenever possible.
Good luck in learning java, and I hope this helped!

Categories

Resources