I'm new to java and I was wondering if there was a way to access a variable from one method in another method. While writing a program using methods, I realized that I cannot just take one variable from one method and use it in another method. So I was wondering if there was a way to do this.
Here is my code so far
import java.util.Scanner;
public class program{
public static void mass(){
double a,e,p,v;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the volume: ");
v=scanner.nextDouble();
p=0.8;
System.out.println("Enter the alcohol volume:(in percents) ");
e=scanner.nextDouble();
e=e/100;
a=v*e*p;
System.out.println("mass is: "+a);
}
public static void Concentration(){
double w,r,m;
String person;
System.out.println("Enter the person: m for male, f for female, j for teenager ");
Scanner sc=new Scanner(System.in);
person=sc.nextLine();
switch(person){
case "m": r=0.7;
break;
case "f": r=0.6;
break;
case "j": r=0.5;
break;
}
System.out.println("Enter person's weight: ");
m=sc.nextDouble();
//w=a/(m*r); //a from the method mass
}
public static void main(String[]args){
mass();
Concentration();
/*If(w>=0.5){ //w from the method concentration
System.out.println("You cannot drive!");
Else{
System.out.println("You can drive");
}
} */
}
}
There are two kinds of variables:
local variables (block-scoped)
member variables (class/instance level scope)
See: https://www.geeksforgeeks.org/variable-scope-in-java/
So, if you want to reuse a variable accross multiple methods, then you will need to convert it from a local variable into a member variable. In your case you only use static methods, so a would be declared outside your methods as
static double a;
and avoid declaring it inside your mass method, so your declaration line would be changed to
double e,p,v;
Note that the a is missing to avoid variable shadowing.
You may want to change your methods to instance-level methods, in which case you can declare a without the static keyword, depending on your plans and needs.
Also, a well-known approach is to implement getters and setters in order to make sure that whenever you get or set a value, if there are common operations, then they are implemented only once instead of code repeating.
Below you see the simplest changes to your code to achieve the goal you have specified:
import java.util.Scanner;
public class program{
static double a;
public static void mass(){
double e,p,v;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the volume: ");
v=scanner.nextDouble();
p=0.8;
System.out.println("Enter the alcohol volume:(in percents) ");
e=scanner.nextDouble();
e=e/100;
a=v*e*p;
System.out.println("mass is: "+a);
}
public static void Concentration(){
double w,r,m;
String person;
System.out.println("Enter the person: m for male, f for female, j for teenager ");
Scanner sc=new Scanner(System.in);
person=sc.nextLine();
switch(person){
case "m": r=0.7;
break;
case "f": r=0.6;
break;
case "j": r=0.5;
break;
}
System.out.println("Enter person's weight: ");
m=sc.nextDouble();
w=a/(m*r); //a from the method mass
}
public static void main(String[]args){
mass();
Concentration();
/*If(w>=0.5){ //w from the method concentration
System.out.println("You cannot drive!");
Else{
System.out.println("You can drive");
}
} */
}
}
Finally, you could also use a as a return value, like:
import java.util.Scanner;
public class program{
public static double mass(){
double a,e,p,v;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the volume: ");
v=scanner.nextDouble();
p=0.8;
System.out.println("Enter the alcohol volume:(in percents) ");
e=scanner.nextDouble();
e=e/100;
a=v*e*p;
System.out.println("mass is: "+a);
return a;
}
public static void Concentration(double a){
double w,r,m;
String person;
System.out.println("Enter the person: m for male, f for female, j for teenager ");
Scanner sc=new Scanner(System.in);
person=sc.nextLine();
switch(person){
case "m": r=0.7;
break;
case "f": r=0.6;
break;
case "j": r=0.5;
break;
}
System.out.println("Enter person's weight: ");
m=sc.nextDouble();
//w=a/(m*r); //a from the method mass
}
public static void main(String[]args){
Concentration(mass());
/*If(w>=0.5){ //w from the method concentration
System.out.println("You cannot drive!");
Else{
System.out.println("You can drive");
}
} */
}
}
To make a variable accessible in all functions of the class you can static the variable in question in the current class
package javaapplication6;
import java.util.Scanner;
// #author Vulembere
public class JavaApplication6 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
mass();
Concentration();
if (w >= 0.5) {
System.out.println("You cannot drive!");
} else {
System.out.println("You can drive");
}
}
static double w;
public static void mass() {
double a, e, p, v;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the volume: ");
v = scanner.nextDouble();
p = 0.8;
System.out.println("Enter the alcohol volume:(in percents) ");
e = scanner.nextDouble();
e = e / 100;
a = v * e * p;
System.out.println("mass is: " + a);
}
public static void Concentration() {
double r, m;
String person;
System.out.println("Enter the person: m for male, f for female, j for teenager ");
Scanner sc = new Scanner(System.in);
person = sc.nextLine();
switch (person) {
case "m":
r = 0.7;
break;
case "f":
r = 0.6;
break;
case "j":
r = 0.5;
break;
}
System.out.println("Enter person's weight: ");
m = sc.nextDouble();
//w=a/(m*r); //a from the method mass
}
}
Related
I just started a java class that my summer program was offering and we were tasked with creating a simple calculator. I have all the different cases created and all the variables accounted for but for some reason I keep getting a .class error and I have no clue what it is all I know is it comes from:
cases(int fnum, int snum, String op);
import java.util.Scanner;
public class day1{
public static void main(String [] args){
cases(int fnum, int snum, String op);
}
public static void input(){
Scanner userInput = new Scanner(System.in);
int fnum, snum;
String op;
System.out.println("Enter first num: ");
fnum = userInput.nextInt();
System.out.println("Enter second num: ");
snum = userInput.nextInt();
System.out.println("Enter operation: ");
op = userInput.next();
}
public static void cases(int fnum, int snum, String op){
input();
switch(op){
case "+":
System.out.println(fnum + snum);
break;
case "-":
System.out.println(fnum - snum);
break;
case "*":
System.out.println(fnum * snum);
break;
case "/":
System.out.println(fnum / snum);
break;
default:
System.out.println(fnum % snum);
break;
}
}
}
Change your code to look like this.
import java.util.Scanner;
public class day1{
public static void main(String [] args){
int fnum = 5;
int snum = 5;
String op = "";
input(fnum, snum, op);
}
public static void input(int fnum, int snum, String op){
Scanner userInput = new Scanner(System.in);
System.out.println("Enter first num: ");
fnum = userInput.nextInt();
//rest of your code
cases(fnum, snum, op);
}
public static void cases(int fnum, int snum, String op){
//your code
}
}
You needed to declare your variables then pass them into your function so your cases function can also reference them. I think what your teacher means by keep things out of main is don't do your input and cases code inside of main(). Instead your teacher probably wants you to use functions, like you're doing.
Ok so I have written two blueprint classes and one tester.I keep getting this same error:
'java.util.Scanner.throwFor(Unknown Source)'.
Can anyone enlighten me on what I am doing wrong? Here is my code.
blueprint class ShoppingCart:
package exercise3;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class ShoppingCart
{
ScanShop amount = new ScanShop();
public void getbill()
{
JOptionPane.showMessageDialog(null,"your total is: " + amount.getcart());
}
public void billCal()
{
String answer;
int number;
Scanner input = new Scanner(System.in);
/*System.out.println("please enter how much your bill is:...");
//how much bill is:
cart = in.nextDouble();
in.nextLine();
System.out.printf("you have entered: %.2f", cart);*/
System.out.println("Do you have a loyalty card? y or n");
// asking do you have loyalty card
answer= input.next();
if (answer.equalsIgnoreCase("y"))
{
amount.setcart(amount.getcart()*0.9);
//other vouchers to discount
System.out.println("thats great! do you have a voucher: "
+ "\n(1) £5 "
+ "\n(2) £10 "
+ "\n (3) no vouchers");
number= input.nextInt();
switch(number)
{
case 1 :
amount.setcart(amount.getcart()-5);
getbill();
break;
case 2 :
amount.setcart(amount.getcart()-10);
getbill();
break;
default :
getbill();
break;
}
}
else
{
getbill();
}
input.close();
}//closing billCal
}
Blueprint ScanShop:
package exercise3;
import java.util.Scanner;
public class ScanShop
{
private double cart;
public double getcart()
{
return cart;
}
public void setcart(double cart)
{
this.cart =cart;
}
public void scan()
{
//the prices of items
double p1;
double p2;
double p3;
double total;
Scanner in = new Scanner(System.in);
System.out.println("what price is item one?");
p1 = in.nextDouble();
System.out.println("What is price of item two?");
p2= in.nextDouble();
System.out.println("And what is the price of the third item?");
p3= in.nextDouble();
in.nextLine();
total = p1 + p2 + p3;
System.out.printf("The total bill is %.2f\n\n", total);
setcart(total);
System.out.println("the cart is: " + getcart());
in.close();
}
}
Tester class:
package exercise3;
public class ShoppingCart_Test {
public static void main (String [] arg){
ShoppingCart customerOne = new ShoppingCart();
//c1 is customer one
ScanShop c1 = new ScanShop();
c1.scan();
customerOne.billCal();
}
}
Problem:
Your problem is that you're closing your Scanner in the scan() method. Somewhat non-intuitively, closing the Scanner also closes the System.in input stream, thus causing you to be unable to create a new Scanner in the billCal() method.
Solution:
You can either A) remove in.close() at the end of your scan() method or B) create a single Scanner in the main method, and pass it to each of your methods.
Hello I'm still new to Java and OOP and am having issues trying to get my code to compile. I understand the issue with my code is the instantiation of the same object twice however I'm not sure how I can work around that to compile my code.
package week2;
import java.util.*
public class aBug {
aBug theBug = new aBug();
String Inspecies, Inname;
int Inx, Iny, Inenergy, Inid;
char Insymbol;
Scanner scan = new Scanner(System.in);
aWorld newWorld = new aWorld();
public static void main(String[] args) {
aBug theBug = new aBug();
theBug.mainMenu();
}
public void mainMenu() {
int choice;
do {
System.out.print("1\t Create bug\n");
System.out.print("2\t Enter world\n");
System.out.print("3\t Quit\n");
choice = scan.nextInt();
switch (choice) {
case 1:
bugInit();
break;
case 2:
System.out.println();
newWorld.mapInit(theBug.Inx, theBug.Iny, theBug.Insymbol);
System.out.println();
break;
}
} while (choice != 3);
}
public void bugInit() {
String species, name;
int x, y, energy, id;
char symbol;
System.out.print("Species: ");
species = scan.nextLine();
System.out.print("Name: ");
name = scan.nextLine();
System.out.print("X position: ");
x = scan.nextInt();
System.out.print("Y position: ");
y = scan.nextInt();
System.out.print("Energy: ");
energy = scan.nextInt();
System.out.print("ID: ");
id = scan.nextInt();
theBug.Insymbol = 'b';
theBug.Inspecies = species;
theBug.Inname = name;
theBug.Inx = x;
theBug.Iny = y;
theBug.Inenergy = energy;
theBug.Inid = id;
System.out
.format("\nThe bug is of the species %s, called %s, "
+ "with positions %d & %d, with energy amount: %d, and %d as it's id number\n\n",
theBug.Inspecies, theBug.Inname, theBug.Inx, theBug.Iny,
theBug.Inenergy, theBug.Inid);
}
}
In the constructor you have:
public class aBug {
aBug theBug = new aBug();
...
}
So while creating an instance of aBug (for example in your main) you call new aBug(), which calls the constructor again recurrently with out end overflowing the stack.
I am not sure why do you think you need to create an instance of the object within itself. So it's hard to give any hints. If I guess correctly, you merged the idea of aBug and "main program" in one class. You should split it and put aBug internal stuff in its own class.
I'm getting a NullPointerException at:
If(bookingList.size() == 0)
,
bookingList.add(vehicleBooking)
and
bookingList.add(rvBooking)
And i am not sure what is causing it. Any help is much appreciated.
Stack trace
bookingSystem.FerryBookingSystem at localhost:59034
Thread [main] (Suspended (exception NullPointerException))
FerryBookingSystem.bookingIDExists(String) line: 35
FerryBookingSystem.addVehicleBooking() line: 49
FerryBookingSystem.main(String[]) line: 114
C:\Program Files\Java\jre7\bin\javaw.exe (14/05/2013 10:52:02 PM)
BookingException
package bookingSystem;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
class BookingException extends Exception{
String message;
String IDs;
public BookingException(String message){
this.message = message;
}
public BookingException(String message, String IDs){
this.message = message;
this.IDs = IDs;
}
public String getIDs(){
return IDs;
}
public String getMessage(){
return message;
}
}
FerryBookingSystem
public class FerryBookingSystem {
private static ArrayList<VehicleBooking> bookingList;
private static Scanner userInput = new Scanner (System.in);
public FerryBookingSystem(){
bookingList = new ArrayList<VehicleBooking>();
}
public static int bookingIDExists(String IDs){
if (bookingList.size() == 0)
return -1;
for (int i = 0; i < bookingList.size(); i++){
if(bookingList.get(i).getbookingID().equals(IDs))
return i;
}
return -1;
}
public static boolean addVehicleBooking(){
System.out.print("Please enter the booking ID: ");
String booking_ID = userInput.nextLine();
if(bookingIDExists(booking_ID) != 1)
{
System.out.println("\nError - Sale ID \"" + booking_ID +
"\" already exists in the system!");
return false;
}
System.out.print("Please enter the registration number for the vehicle: ");
String registration_Number = userInput.nextLine();
System.out.print("Please enter the vehicle " +
"description: ");
String vehicle_Description = userInput.nextLine();
System.out.print("Please enter the number of people travelling in the vehicle: ");
int travelling_Number = userInput.nextInt();
userInput.nextLine();
VehicleBooking vehicleBooking = new VehicleBooking(booking_ID, registration_Number, vehicle_Description, travelling_Number);
bookingList.add(vehicleBooking);
System.out.println("New vehicle booking added successfully for " + booking_ID);
return true;
}
public static boolean addRecreationalVehicleBooking(){
System.out.print("Please enter the booking ID: ");
String booking_ID = userInput.nextLine();
System.out.print("Please enter the registration number for the vehicle: ");
String registration_Number = userInput.nextLine();
System.out.print("Please enter the vehicl description: ");
String vehicle_Description = userInput.nextLine();
System.out.print("Please enter the number of people travelling in the vehicle: ");
int travelling_Number = userInput.nextInt();
userInput.nextLine();
RVBooking rvBooking = new RVBooking(booking_ID, registration_Number, vehicle_Description, travelling_Number);
bookingList.add(rvBooking);
System.out.println("New rvbooking added successfully for " + booking_ID);
return true;
}
public static void displayBookingSummary(){
if (bookingList.size() != 0){
System.out.println("\nSummary of all past vehicle booking stored on system.");
for (int i=0 ; i<bookingList.size() ; i++){
bookingList.get(i).printBookingSummary();
System.out.println("");
}
}
}
public static void main (String [] args) throws IOException{
char user;
do{
System.out.println("**** Ferry Ticketing System ****");
System.out.println(" A - Add Vehicle Booking");
System.out.println(" B - Add Recreational Vehicle Booking");
System.out.println(" C - Display Booking Summary");
System.out.println(" D - Update Insurance Status");
System.out.println(" E - Record Recreational Vehicle Weight");
System.out.println(" F - Compile Vehicle Manifest");
System.out.println(" X - Exit");
System.out.print("Enter your selection: ");
String choice = userInput.nextLine().toUpperCase();
user = choice.length() > 0 ? choice.charAt(0) : '\n';
if (choice.trim().toString().length()!=0){
switch (user){
case 'A':
addVehicleBooking();
break;
case 'B':
addRecreationalVehicleBooking();
break;
case 'C':
displayBookingSummary();
break;
case 'D':
break;
case 'E':
break;
case 'F':
break;
case 'X':
break;
default:
break;
}
}
}while(user!='X');
}
}
Your code at:
private static ArrayList<VehicleBooking> bookingList;
have not been initialized. So initialize it.
bookingList is a static attribute of FerryBookingSystem.
You initialize it in the constructor, which is a non-sense for a static attribute.
Then, you never call your constructor because you never instantiate FerryBookingSystem.
Edit:
After looking more deeply into your code, it seems that you first declared bookingList as static then marked all methods static to solve compilations problems...
I don't think that you really need this attribute to be static so just remove the static keywork on your attribute and on all your methods:
public class FerryBookingSystem {
private ArrayList<VehicleBooking> bookingList;
Then, instantiate a FerryBookingSystem at the beginning of your main method:
public static void main (String [] args) throws IOException{
char user;
FerryBookingSystem fbs=new FerryBookingSystem();
and call methods of this instance :
switch (user){
case 'A':
fbs.addVehicleBooking();
break;
case 'B':
fbs.addRecreationalVehicleBooking();
break;
case 'C':
fbs.displayBookingSummary();
Move initialization of the bookingList from a regular constructor to a static initialization block:
static {
bookingList = new ArrayList<VehicleBooking>();
}
or initialize it at the point of declaration:
private static ArrayList<VehicleBooking> bookingList = new ArrayList<VehicleBooking>();
Otherwise, bookingList would remain null until the first call of FerryBookingSystem's constructor is made.
You're initializing the static field bookingList in a constructor and use it in static methods. Now you can call those methods without haveing created an instance of that class.
So there is a good chance, that bookingList is not initialized at the time you call the methods. Either remove all static modifiers or initialize the field directly and drop the constructor.
(I recommend removing all static modifiers and use instances of your class)
Don't initialize the static variables in a constructor. static can be called even before instance created for that class.
In your case bookingList is a static and it can be called without creating any object for this class. My be this is the reason for NullPonterException.
I am getting an error when am trying to get the variables in the If else if statements any help will do thanks here is the program
public class Info {
public static void main(String [] args){
char f,F,c,C,h,H;
Scanner input=new Scanner(System.in);
System.out.print("Enter employee num");
int e_num=input.nextInt();
System.out.print("Enter employee first name");
String e_fname=input.next();
System.out.print("Enter employee surname");
String e_sname=input.next();
System.out.print("Enter employee code C or c,H or h and F or f");
char e_code = input.next().charAt(0);
if(e_code=='f' || e_code=='F') {
System.out.print("Enter employee salary: ");
double salary=input.nextDouble();
e_code=calGrossF();
}
else if(e_code=='c'||e_code=='C'){
e_code=calGrossC();
}
else if(e_code=='h'|| e_code=='H'){
e_code=calGrossH();
}
}//end of main
public static void calGrossF(int f, int F){
}//end of Gross(F)
public static char calGrossC(){
}// end of Gross(C)
public static char calGrossH();{
Your code currently has several syntax errors.
Your methods calGrossC() and calGrossH() have to return a char according to the declaration. Currently they just return nothing.
This code e_code=calGrossF(); expects calGrossF() to return a char as well. Currently it is declared to return void.
You did not import the class Scanner (probably just not in the code sample).
callGross() expects two int parameters. You gave none in e_code=calGrossF();.
All those errors are pointed out by the Java compiler. Just get through your error messages one by one and correct the code accordingly.
Not really syntax, but wanted to note it here:
You declare a bunch of variables at the start (f,F,c,C,h,H), but never use them.
Here is a corrected code (just placeholders on several occasions):
import java.util.Scanner;
public class Info {
public static void main(String [] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter employee num");
int e_num=input.nextInt();
System.out.print("Enter employee first name");
String e_fname=input.next();
System.out.print("Enter employee surname");
String e_sname=input.next();
System.out.print("Enter employee code C or c,H or h and F or f");
char e_code = input.next().charAt(0);
if(e_code=='f' || e_code=='F') {
System.out.print("Enter employee salary: ");
double salary=input.nextDouble();
e_code=calGrossF( 0, 0 );
}
else if(e_code=='c'||e_code=='C'){
e_code=calGrossC();
}
else if(e_code=='h'|| e_code=='H'){
e_code=calGrossH();
}
}//end of main
public static char calGrossF(int f, int F){
return 'F';
}//end of Gross(F)
public static char calGrossC(){
return 'C';
}// end of Gross(C)
public static char calGrossH(){
return 'H';
}
}
First of all u have public static void calGrossF(int f, int F) as "void"
and u are storing its value in e_code
and also no arguments is being passed in the calling
//Method Statement
public char calGrossF(String name, int emp_num, double gross_sal, double fix_sal, double
ded, double net_pay, double highest_sal, double lowest_sal,
char ch)
{
//return statement
return calGrossF(name, emp_num, gross_sal, fix_sal, ded, net_pay, highest_sal, lowest_sal, ch);
}