How to efficiently use arguments within methods in java? - java

Im fairly new to Java , and OOP in general hence many concepts in Java dont make complete sense even though the API is thorough. I have made a small calculator code , however I want to learn how to achieve the same product using arguments within method, samples would be prime.
import java.io.IOException;
import java.util.Scanner;
public class Ga {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
System.out.println("First number:");
float i = input.nextInt();
System.out.println("Choose operator +, -, *, /");
char s = input.next().charAt(0);
System.out.println("Second number:");
float z = input.nextInt();
switch (s) {
case '+':
System.out.println("Result= "+(i+z));
System.in.read();
break;
case '-':
System.out.println("Result= "+(i-z));
System.in.read();
break;
case '*':
System.out.println("Result= "+(i*z));
System.in.read();
break;
case '/':
System.out.print("Result= "+(i/z));
System.in.read();
break;
}
}
}

To start with OOP, you could write an abstract class representing an operation:
public abstract class Operation {
public abstract float getResult(float a, float b);
}
Then, try to write concrete operation like Addition, Division:
public class Addition extends Operation {
#Override
public float getResult(float a, float b) {
return a + b;
}
}
public class Division extends Operation {
#Override
public float getResult(float a, float b) {
return a / b;
}
}
Then, rewrite your main method like that:
public static void main(String[] args) throws IOException {
System.out.println("First number:");
float i = input.nextInt();
System.out.println("Choose operator +, -, *, /");
char s = input.next().charAt(0);
System.out.println("Second number:");
float z = input.nextInt();
Operation op = null;
switch (s) {
case '+':
op = new Addition();
break;
case '-':
op = new Subtraction();
break;
...
}
System.out.println("Result= " + op.getResult(i, z));
System.in.read();
}
As Richard mentions it, you could also rewrite the switch with an HashMap:
public static void main(String[] args) throws IOException {
System.out.println("First number:");
float i = input.nextInt();
System.out.println("Choose operator +, -, *, /");
char s = input.next().charAt(0);
System.out.println("Second number:");
float z = input.nextInt();
Map<String, Operation> operationMap = new HashMap<String, Operation>();
operationMap.put("+", new Addition());
operationMap.put("-", new Substraction());
...
Operation op = operationMap.get(s);
System.out.println("Result= " + op.getResult(i, z));
System.in.read();
}

Related

Java program skips an input?

Hello,
I was trying to build a simple calculator using basic Java code and understand OOP better, so, I wrote this:
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num1 = input.nextInt();
System.out.println("Enter an operation: ");
String opr;
opr = input.nextLine();
if(opr == "+") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.addition();
} else if (opr == "-") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.subtraction();
} else if (opr == "*") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.multiplication();
} else if (opr == "/") {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.division();
} else {
System.out.println("Please, Enter a valid operation!");
}
}
}
and another Class for math operations:
import java.util.Scanner;
public class Operation {
static int Num1;
static int Num2;
Scanner input = new Scanner(System.in);
public Operation(int x, int y) {
x = Num1;
y = Num2;
}
public void addition() {
System.out.println(Num1 + Num2);
}
public void subtraction() {
System.out.println(Num1 - Num2);
}
public void multiplication() {
System.out.println(Num1 * Num2);
}
public void division() {
System.out.println(Num1 / Num2);
}
}
but it doesn't take input for the operation, and it goes straight to the next line of code, like so:
Enter a number:
4
Enter an operation:
Please, Enter a valid operation!
Could anyone, please point my mistake?
Note: I'm a newbie in Java and programming in general. so, please don't mind me if my code isn't the best, I'm still learning.
Hello you had a couple of problems. The nextLine() will return an empty line the first time since nextInt consumes the integer only after receiving a new line char but leaves the new line char in the buffer. Additionally the equals comparison needs to be using opr.equals("+") or a switch statement. And finally your Operation class constructor had the variable assignment backwards. I have also modified the Operation private member variables to follow standard naming conventions and scoping practices. You generally want to make member variables private since if not explicitly defined they will be protected. I would recommend using a good IDE since it can catch a lot of those errors for you, try using the free IntelliJ. Here is an updated version of your code.
public class Operation {
private final int num1;
private final int num2;
public Operation(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
public void addition() {
System.out.println(num1 + num2);
}
public void subtraction() {
System.out.println(num1 - num2);
}
public void multiplication() {
System.out.println(num1 * num2);
}
public void division() {
System.out.println(num1 / num2);
}
}
And your main class
public class Calc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num1 = input.nextInt();
System.out.println("Enter an operation: ");
String opr = null;
while(opr == null || opr.length() == 0){
opr = input.nextLine();
}
switch (opr) {
case "+": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.addition();
break;
}
case "-": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.subtraction();
break;
}
case "*": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.multiplication();
break;
}
case "/": {
System.out.println("Enter another Number: ");
int num2 = input.nextInt();
Operation op = new Operation(num1, num2);
op.division();
break;
}
default:
System.out.println("Please, Enter a valid operation!");
break;
}
}
}
Use
input.next
rather than
input.nextLine
as nextInt accepts a number and the new line character \n.
In the switch ts checking for the new line character.

