How to access arguments of one method in another method? - java

/*
Program for salary incrementation
*/
import java.util.*;
class Increment
{
Scanner sc = new Scanner(System.in);
void getdata(String n, double d, int a)
{
System.out.print("Enter name of employee ");
n = sc.nextLine();
System.out.println("Enter current salary ");
d = sc.nextDouble();
System.out.println("Enter age");
a = sc.nextInt();
}
void calculate()
{
if(a>=56)
{
d = d+(20/100);
}
if(a>45&&a<56)
{
d = d+(15/100);
}
if(a<=45)
{
d = d+(10/100);
}
}
void display()
{
System.out.println("Name \t Age \t Basic ");
System.out.print(n +"\t"+ d + "\t" + a);
}
public static void main(String[] args)
{
Increment i = new Increment();
i.getdata();
i.calculate();
i.display();
}
}
How can I use values of n, d and a in calculate() method?
Please help me if you find any other mistake!

You have getdata return the information (as an object with private fields and getters [at least] for them), and then you pass that object into calculate and have calculate use the getters to get the values. (Similarly, this is how you would get information from calculate into display.)
You could also make them fields in Increment, but that makes Increment stateful (prior to calling getdata, it doesn't have the necessary information), which is generally best avoided.

In this case you need to have instance variables, so you can use them in methods
class Increment
{
String n; double d; int a;
Scanner sc = new Scanner(System.in);
void getdata()
{
System.out.print("Enter name of employee ");
n = sc.nextLine();
System.out.println("Enter current salary ");
d = sc.nextDouble();
System.out.println("Enter age");
a = sc.nextInt();
}
void calculate()
{
if(a>=56)
{
d = d+(20/100);
}
if(a>45&&a<56)
{
d = d+(15/100);
}
if(a<=45)
{
d = d+(10/100);
}
}
void display()
{
System.out.println("Name \t Age \t Basic ");
System.out.print(n +"\t"+ d + "\t" + a);
}
public static void main(String[] args)
{
Increment i = new Increment();
i.getdata();
i.calculate();
i.display();
}
}

You must declare the variables you are using
String n;
double d;
int a;
Also the main put it in another class.
In method "calculate" use the switch

Related

Encountered Issues Using Multiple Methods on the Same Code

I am a fairly new programmer in Java and am currently learning about how to incorporate multiple methods in one code. The goal of this practice activity is to use several different methods to:
-Create two arrays (one for employee names and another for how much that employee sold)
-Find the average of total sales
-Find the highest sale number
-Find the name of the Employee(s) with the highest sale count (and print "hooray" for every employee that had the highest sale count)
import java.util.*;
public class MethodActivity{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] names={"Employee A", "Employee B", "Employee C", "Employee D", "Employee E", "Employee F", "Employee G", "Employee H", "Employee I", "Employee J"};
System.out.print("Enter the sales numbers, in dollars, for each employee: ");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int num3 = sc.nextInt();
int num4 = sc.nextInt();
int num5 = sc.nextInt();
int num6 = sc.nextInt();
int num7 = sc.nextInt();
int num8 = sc.nextInt();
int num9 = sc.nextInt();
int num10 = sc.nextInt();
double[] sales={num1, num2, num3, num4, num5, num6, num7, num8, num9, num10};
return double[] sales;
return String[] names;
}
public static double getAverage(double[] sales){
double average=(num1+num2+num3+num4+num5+num6+num7+num8+num9+num10)/10;
return average;
}
public static int getHighestSale(double[] sales){
double highest = sales[0];
int locationOfHighest=0;
if(sales[1]>highest){
highest=sales[1];
locationOfHighest=1;
}else if(sales[2]>highest){
highest=sales[2];
locationOfHighest=2;
}else if(sales[3]>highest){
highest=sales[3];
locationOfHighest=3;
}else if(sales[4]>highest){
highest=sales[4];
locationOfHighest=4;
}else if(sales[5]>highest){
highest=sales[5];
locationOfHighest=5;
}else if(sales[6]>highest){
highest=sales[6];
locationOfHighest=6;
}else if(sales[7]>highest){
highest=sales[7];
locationOfHighest=7;
}else if(sales[8]>highest){
highest=sales[8];
locationOfHighest=8;
}else{
highest=sales[9];
locationOfHighest=9;
}
return highest;
}
public static String showName(String[] names){
String nameOfHighest = "";
String hooray = "";
for (int i = 0; i<names.length; i++){
if (i=locationOfHighest){
nameOfHighest=nameOfHighest+names[i]+", ";
hooray = ""+"hooray ";
}else{
nameOfHighest=nameOfHighest;
}
}
return nameOfHighest;
}
public static void (String[] args){
System.out.println("The average sales for today was: "+average);
System.out.println(nameOfHighest+" made the highest sales of "+highest);
System.out.println(hooray);
}
}
However, when I run the program, I got these errors. The thing is, I don't really understand what they mean:
MethodActivity.java:20: error: '.class' expected
return double[] sales;
^
MethodActivity.java:21: error: '.class' expected
return String[] names;
^
MethodActivity.java:75: error: <identifier> expected
public static void (String[] args){
I would really appreciate if someone could clarify what these mean, since I'm still quite confused by the concept of a multi method code. And, if you could, maybe point out any other issues or fixable elements in my code (since I know my code might look pretty sloppy to someone with programming experience and I could really use some pointers). Thank you for your time.
You need to remove this both returns.
There are two problem in your code:
1) java method can have only one return statement.
2) it is main method and because of it returns void type. void means no return type.
Rather using separate method for printing "public static void (String[] args), print those in main method itself.
Also refer answer by iMBMT.
import java.util.Scanner;
public class MethodActivity {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of employees : ");
int totalEmployeeCount = sc.nextInt();
System.out.println("## totalEmployeeCount : " + totalEmployeeCount);
String[] employeeNames = new String[totalEmployeeCount];
int[] employeeSoldCount = new int[totalEmployeeCount];
String name;
int count;
for (int index = 0; index < totalEmployeeCount; index++) {
System.out.print("Enter employee name : ");
name = sc.next();
System.out.print("Enter employee sale count : ");
count = sc.nextInt();
employeeNames[index] = name;
employeeSoldCount[index] = count;
}
System.out.println("---------------- Pringting all info ----------------");
for (int i = 0; i < employeeNames.length; i++) {
System.out.println("name : " + employeeNames[i] + " & sale count : " + employeeSoldCount[i]);
}
findTheAverageOfTotalSales(employeeSoldCount);
findTheHighestSaleNumber(employeeSoldCount);
}
private static void findTheAverageOfTotalSales(int[] employeeSoldCount) {
for (int saleCount : employeeSoldCount) {
System.out.println("Write your own code ...");
}
}
private static void findTheHighestSaleNumber(int[] employeeSoldCount) {
for (int saleCount : employeeSoldCount) {
System.out.println("Write your own code ...");
}
}
}

