How take user input in one method and use it in another - java

I am very new to java and have searched around and can't seem to find what to do. I need to take int number and be able to use it in another method. I have to use two methods to do this. I am unsure how to call upon it.
public static void first()
{
System.out.print("Enter number: ")
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
}
public static void getNumber(String name, int move)
{
if (number == 1)
{
System.out.println("Player shows one" );
}

Make a method which return a number and call it from another method.
public static int first()
{
System.out.print("Enter number: ")
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
return number;
}
public static void getNumber(String name, int move)
{
int number = first(); //Call method here.
if (number == 1)
{
System.out.println("Player shows one" );
}
}

Define number as a class attribute.
Something like (its not final/working code)
class myClass{
int number = 3; // Or any other default value
public static void first()
{
//....
obj.number = scan.nextInt();
//...
}
public static void getNumber(String name, int move)
{
if (obj.number == 1)
{
//......
}
}
}

After int number call method
int number = scan.nextInt();
getNumber("Your Name", number);

Related

How can I use parameters to pass down a non constant variable value to a method?

I'm struggling with passing a variable value that a user has entered into my program into a method. I think the technical word is parameters.
The problem I'm having is that after the user enters a number in the getnum() method I want the number to be passed down to the two methods calculation and `calculation_two. However, I can't seem to be able to achieve it.
Just to explain the program, the user enters a number in the getnum() method, then they go to the option method and after they select what option, in the calculations methods the number that was written in the getnum() method needs to be passed down the the calculations methods. Therefore, I will then be able to perform calculations with it that way. I need the program to be set up like this as well for my own personal reasons.
Can anyone assist please?
Thanks
public static void main (String[]args){
getnum();
}
public static void getnum() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = input.nextInt();
option();
}
public static void option() {
Scanner input2 = new Scanner(System.in);
System.out.println("would you like to see option 1 or 2");
int num2 = input2.nextInt();
if(num2==1) {calculation();}
else if(num2==2) {calculation_two();}
else {System.exit(0);}
}
public static void calculation() {
}
public static void calculation_two() {
}
Please see call by reference and call by value to further clarify how primitives or objects are passed from one method to another.
Here are the steps to pass the parameter from one method to another:
You pass the int you got from the scanner as an argument in the option method call:
public static void getnum() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = input.nextInt();
option(num); // You pass the int as an argument
}
Now, since you are now calling a method with arguments you need to change the signature of the option method to take a parameter. You pass the int value(theNumber variable) from the option method's parameter to the calculation method call.
Arguments and parameters are terms which are used interchangeably but you can check the difference here.
public static void option(int theNumber) { // option now takes a int parameter
Scanner input2 = new Scanner(System.in);
System.out.println("would you like to see option 1 or 2");
int num2 = input2.nextInt();
if(num2==1) {
calculation(theNumber); // method now takes an argument
}
else if(num2==2) {
calculation_two(theNumber); // method now takes an argument
}
else {System.exit(0);}
}
You pass the parameter again to the calculation(s) method and change the signature to:
public static void calculation(int theNumber) { // method with parameter
}
public static void calculation_two(int theNumber) {
}
Declare your methods to use parameters and return values. Easiest way to do it:
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = input.nextInt();
System.out.println("would you like to see option 1 or 2");
int option = input.nextInt();
int result = 0;
if (option == 1) {
result = calculation(num);
} else if (option == 2) {
result = calculation_two(num)
} else {
System.out.println("Invalid option, exiting...");
System.exit(0);
}
System.out.println("Result = " + result);
}
private static int calculation(int num) {
// implement this
return 0;
}
private static int calculation_two(int num) {
// implement that
return 0;
}
To answer with secure coding practices
package in.faridabad.mandheer;
public class Main{
public static void main (String[]args){
Main m = new Main();
// Assuming calculation is "sum"
System.out.println("sum is + "+ m.option());
}
private int getnum() {
Scanner input = new Scanner(System.in);
return input.nextInt();
}
int option() {
System.out.println("would you like to see option 1 or 2");
int num2 = getnum();
if(num2==1) {return calculation();}
else if(num2==2) {return calculation_two();}
else {System.exit(0);}
}
private int calculation() {
System.out.println("Enter a number: ");
int num1 = getnum();
return num1;
}
private int calculation_two() {
System.out.println("Enter a number: ");
int num1 = getnum();
System.out.println("Enter 2nd number: ");
int num2 = getnum();
return num1+num2;
}
}

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);
}
}

Recursive methods which exclude each other?

I am trying to write a method that calculates the sum of odd integers between 1 and a given positive integer n, without using anything else than if statements (sheesh!). It worked out just fine until I decided to also create a method that would ask recursively for the number until it was positive and use it to get n.
Now my program outputs the correct results until I enter a negative number. It then asks for a postive one until I enter one and it outputs 0, the value I initialised the variable val with.
I'm not sure where the logic error is. Could you please take a look? I'm sure it's something obvious, but I guess I have just reached the end of my wits today. Thanks!
package oddsum;
import java.util.Scanner;
public class Oddsum {
public static int oddSum(int n){
int val=0;
if(n>1){
if(n%2==0){
val=n+oddSum(n-1);
}else{
val=oddSum(n-1);
}
}
return val;
}
public static int request(int n){
Scanner in= new Scanner(System.in);
System.out.println("Give me a positive integer: ");
n=in.nextInt();
if (n<0){
System.out.println("I said positive! ");
request(n);
}
return n;
}
public static void main(String[] args) {
int val=0;
int n=request(val);
System.out.println(oddSum(n));
}
}
You should remove input parameter from your request() method. Because your negative input is carried out through the recursive call.
public class Oddsum {
public static int oddSum(int n) {
int val = 0;
if (n > 1) {
if (n % 2 == 0) {
val = n + oddSum(n - 1);
} else {
val = oddSum(n - 1);
}
}
return val;
}
public static int request() {
Scanner in = new Scanner(System.in);
System.out.println("Give me a positive integer: ");
int n = in.nextInt();
if (n < 0) {
System.out.println("I said positive! ");
return request();
}
return n;
}
public static void main(String[] args) {
int n = request();
System.out.println(oddSum(n));
}
}
Output;

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);
}
}

Beginner to java and not sure what this means

import java.util.*;
public class decimalToBinaryTest {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive interger");
number = in.nextInt();
if (number < 0) {
System.out.println("Not a positive interger");
}
else {
System.out.print("Convert to binary is: ");
System.out.print(binaryform(number) + ".");
}
}
private static Object binaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return null;
}
remainder = number % 2;
binaryform(number >> 1);
System.out.print(remainder);
{
return " ";
}
}
}
In the main part of a program an int variable was created. In the next part is says private static Object binaryform ( int number ). Is the int number in the Objectrelating to the variable I the main method?
Yes and no. The variable name number has nothing to do with the main method. It is a formal parameter to the method named binaryform. The parameter number only exists within the method itself. However, when binaryform is called, the actual value of the variable (or constant) used in the call becomes the value of number while the method is executing.
public class Example {
public static void main(String[] args) {
int n = 3; // the name could be "number" and no behavior would change
Object bf = binaryForm(n);
// do something with bf
}
private static Object binaryform(int number) {
// from the call above, number will have the value 3
Object o = . . .;
// generate or modify o from the value of number
return o;
}
}

Categories