Storing value into another class after a switch statement and reuse the variable in another switch statement

So basically in the case 1 of main function, I am trying to store the two values the user input into another class. Then if I go to case 2 immediately, the output will be the sum of the two values that were input earlier. My question is how to change my code such that case 2 and 3 are able to use the values that I have stored in case 1 earlier? Thank you.
Code for main function:
import java.util.Scanner;
public class calculatorfinal
{
public static void main(String args[])
{
int number1,number2,choice,sum,product;
while(true)
{
Scanner scan = new Scanner(System.in);
operations myoperations=new operations();
System.out.println("\n1. Get numbers");
System.out.println("\n2. Addition");
System.out.println("\n3. Multiplication");
System.out.println("\n4. Exit");
choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("enter the two numbers:");
number1=scan.nextInt();
number2=scan.nextInt();
myoperations.getnumbers(number1,number2);
break;
case 2:
myoperations.addnumbers();
break;
case 3:
myoperations.multiplynumbers();
break;
case 4:
System.exit(0);
break;
}
}
}
}
Code for another class(the operations)
public class operations
{
int a,b;
public void addnumbers()
{
int sum = a+b;
System.out.println("ans is "+sum);
}
public void multiplynumbers()
{
int product = a*b;
System.out.println("ans is "+product);
}
public void getnumbers(int number1,int number2)
{
a=number1;
b=number2;
System.out.println("the first number is "+number1);
System.out.println("the second number is "+number2);
}
}
The problem is that you discard your variable myoperations every time the while-loop ends and creating a new myoperations. Your variable has to stay outside the loop like your ints do. Also the Scanner should stay outside, as long as you do not want to let the garbage collector work unnecessarily.
public static void main(String args[]) {
int number1, number2, choice, sum, product;
operations myoperations = new operations();
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("\n1. Get numbers");
System.out.println("\n2. Addition");
System.out.println("\n3. Multiplication");
System.out.println("\n4. Exit");
choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("enter the two numbers:");
number1 = scan.nextInt();
number2 = scan.nextInt();
myoperations.getnumbers(number1, number2);
break;
case 2:
myoperations.addnumbers();
break;
case 3:
myoperations.multiplynumbers();
break;
case 4:
System.exit(0);
break;
}
}
}
You just have to use the initialisation operations myoperations=new operations(); outside of the while loop. Otherwise you override the instance of the class each time. And so your stored values get lost each time you choose a case.
1.Make your instance variable static to avoid reinitialization
import java.util.Scanner;
class operations
{
static int a,b; //Add static KeyWord
public void addnumbers()
{
int sum = a+b;
System.out.println("ans is "+sum);
}
public void multiplynumbers()
{
int product = a*b;
System.out.println("ans is "+product);
}
public void getnumbers(int number1,int number2)
{
a=number1;
b=number2;
System.out.println("the first number is "+number1);
System.out.println("the second number is "+number2);
}
}
2.Write operations myoperations=new operations(); line out of while loop
class Main {
public static void main(String args[])
{
int number1,number2,choice,sum,product;
Scanner scan = new Scanner(System.in);
operations myoperations=new operations();
while(true)
{
//Scanner scan = new Scanner(System.in);
//operations myoperations=new operations();
System.out.println("\n1. Get numbers");
System.out.println("\n2. Addition");
System.out.println("\n3. Multiplication");
System.out.println("\n4. Exit");
choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("enter the two numbers:");
number1=scan.nextInt();
number2=scan.nextInt();
myoperations.getnumbers(number1,number2);
break;
case 2:
myoperations.addnumbers();
break;
case 3:
myoperations.multiplynumbers();
break;
case 4:
System.exit(0);
break;
}
}
}
}

i cant get my calculator to work