Meaning and how to get and work with a return value from a user input in a method in java

I am trying to write a java program which have two classes. The second class will have the main method and for checking the balance of the account and. The first class will have three methods one for opening an bank account, one for deposit and one for withdrawal. All input needs to be given by user. I am new to java and stuck after at one point any help would be appreciated.
import java.util.Scanner;
class Balance {
static int account()
{ Scanner minimumAmount = new Scanner(System.in);
int openingAmount = minimumAmount.nextInt();
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account:" + openingAmount);
if (openingAmount > 1000)
{
System.out.println("Your Bank account has opened successfully");
int ac = minimumAmount.nextInt();
System.out.println("Enter your account number" + ac);
}
}
static int withdrawal() {
Scanner withdrawalAmount = new Scanner(System.in);
int w = withdrawalAmount.nextInt();
System.out.println("Withdrawal Amount is :" + w);
int b = openingAmount - w;
if (b < 100) {
System.out.println("Unable to process your request");
}
}
void deposit() {
Scanner depositAmount = new Scanner(System.in);
int d = depositAmount.nextInt();
System.out.println("Deposited amount is :" + d);
int b = openingAmount + d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
}
}
i) Is there a way where an user input variable declared under one method can be used in another method to declare another variable?
ii) ow to return a value from a method so that the value received works in different method while declaring a variable?
Is there a way where an user input variable declared under one method
can be used in another method to declare another variable?
You can declare your attribute in your class and use constructor to initialize it for example :
class A{
private String name;
public A(String name){
this.name = name
}
public int account(){
//can use and change the name
}
public int withdrawal(){
//can use and change the name
}
public int deposit(){
//can use and change the name
}
}
Main class
public class B{
public static void main(String[] args) {
A s = new A("Hello");
//------------^^---pass your attribute in the constructor
s.account();
s.withdrawal();
s.deposit();
}
}
How to return a value from a method so that the value received works
in different method while declaring a variable?
You can use the result of each method in another method for example :
s.withdrawal(s.account());
//--------------^^-------account return a result that can be used by withdrawal
I don't know what you really want to do, but I can explain some things.
Methods account() & withdrawal() don't have to be static.
You can use instance attribute like I do to store values.
Balance & AccountBalance should be in different files.
Take a look about private & public on attribut & methods (& getter/setter)
Scanner is a little bit tricky so you should declare it once, and reuse it.
If you want to use returned value from function, change void by int (in this case) and use "return var" (var is what you want to return). So when you can call the function like this -> int value = s.account();
Try this code, it works.
Cheers !
import java.util.Scanner;
class Balance {
private Scanner scanner;
public int userAccount;
public int userAccountNumber;
public Balance() {
scanner = new Scanner(System.in);
}
public void account() {
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account : ");
int openingAmount = scanner.nextInt();
if (openingAmount > 1000) {
System.out.println("Your Bank account has opened successfully");
userAccount = openingAmount;
System.out.println("Enter your account number : ");
userAccountNumber = scanner.nextInt();
} else {
System.out.println("Not enought money");
this.account(); //Ask again for opening an account
}
}
public void withdrawal() {
System.out.println("Withdrawal Amount is : ");
int w = scanner.nextInt();
int b = userAccount - w;
if (b < 100) {
System.out.println("Unable to process your request");
} else {
userAccount = b;
}
}
public void deposit() {
System.out.println("Deposited amount is : ");
int d = scanner.nextInt();
userAccount += d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
System.out.println("Final amount is : "+s.userAccount);
}
}

