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);
}
}
Related
I'm developing a maths quiz program which will ask the user whether the wanna have Addition, Subtraction, Division or Multiplication quiz. So by using switch case statement can I access the method?
public static void Addition(){
}
public static void Subtraction(){
}
public static void Division(){
}
Public static void Multi(){
}
static void option(){
Scanner input = new Scanner(System.in);
int choice = 0;
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice){
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
default:
break;
}
Proper syntax would be, for example:
switch (choice){
case 1:
Addition();
break;
case 2:
Subtraction();
break;
case 3:
Division();
break;
case 4:
Multi();
break;
default:
break;
}
I would recommend usually naming methods in Java with camelcase
I think you really want something like this:
public static double add(double x, double y){
return x + y;
}
public static double subtract(double x, double y){
...
}
public static void divide(double x, double y){
...
}
public static double multiply(double x, double y){
...
}
public static void main (String[] args ) {
Scanner input = new Scanner(System.in);
int choice = -1;
while (choice != 5) {
System.out.print("1) add, 2) subtract, 3) divide, 4) multiply 5) quit");
int choice = input.nextInt();
// Get x, y, result
switch (choice){
case 1:
result = add(x, y);
break;
case 2:
result = subtract(x, y);
break;
case 3:
result = divide(x, y);
break;
case 4:
result = multiply(x, y);
break;
default:
System.out.println("Exiting program...");
return;
break;
}
}
Note that you should probably leverage the ability to pass a "return value" from functions (methods). Note, too, that methods are usually "camel case" (e.g. "addNumbers()", instead of "Addition()".
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;
}
}
}
}
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();
}
I was wondering how I should initialize int c from the switch statement. I can't figure out how to "extract" the random switch-argument into the final answer. I am a beginner so maybe I am missing something obvious here. Here is the code that I have so far:
import java.util.*;
public class whileTest{
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
String a;
do{
String operatorSwitch;
int b;
int c;
Random number = new Random();
int d = number.nextInt(100) +1;
int e = number.nextInt(100) +1;
Random operatorChoice = new Random();
int operator = operatorChoice.nextInt(4);
switch (operator){
case 0: operatorSwitch= "+";
c = d+e;
break;
case 1: operatorSwitch= "-";
c = d-e;
break;
case 2: operatorSwitch= "*";
c = d*e;
break;
case 3: operatorSwitch= "/";
c = d/e;
break;
default: operatorSwitch= "";
}
System.out.println("What is: "+d+operatorSwitch+e+"?");
b = sc.nextInt();
if(b!=c)
System.out.println("Wrong answer! Right answer is: "+c);
else{if(b==c)
System.out.println("Right answer!"+c);
}
System.out.println("Continue? y/n");
a = sc.next();
}while(a.equals("y"));
}
}
As a practice, unless you have a good reason not too, you should always explicitly initialize your variables. In this case you want to change this:
String operatorSwitch;
int b;
int c;
To this:
String operatorSwitch = null;
int b = 0;
int c = 0;
The problem with your current code is a compilation one, due to the variable 'c' possibly not being initialized.
Not sure how pretty you wish to make this but you could write an Operator interface with anonymous subclasses and pick a random index from those.
interface Operator{
public int operateOn( int a, int b );
public char getDisplayChar();
}
Operator[] operators = {new Operator(){
public int operateOn(int a, int b){
return a + b;
}
public char getDisplayChar(){
return '+';
}
}, new Operator(){
public int operateOn(int a, int b){
return a - b;
}
public char getDisplayChar(){
return '-';
}
} // etc.
};
I had been given an assignment to implement ArrayList and LinkedList without using generics. The problem is with the insertnode() method. Though I try to read from commandline using a scanner, the method returns without waiting.
import static java.lang.System.out;
import java.util.Scanner;
class Arraylist
{
public static final int LIST_SIZE=30;
static Scanner input = new Scanner(System.in);
static Object list[];
static int top = -1;
static int typeoflist;
public static void displaymenu()
{
int choice;
do{
out.print("\n Basic operations on a linked list:");
out.print("\n 1. Create list \n 2. Insert node \n 3. Delete node \n 4. Modify node \n 5. Search value \n 6. Print list\n Else. Exit \n Choice:");
choice = input.nextInt();
switch(choice)
{
case 1:
list = createlist();
break;
case 2:
insertnode();
break;
case 3:
//deletenode();
break;
case 4:
//modifynode();
break;
case 5:
//searchnode();
break;
case 6:
printlist();
break;
default:
return;
}
}while(true);
}
public static Object[] createlist()
{
int typeoflist;
out.println("Enter your choice of list datatype: \n 1. int \n 2. float \n 3. char \n 4. String \n 5. UserDefined \n Choice:");
typeoflist = input.nextInt();
switch(typeoflist)
{
case 1:
list = new Integer[LIST_SIZE];
break;
case 2:
list = new Float[LIST_SIZE];
break;
case 3:
list = new Character[LIST_SIZE];
break;
case 4:
list = new String[LIST_SIZE];
break;
}
return (Object[])list;
}
public static void insertnode()
{
Object o;
top++;
out.println("Enter the value to insert:");
switch(typeoflist)
{
case 1:
o = (Integer)input.nextInt();
list[top] = o;
break;
case 2:
o = (Float)input.nextFloat();
list[top] = o;
break;
case 3:
//o = (Character)input.next(); //
//list[top] = o;
break;
case 4:
o = (String)input.next();
list[top] = o;
break;
}
}
public static void printlist()
{
for(int i =0; i<top; i++)
{
out.println(list[i]);
}
}
public static void main(String[] args)
{
displaymenu();
}
}
Hint: typeoflist in createList() is hiding the static member variable.