i want to input a int to get first number then use a string to get the operator and another int for the second number. user should input some thing like 10+20.
but as soon as i enter the "+" then i get an error why?
cuz it works if i manually add the values into the sum.calc(); myself like sum.calc(12, "+", 24); then it works ill get 36
PART 1:
import java.util.Scanner;
public static void main(String[] args) {
math sum = new math();
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
String b = input.nextLine();
double c = input.nextDouble();
sum.calc(a, b, c);
input.close();
}
PART 2:
public class math {
public void calc(double a, String b, double c){
double t;
switch(b){
case "+":
t = a + c;
System.out.println(a+" + "+c+" = "+t);
break;
case "-":
t = a - c;
System.out.println(a+" - "+c+" = "+t);
break;
case "*":
t = a * c;
System.out.println(a+" * "+c+" = "+t);
break;
case "/":
t = a / c;
System.out.println(a+" / "+c+" = "+t);
break;
}
}
}
Try using input.next(); instead of input.nextLine(); Because input.nextLine(); advances this scanner past the current line and returns the input that was skipped. so if your input was 20, +, and 24, your method calc would get 20,24,null.
input.next() works instead of input.nextLine() for strings.Try it out

Error in simple java program

I am working on teaching myself java and while working on a code using classes I ran into this error
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at StateCalculator.getOperand(StateCalculator.java:29)
at StateCalculator.main(StateCalculator.java:77)
Below is my code:
import java.util.Scanner;
public class StateCalculator {
private double currentValue = 0;
//Initialize to 0
public StateCalculator() {
}
public static int displayMenu() {
Scanner keyboard = new Scanner(System.in);
int menuChoice = 0;
do {
System.out.print("Menu\n 1. Add\n 2. Subtract\n 3. Multiply\n 4. Divide\n 5.Clear\n 6. Quit\n What would you like to do?: ");
menuChoice = keyboard.nextInt();
} while(menuChoice < 1 || menuChoice > 6);
keyboard.close();
return menuChoice;
}
public static double getOperand(String prompt) {
Scanner input = new Scanner(System.in);
double operand = 0;
System.out.print(prompt);
operand = input.nextDouble();
input.close();
return operand;
}
public double getCurrentValue() {
return currentValue;
}
public void add(double operand) {
currentValue += operand;
}
public void subtract(double operand) {
currentValue -= operand;
}
public void multiply(double operand) {
currentValue *= operand;
}
public void divide(double operand) {
if(operand == 0) {
currentValue = Double.NaN;
}
else {
currentValue /= operand;
}
}
public void clear() {
currentValue = 0;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
StateCalculator calculator = new StateCalculator();
int option;
double operand;
do{
System.out.println("The current value is " + calculator.currentValue);
option = StateCalculator.displayMenu();
switch(option) {
case 1:
operand = getOperand("What is the second number?: ");
calculator.add(operand);
break;
case 2:
operand = getOperand("What is the second number?: ");
calculator.subtract(operand);
break;
case 3:
operand = getOperand("What is the second number?: ");
calculator.multiply(operand);
break;
case 4:
operand = getOperand("What is the second number?: ");
calculator.divide(operand);
break;
case 5:
calculator.clear();
break;
}
}while(option != 6);
keyboard.close();
}
}
I tried running the debug feature in eclipse and discovered the problem occurs on line 29 in my getOperand method when I attempt to set operand = input.nextDouble. However, I don't understand why this would be an issue.
Don't call keyboard.close(); when you close keyboard (which you defined)
Scanner keyboard = new Scanner(System.in);
it closes System.in, and then your other methods can't work (because the console will not re-open). You can have multiple scanners on System.in (as long as you don't close them), or pass one (or, but please don't, use a global).
Per the javadoc,
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

Java calculator switch dont work

I can enter 2 numbers but when I enter an integer for "wahl" (the switch) the result is wrong.
import java.util.Scanner;
public class taschenrechner {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Bitte erste Zahl eingeben:");
int a = s.nextInt();
System.out.println("Bitte zweite Zahl eingeben:");
int b = s.nextInt();
System.out.println("1.+ \n 2.- \n 3.* \n 4. /");
int wahl = s.nextInt();
switch(wahl){
case 1:
addieren(a,b);
break;
case 2:
subtrahieren(a,b);
break;
case 3:
multiplizieren(a,b);
break;
case 4:
dividieren(a,b);
break;
}
System.out.println("Bye Bye World");
}
private static int addieren(int a, int b){
int c = a + b;
return c;
}
private static int subtrahieren(int a, int b){
int c = a - b;
return c;
}
private static int multiplizieren(int a, int b){
int c = a * b;
return c;
}
private static int dividieren(int a , int b){
int c = a / b;
return c;
}
}
Maybe some method leaks?
I wanted to do this with methods and the return function to practice a bit java.
Your methods return int, but you don't seem to use the result and call them as void instead.
Try testing in your switch cases with something like:
System.out.println(multiplizieren(a,b));
It will print the result to sdtout.
Also note that as per both Java and SO convention, code should all be in English (although it's quite clear in this case).
If you want to see the result, use the returned value from the methods in a new variable in main (say, result) or print out the result inside the methods using System.out.println() or something of the sort. For example like this:
int result = 0;
case 1:
result = addieren(a,b);
break;
case 2:
result = subtrahieren(a,b);
break;
case 3:
result = multiplizieren(a,b);
break;
case 4:
result = dividieren(a,b);
break;
}
System.out.println("Result = " + result);
you just return the result...
you have to print the result, too
int result = 0
switch(wahl){
case 1:
result = addieren(a,b);
break;
case 2:
result = subtrahieren(a,b);
break;
case 3:
result = multiplizieren(a,b);
break;
case 4:
result = dividieren(a,b);
break;
}
System.out.println(result)
If you are returning the result then you should put it in some valriable or can directly display by s.o.println
like...
switch(wahl){
case 1:
system.out.println(addieren(a,b));
or
int result = addieren(a,b)
system.out.println(result);
int result = 0
switch(wahl){
case 1:
result = addieren(a,b);
break;
case 2:
result = subtrahieren(a,b);
break;
case 3:
result = multiplizieren(a,b);
break;
case 4:
result = dividieren(a,b);
break;
}
//Print the result using a syso
System.out.println(result)
OK here are a couple of pointers that might be useful:
import java.util.Scanner;
// Class names typically start with a capital letter, good practice to get accustomed to
public class Taschenrechner {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Bitte erste Zahl eingeben:");
int a = s.nextInt();
System.out.println("Bitte zweite Zahl eingeben:");
int b = s.nextInt();
System.out.println("1.+ \n 2.- \n 3.* \n 4. /");
int wahl = s.nextInt();
switch(wahl){
case 1:
addieren(a,b); // <- nothing happens to the result!!
break;
case 2:
subtrahieren(a,b); // <- nothing happens to the result!!
break;
case 3:
multiplizieren(a,b); // <- nothing happens to the result!!
break;
case 4:
dividieren(a,b); // <- nothing happens to the result!!
break;
default: // <- always good to have a default in a switch
// warn user that invalid option is entered
}
System.out.println("Bye Bye World");
}
// dont need the integer "c" as you never use it locally.
private static int addieren(int a, int b){
retrun a + b;
}
private static int subtrahieren(int a, int b){
return a - b;
}
private static int multiplizieren(int a, int b){
return a * b;
}
private static int dividieren(int a , int b){
return a / b;
}
}
I suppose you made the 4 operation methods static, since you call it in main, and the compiler complains about static reference? If so, read a bit about what static means; and consider creating an instance of your calculator by:
supplying a constructor method, and
creating an instance of it in your main something like:
Taschenrechner t = new Taschenrechner();
t.addieren(a,b); //the methods don't need to be static anymore :)
Hope it helps
You can use this example
package com.alindal.calc;
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
System.out.println("Select an option : \n 1:Addition 2:Subtraction 3:Multiplication 4: Division");
// TODO Auto-generated method stub
Scanner read=new Scanner(System.in);
int x=read.nextInt();
switch(x)
{
case 1:
add();
break;
case 2:
sub();
break;
case 3:
multi();
break;
case 4:
div();
break;
default:
System.out.println("Invalid choice");
}
}
public static void add()
{
Scanner read=new Scanner(System.in);
System.out.println("Enter the values a and b");
int a=read.nextInt();
int b=read.nextInt();
int c=a+b;
System.out.println("The sum is "+c);
}
public static void sub()
{
System.out.println("Enter the values a and b");
Scanner read=new Scanner(System.in);
int a=read.nextInt();
int b=read.nextInt();
int c=a-b;
System.out.println("The difference is "+c);
}
public static void multi()
{
System.out.println("Enter the values a and b");
Scanner read=new Scanner(System.in);
int a=read.nextInt();
int b=read.nextInt();
int c=a*b;
System.out.println("The product is "+c);
}
public static void div()
{
System.out.println("Enter the values a and b");
Scanner read=new Scanner(System.in);
int a=read.nextInt();
int b=read.nextInt();
int c=a/b;
System.out.println("The division is "+c);
}
}

Categories