How do I use the interface for this number reverse program, instead of using the program entry itself? (JAVA)

I need to know how to add the input as the number to be reversed. This questions answer should help anyone who has the need to make an input go into a program and come out modified.
import java.util.Scanner;
public class NumberReverse {
public int reverseNumber(int number){
System.out.print("Enter a number: "); <------ input
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
NumberReverse nr = new NumberReverse();
System.out.println("Result: " +nr.reverseNumber(Where I want the input to go / or you can put a number here inside of the program, instead of using the interface.));
}
}
I think best way to handle input in the main method and then trigger to reverseNumber with input value;
public class NumberReverse {
public int reverseNumber(int number){
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
try {
NumberReverse nr = new NumberReverse();
System.out.println("Result: " +nr.reverseNumber(Integer.valueOf(input)));
} catch (NumberFormatException nme) {
System.err.println("You entered not numeric value...!");
}
}
}
You can pass the number as the argument of the main:
public static void main(String a[]) {
NumberReverse nr = new NumberReverse();
System.out.println("Result: "+ nr.reverseNumber(Integer.parseInt(a[0])));
}
If you don't want interface, then remove Scanner statements and pass number as argument like below
public int reverseNumber(int number){
int reverse = 0;
while(number !=0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
reverseNumber nr = new reverseNumber();
System.out.println("Result: " +nr.reverseNumber(52)); //pass the number you wish to reverse
}

Passing another instance of the same class and comparing it's stored values to current stored values

Last objective of my assignment asks to create a method matches(). It receives another GenericMemoryCell as a parameter, and returns true if both of its stored values can be found in the stored values of the current GenericMemoryCell. Order of stored values is not important.
Creating the method was not difficult, but I am lost on how to call it from main() because I cannot wrap my head around the concept of passing another instance of GenericMemoryCell. Where am I getting another pair of storedValueA and storedValueB in the first place? Is matches() "running" a virtual instance of the entire program within itself?
import java.util.*;
public class GenericMemoryCell<T>{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter valueA: ");
String readerA = input.next();
System.out.print("Enter valueB: ");
String readerB = input.next();
GenericMemoryCell<String> values = new GenericMemoryCell<>(readerA, readerB);
System.out.println("storedValueA: " + values.readA());
System.out.println("storedValueB: " + values.readB());
values.writeA(readerA);
values.writeB(readerB);
}
public GenericMemoryCell(T storedValueA, T storedValueB)
{ this.storedValueA = storedValueA; this.storedValueB = storedValueB; writeA(storedValueA); writeB(storedValueB); }
public T readA()
{ return storedValueA; }
public T readB()
{ return storedValueB; }
public void writeA(T x)
{ storedValueA = x; }
public void writeB(T y)
{ storedValueB = y; }
public boolean matches(GenericMemoryCell<T> that){
return (this.storedValueA.equals(that.storedValueA) && this.storedValueB.equals(that.storedValueB)); }
private T storedValueA, storedValueB;
}
I think you need something like this
public class GenericMemoryCell {
public static void main(String[] args) {
GenericMemoryCell g1 = new GenericMemoryCell();
//set g1 values here
GenericMemoryCell g2 = new GenericMemoryCell();
//set g2 values here
System.out.println(g1.matches(g2));
}
public boolean matches(GenericMemoryCell g) {
//implement the logic here
return ...;
}
}
Hopefully, it might work for you. However, if you want system to ask for inputs repeatedly, you need to some kind of loop.
public class GenericMemoryCell {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first input: ");
int firstInput = scanner.nextInt();
System.out.println("Please enter second input");
int secondInput = scanner.nextInt();
list.add(firstInput);
list.add(secondInput);
Scanner scannerObj = new Scanner(System.in);
System.out.println("Please enter first input: ");
int firstArg = scannerObj.nextInt();
System.out.println("Please enter second input: ");
int secondArg = scannerObj.nextInt();
boolean isMatches = isInputMatches(firstArg, secondArg, list);
if (isMatches) {
System.out.println("These inputs were already stored before. Please try again with different inputs");
} else {
System.out.println("The inputs are successfully stored. Thank you.");
}
scanner.close();
scannerObj.close();
}
private static boolean isInputMatches(int firstArg, int secondArg, List<Integer> list) {
return list.contains(firstArg) && list.contains(secondArg);
}
}

