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()".
Related
I am trying to convert a roman numeral entered by the user into the correct value it represents.
My code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the a roman numberal (I, V, X, L, C, D, M): ");
String romanNumeral = in.nextLine();
romanNumeralToInt(romanNumeral);
System.out.println(romanNumeral);
}
public static int romanNumeralToInt(String romanNumeral) {
switch (romanNumeral) {
case "I":
romanNumeral = 1;
break;
case "V":
romanNumeral = 5;
break;
case "X":
romanNumeral = 10;
break;
case "L":
romanNumeral = 50;
break;
case "C":
romanNumeral = 100;
break;
case "D":
romanNumeral = 500;
break;
case "M":
romanNumeral = 1000;
break;
}
}
I have tried numerous different ways of converting this. I tried to use char instead of string but the same problem came up.
I have also tried to use the line:
public static int romanNumeralToInt(String romanNumeral, int romanDecimal) {
and then using:
case "I":
romanDecimal = 1;
break;
Which didn't work.
I have tried printing out just System.out.println(romanNumeral) which also didn't work.
I am kinda stuck and don't really understand how I go about returning a value as an integer when it was inputted as a string in a method
The current code you have pasted here does not seem right. No return written for the method, even though it clearly has an int return type. Was it compiled correctly?
Anyhow, change your method to have a return;
public static int romanNumeralToInt(String romanNumeral) {
int intNumeral = 0;
switch (romanNumeral) {
case "I":
intNumeral = 1;
break;
case "V":
intNumeral = 5;
break;
case "X":
intNumeral = 10;
break;
case "L":
intNumeral = 50;
break;
case "C":
intNumeral = 100;
break;
case "D":
intNumeral = 500;
break;
case "M":
intNumeral = 1000;
break;
}
return intNumeral;
}
Then in the main method let the methods return variable be stored in an int type variable;
int intNumericConverted = romanNumeralToInt(romanNumeral);
Welcome to stackoverflow!
My first thought is that you're not using your return value from your function, to do this, add a return statement instead of a break statement.
it should read
case "I":
return 1;
then return from it:
System.out.println(romanNumeralToInt("I"));
Or , simply make sure youre assigning strings instead of integers inside your function :
case "I":
romanNumeral = "1";
break;
but to accomplish this, you'll need to change the scope of romanNumeral to global if im not mistaken and this wouldnt be the best practice, in my opinion
You don't need to convert it you can simply return integer values like this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the a roman numberal (I, V, X, L, C, D, M): ");
String romanNumeral = in.nextLine();
romanNumeralToInt(romanNumeral);
System.out.println(romanNumeral);
}
public static int romanNumeralToInt(String romanNumeral) {
switch (romanNumeral) {
case "I":
return 1;
case "V":
return 5;
case "X":
return 10;
case "L":
return 50;
case "C":
return 100;
case "D":
return 500;
case "M":
return 1000;
}
}
Integer class has static method toString() - you can use it:
int i = 1234;
String str = Integer.toString(i);
Returns a String object representing the specified integer. The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and radix 10 were given as arguments to the toString(int, int) method.
i have a problem i dont know what to put on case section, when ever the user input their grades from 0-100 there are output corresponds to their grades failed,good,verygood,excellent.
import java.util.Scanner;
public class ProgTestI {
public static void main (String args[]){
Scanner pao = new Scanner(System.in);
System.out.print("Grades: ");
String grades = pao.next();
int grado = Integer.parseInt(grades);
switch (grado){
case =<74: /* iwant to put 0 to 74*/
System.out.println("Failed");
case : /* 75-80*/
System.out.println("bellow average");
case : /*81-85*/
System.out.println("average");
case : /*86-90*/
System.out.println("Good");
case : /*91-96*/
System.out.println("VeryGood");
default:
}
}
}
You cannot use switch for ranges, you need to replace this chunk of code with proper if/else blocks.
Switch works only on numeric values, but it works like
if(numericVal == 40)
So writing it for ranges is... waste of code, and not readable.
You need to rewrite it:
if( g <= 74){
...
}else if( g > 74 && g <= 80 ){
...
Your case code is incorrect, you can do as Beri mentioned.
If you want to implement switch statement in your application, then you can do as follows:
public static void main(String[] args) {
Scanner pao = new Scanner(System.in);
System.out.print("Grades: ");
String grades = pao.next();
int grado = Integer.parseInt(grades);
int checkedCase=0;
if(grado<=74){
checkedCase=1;
}
else if(grado>=75&&grado<=80){
checkedCase=2;
}
else if(grado>=81&&grado<=85){
checkedCase=3;
}
else if(grado>=86&&grado<=90){
checkedCase=4;
}
else if(grado>=91&&grado<=96){
checkedCase=5;
}
switch (checkedCase){
case 1: /* iwant to put 0 to 74*/
System.out.println("Failed");
break;
case 2: /* 75-80*/
System.out.println("bellow average");
break;
case 3: /*81-85*/
System.out.println("average");
break;
case 4: /*86-90*/
System.out.println("Good");
break;
case 5: /*91-96*/
System.out.println("VeryGood");
break;
default: System.out.println("Please enter a value in range 0-96");
break;
}
}
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);
}
}
this code is supposed to recieve two integers and an operation and then calculate the numbers. this is only part of the entire program everything else works but the calculations are wrong. The only correct output that i get when i run the whole thing is the subtraction. Whats wrong with it?
public static double calculate(int operand1, int operand2, char operation)
{
if (operation=='^')
{
return (Math.pow(operand1,operand2));
}
else if(operation=='+')
{
return ((operand1)+(operand2));
}
else if(operation=='-')
{
return (operand1-operand2);
}
else if(operation=='*')
{
return (operand1*operand2);
}
else
{
if (operand2==0)
{
System.out.println("Cant divide by zero");
}
return(operand1/operand2);
}
}
Here is the entire code for the program
import java.util.Scanner;
public class Calculator
{
public static void main(String[] args)
{
printIntro();
Scanner kb = new Scanner(System.in);
String answer = "yes";
while (answer.equals("yes"))
{
System.out.println("Enter your problem");
String fullExpression=kb.nextLine();
fullExpression=fullExpression.replaceAll("\\s","");
int length=fullExpression.length();
char op1=fullExpression.charAt(0);
char op2=fullExpression.charAt(1);
String operation=fullExpression.substring(2,length);
printEnglish(op1,op2,operation);
System.out.println("Type yes to continue");
Scanner kb1 = new Scanner(System.in);
answer=kb1.nextLine();
};
}
/*this methods gets the operands and the operation and
prints the English version: if we call this method
printEnglish(2,3, plus), then this method will output:
Two plus three = 5 */
public static void printEnglish(char op1, char op2, String operation)
{
String resultOp1CharToString=charToString(op1);
String resultOp2CharToString=charToString(op2);
char resultOperationConversion=operationConversion(operation);
double resultCalculate=calculate(op1, op2, resultOperationConversion);
System.out.print(resultOp1CharToString+ operationConversion(operation) + resultOp2CharToString+ "=" + resultCalculate);
/*1. call the method charToString(op1) to convertlish
word for example ‘1’ to one or ‘2’ to two,….
2. call the method operandConversionToNumber(op1) to
get its numeric value. For example if op1 is ‘1’ then
this method call should return the integer value 1
3. call the method operationConversion(operation) to
convert the operation to a mathematical operation. For
example if you call this method with the string plus
then it will return ‘+’
4. finally call the method calculate to get the result
of the operation.*/
}
/*this method prints the numeric version which is 2 *3
=6*/
//public static boolean printNumeric(char op1, char op2, String operation)
//{
/*String resultCharToString=charToString(op1);
String resultCharToString2=charToString(op2);
int resultOperandToNumber=operandConversionToNumber(op1);
int resultOperandToNumber2=operandConversionToNumber(op2);
char resultOperationConversion=operationConversion(operation);
double resultCalculate=calculate(op1, op2, operation); */
//}
/*this method gets a number as a character and returns
its numeric value as an integer. You must use case
statement for this method*/
public static int operandConversiontoNumber(char operand)
{
int numberOperand=0;
switch(operand)
{
case '0':
numberOperand=0;
break;
case '1':
numberOperand=1;
break;
case '2':
numberOperand=2;
break;
case '3':
numberOperand=3;
break;
case '4':
numberOperand=4;
break;
case '5':
numberOperand=5;
break;
case '6':
numberOperand=6;
break;
case '7':
numberOperand=7;
break;
case '8':
numberOperand=8;
break;
case '9':
numberOperand=9;
break;
}
return numberOperand;
}
/*this method gets the operation as a string and
return the equivalent operation in math. For example
if it receives “plus” the it will return ‘+’ */
public static char operationConversion(String s)
{
char operation=0;
if(s.equals("plus"))
{
operation= '+';
}
else if(s.equals("minus"))
{
operation= '-';
}
else if(s.equals("multiply"))
{
operation= '*';
}
else if(s.equals("divide"))
{
operation= '/';
}
else
{
operation= '^';
}
return operation;
}
/*this method recives two numbers and the operation
and returns the result*/
public static double calculate(int operand1, int operand2, char operation)
{
if (operation=='^')
{
return (Math.pow(operand1,operand2));
}
else if(operation=='+')
{
return ((operand1)+(operand2));
}
else if(operation=='-')
{
return (operand1-operand2);
}
else if(operation=='*')
{
return (operand1*operand2);
}
else
{
if (operand2==0)
{
System.out.println("Cant divide by zero");
}
return(operand1/operand2);
}
}
/*this method converst a number character to its
English word for example if this method receives ‘1’
it will return “one” */
public static String charToString(char num)
{
String englishOperand="one";
switch(num)
{
case '0':
englishOperand= "zero";
break;
case '1':
englishOperand="one";
break;
case '2':
englishOperand="two";
break;
case '3':
englishOperand="three";
break;
case '4':
englishOperand= "four";
break;
case '5':
englishOperand= "five";
break;
case '6':
englishOperand= "six";
break;
case '7':
englishOperand= "seven";
break;
case '8':
englishOperand= "eight";
break;
case '9':
englishOperand= "nine";
break;
}
return englishOperand;
}
//this method prints the decription of this program.
public static void printIntro()
{
System.out.println("This program is a calculator, you need to enter two");
System.out.println("single digit numbers and an operation(plus, minus,");
System.out.println("divide, multiply, power) and it outputs its numeric");
System.out.println("and English version. Your operand and operation can be");
System.out.println("separated by space(s) or there could be no spaces");
System.out.println("between them. For example you can enter “23plus” or “2 3 plus”");
}
}
I entered 2 3 plus and i expect 5 but i dont recieve that, but when i enter 2 3 minus i recieve -1
if (operand2==0)
{
System.out.println("Cant divide by zero");
return -1; // some dummy value
}
else
{
return(operand1/operand2);
}
Division will be incorrect as it's doing integer division and you want a double result. It will also throw a divide by zero error because you don't return.
if (operand2 == 0)
{
System.out.println("Cant divide by zero");
return 0; // I guess
}
return (double)operand1 / (double)operand2;
All the rest look like they should work fine.
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.