Need to call a method from a specific class

I need to call the method getAmount() from the Service class only. I do not want to add the values of the Purchaser class. Is there a way I can call the method explicitly from the Service class? I have put a ** where I am referring to.
package prog24178.assignment;
import java.util.Scanner;
public class Assignment3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int MAX = 99999; // Max array size.
Customer [] cust = new Customer[MAX];
int choice = 0;
int cnt = 0;
double total = 0;
//loop to choose customer type and create a new object.
for(cnt=0; cnt < MAX && (choice == 1 || choice ==2 || choice == 0); cnt++){
System.out.println("For a Service customer type 1, for a Purchaser type 2, to terminate the program press any number besides 1 or 2");
choice = s.nextInt();
switch (choice){
case 1:
cust [cnt] = new Service();
break;
case 2:
cust [cnt] = new Purchaser();
break;
default:
break;
}
}
//loop to print the entries
for(int i=0; i < cnt; i++){
if(cust[i]!= null)
cust[i].showData();
}
//loop to print the total for the service objects.**THIS IS LOOP I AM //REFFERING TO
for(int i=0; i < cnt; i++ ){
if(cust[i]!= null)
total = cust[i].getAmounts() + total;
}
System.out.println("Monthly invoice total: " + total);
s.close();
}
}
interface Functions {
public void getData();
public void showData();
public double getAmounts();
}
abstract class Customer implements Functions {
protected String name;
}
class Purchaser extends Customer {
protected double payment;
public Purchaser(){
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter payment amount: ");
payment = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s Payment amount is: %.2f\n",name,payment);
}
//**I DO NOT WANT TO CALL THIS METHOD
public double getAmounts(){
return this.payment;
}
}
class Service extends Customer {
protected String date;
public double amount;
public Service () {
getData();
}
public void getData() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the customer");
name = s.nextLine();
System.out.println("Enter date of Service: ");
date = s.nextLine();
System.out.println("Enter the cost of Service: ");
amount = s.nextDouble();
}
public void showData() {
System.out.printf("Customer name: %s The date is: %s, the Amount owed is: %.2f\n",name, date, amount);
}
//**THIS IS THE METHOD I NEED TO CALL
public double getAmounts(){
return this.amount;
}
}
Check your customer for type:
if (cust[i] instanceof Service) {
total = cust[i].getAmounts() + total;
}
That takes care of the null check automatically as well.

Categories