In my convertEuro method the for loop is causing the output to be printed twice, but only sometimes. What I mean is this is what gets displayed:
Converting values to Euros.
£4.00 >>> €5.45
£123.44 >>> €168.13
Converting values to Euros.
£4.00 >>> €5.45
£123.44 >>> €168.13
During testing it seems to do this maybe 2 times out of 10, and I can't figure out why. Code below if someone can please help:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class Conversion {
public void mainMenu(Scanner scan, ArrayList<Double> values, DecimalFormat twoDecimal) {
int menuChoice;
System.out.println("1. Enter values and type -1 to stop");
System.out.println("2. Euros");
System.out.println("3. Dollars");
System.out.println("4. Yen");
System.out.println("5. Rupees");
System.out.println("6. Exit");
menuChoice = scan.nextInt();
switch (menuChoice) {
case 1:
enterValues(scan, values, twoDecimal);
case 2:
scan.nextLine();
convertEuro(scan, values, twoDecimal);
}
}
public void enterValues(Scanner scan, ArrayList<Double> values, DecimalFormat twoDecimal) {
double value = 0;
do {
System.out.print("Enter value. Enter -1 to stop: £");
while (!scan.hasNextDouble()) {
System.out.print("Please enter a double (£xx.xx): £");
scan.nextLine(); //Consumes \n
scan.next();
}
value = scan.nextDouble();
if (value != -1) {
values.add(value);
System.out.println("Value entered.");
}
}
while (value != -1);
System.out.println("Returning to main menu. ");
mainMenu(scan, values, twoDecimal);
}
public void convertEuro(Scanner scan, ArrayList<Double> values, DecimalFormat twoDecimal) {
System.out.println("Converting values to Euros.");
for (int i = 0; i < values.size(); i++) {
System.out.println("£" + twoDecimal.format(values.get(i)) + " >>> " + "\u20ac" + twoDecimal.format(values.get(i) * 1.362));
}
}
public static void main(String[] args) {
Conversion conv = new Conversion();
Scanner scan = new Scanner(System.in);
ArrayList<Double> values = new ArrayList<Double>();
DecimalFormat twoDecimal = new DecimalFormat("0.00");
conv.mainMenu(scan, values, twoDecimal);
scan.close();
}
}
You need to add a break; statement:
case 1:
enterValues(scan, values, twoDecimal);
break;
When the switch statement hits the correct case, it executes it and proceeds executing other cases which are below until and unless it hit an break statement.
The correct process is
switch (menuChoice) {
case 1:
enterValues(scan, values, twoDecimal);
break;
case 2:
scan.nextLine();
convertEuro(scan, values, twoDecimal);
break;
}
Thats why best practice is to put break statement after every case end.
Thank you
Related
I am creating a basic banking app that tracks a user's bank account activities, and I cannot seem to figure out why when I run my code that it is simply running what I have set for the "default" case; so even when I press 1,2,3, or 4, the console states, "Error -- Please choose a valid option."
Thanks in advance!
package Account;
import java.util.Scanner;
public class Account extends Bank {
int Balance;
int Previoustransaction;
int amount;
int amount2;
String Name;
String ID;
Account(String Name,String ID){
}
void deposit(int amount) {
if (amount != 0) {
Balance+=amount;
Previoustransaction=amount;
}
}
void withdraw(int amount) {
if(amount!=0) {
Balance-=amount;
Previoustransaction = -amount;
}
}
void getPrevioustransaction() {
if(Previoustransaction > 0) {
System.out.println("Deposited:" + Previoustransaction);
}
else if(Previoustransaction<0) {
System.out.println("Withdrawn:" + Math.abs(Previoustransaction));
} else {
System.out.println("No transaction occurred.");
}
}
void Menu() {
int choice = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome," + Name + ".");
System.out.println("Your account number is" + ID);
System.out.println("What would you like to do?");
System.out.println("1.Check balance.");
System.out.println("2. Make a deposit.");
System.out.println("3. Make a withrawl.");
System.out.println("4. Show last transaction.");
System.out.println("0. Exit.");
do {
System.out.println("Choose an option.");
choice = scan.nextInt();
System.out.println();
switch(choice) {
case'1':
System.out.println("Balance = $" + Balance);
System.out.println();
break;
case'2':
System.out.println("Enter an amount to deposit.");
int amount = scan.nextInt();
deposit (amount);
System.out.println();
break;
case'3':
System.out.println("Enter an amount to withdrawl.");
int amount2 = scan.nextInt();
withdraw(amount2);
break;
case '4':
getPrevioustransaction();
break;
case '0':
break;
default:
System.out.println("Error -- Please choose a valid option.");
}
} while (choice != 0);
System.out.println("Thank you for using the Bank Account Tracker!");
scan.close();
}
{
}
{
}
}
The reason your program isn't working as you expect is that:
you are prompting for user input
capturing that input as a numeric value; specifically, primitive data type int
comparing that int input against various character values – that is, values of primitive data type ch (such as '1')
Here's a paired down version of what you're doing:
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case '1':
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
Here's that same block, but instead of case '1' (which matches on a single character value), I changed it to case 1 (which matches on an integer value):
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1: // <-- this is the only edit, use 1 instead of '1'
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
So, to fix your program, change your various case statements to use integer values, not characters.
I am new at coding and now I am learning Java. I tryed to write something like calculator. I wrote it with switch case but then I realized I must take all inputs in single line. For example in this code I took 3 inputs but in 3 different lines. But I must take 2 input and 1 char in single line. First first number second char and then third number. Can you help me ?
Public static void main(String[] args) {
int opr1,opr2,answer;
char opr;
Scanner sc =new Scanner(System.in);
System.out.println("Enter first number");
opr1=sc.nextInt();
System.out.println("Enter operation for");
opr=sc.next().charAt(0);
System.out.println("Enter second number");
opr2=sc.nextInt();
switch (opr){
case '+':
answer=opr1+opr2;
System.out.println("The answer is: " +answer);
break;
case '-':
answer=opr1-opr2;
System.out.println("The answer is: " +answer);
break;
case '*':
answer=opr1*opr2;
System.out.println("The answer is: " +answer);
break;
case '/':
if(opr2>0) {
answer = opr1 / opr2;
System.out.println("The answer is: " + answer);
}
else {
System.out.println("You can't divide to zero");
}
break;
default:
System.out.println("Unknown command");
break;
}
Try following way
System.out.print("Enter a number then operator then another number : ");
String input = scanner.nextLine(); // get the entire line after the prompt
String[] sum = input.split(" ");
Here numbers and operator separated by "space". Now, you can call them by sum array.
int num1 = Integer.parseInt(sum[0]);
String operator = sum[1]; //They are already string value
int num2 = Integer.parseInt(sum[2]);
Then, you can do as you did than.
You can try something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter number, operation and number. For example: 2+2");
String value = scanner.next();
Character operation = null;
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
Character c = value.charAt(i);
// If operation is null, the digits belongs to the first number.
if (operation == null && Character.isDigit(c)) {
a.append(c);
}
// If operation is not null, the digits belongs to the second number.
else if (operation != null && Character.isDigit(c)) {
b.append(c);
}
// It's not a digit, therefore it's the operation itself.
else {
operation = c;
}
}
Integer aNumber = Integer.valueOf(a.toString());
Integer bNumber = Integer.valueOf(b.toString());
// Switch goes here...
}
Note: didn't validate input here.
I'm currently creating my first game which is executed in a console.
I've been asked to validate an input which can be done with a simple code. The goal is to input, and then validate if that number is an integer, and is on a range of 1-4. If possible, the problem should be solved with basic algorithm.
The problem is that it won't give me the result I wanted. It works when I enter a string, but it loops on every number I put including the number in the range. Does anyone know why?
public class Menu {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int input = 0;
int min = 1;
int max = 4;
boolean inputValidate;
System.out.println("Main Menu");
System.out.println("=========");
System.out.println("1. Play Game");
System.out.println("2. About");
System.out.println("3. View Saved Games");
System.out.println("4. Exit");
System.out.println("");
do {
System.out.print(">> ");
if (!scanner.hasNextInt()) {
inputValidate = false;
System.out.println("Not a number. Please input number 1-4.");
scanner.nextLine();
} else if (input <= max && !(input < min)) // if input <= 4 and input is not less than 1
{
input = scanner.nextInt();
inputValidate = true;
} else {
inputValidate = false;
System.out.println("Not in range. Please input number 1-4.");
scanner.nextLine();
}
} while (!(inputValidate));
switch (input) {
case 1:
break;
case 2:
System.out.println("Good work!");
break;
case 3:
break;
case 4:
break;
}
}
}
}
Because you instantiate input to be 0, but never give the user an opportunity to change this, the conditions for the first two conditionals are always false (nothing is read from the Scanner and 0 is not between min and max). Therefore, the program falls through to the else every time. Just add a statement before the do-while that will obtain a value for input from the user.
input = scanner.nextInt();
// your do-while loop
(You'll also probably have to adjust the code slightly to get the type of interaction you're looking for. Hint - you're reading two values from the user.)
As Clint said the problem was in your input. Here's a demo how you can fix this,
try (Scanner scanner = new Scanner(System.in)) {
int input = 0;
int min = 1;
int max = 4;
boolean inputValidate = false;
System.out.println("Main Menu");
System.out.println("=========");
System.out.println("1. Play Game");
System.out.println("2. About");
System.out.println("3. View Saved Games");
System.out.println("4. Exit");
System.out.println("");
do {
System.out.print(">> ");
try {
input = scanner.nextInt();
if (input >= min && input <= max) {
inputValidate = true;
} else {
System.out
.println("Not in range. Please input number 1-4.");
scanner.nextLine();
}
} catch (InputMismatchException exception) {
System.out
.println("Not a number. Please input number 1-4.");
scanner.nextLine();
}
} while (!(inputValidate));
I am working on an example using a do-while loop and switch statement. What I basically need is to accumulate numbers and depending on user input either add, substract, multiply or divide (mini calculator type).
The problem is when I ask the user to go back to the main menu the program does not reset the value as it is before the loop. The result is always the previous result.
Here is the code, it will explain it better.
import java.util.Scanner;
public class SwitchLoopNumbers{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int numbers=0;
int result=0;
int option;
boolean quit = true;
String done="";
do{
System.out.println("CALCULATOR MENU");
System.out.println("********** ****");
System.out.println("\n1. Add");
System.out.println("2. Substract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println();
System.out.print("Enter your option >> ");
option = scan.nextInt();
while(quit){
switch(option){
case 1:
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
if(numbers==0)
quit=false;
result +=numbers;
break;
case 2:
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
result -=numbers;
if(numbers==0)
quit=false;
break;
}
}
System.out.println("The total is: "+result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
//I did reset numbers and result here to zero but it did not work
}
while("y".equalsIgnoreCase(done));
System.out.println("Thank you for using calculator");
}
}
A couple things are going on here. To answer your question concisely, it's because you didn't reassign your variables before re-looping. Since you don't reassign result and quit, quit is false so it closes the loop, and result is unchanged so it then prints the same result. Try this:
System.out.println("The total is: "+result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
numbers = 0;
result = 0;
quit = true;
I think it's the most straight-forward solution to your problem.
EDIT: I also wanted to add that using quit as the while condition seems a little counter-intuitive. If I saw a condition quit that was true, my assumption would be that it would break the loop, not continue it. You might make your code a bit clearer by designating more meaningful variable names. So instead of saying something like:
boolean quit = true;
while(quit) {
//do stuff
if (some_condition) {
quit = false;
//close loop
}
}
This may be a little clearer:
boolean quit = false;
while(!quit) {
//do stuff
if (some_condition) {
quit = true;
//close loop
}
}
Just a general suggestion.
You can try to call main() again, but I'm not sure if it will work, solution can be make your own method eg. init() - where you will set vars into init state, and eg. work(), what will be remaining code :D
EDIT: you can make it this way
import java.util.Scanner;
public class main {
//if you want work with result after user will write "y" in the end
static int result = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numbers = 0;
int option;
boolean quit = false;
String done = "";
//int result = 0; // if you want also init result
// menu
System.out.println("CALCULATOR MENU");
System.out.println("********** ****\n");
System.out.println("1. Add");
System.out.println("2. Substract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
// user menu input read
System.out.println();
System.out.print("Enter your option >> ");
option = scan.nextInt();
switch (option) {
case 1:
while (!quit) {
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = true;
}
result += numbers; // result = result + numbers
}
break;
case 2:
while (!quit) {
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
result -= numbers; // result = result - numbers
if (numbers == 0) {
quit = true;
}
}
break;
default:
System.out.println("Bad inpout");
break;
}
System.out.println("The total is: " + result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
//recursive call - run main() again
if (done.equals("y")) {
main(args);
} else {
System.out.println("Thank you for using calculator");
}
}
}
I'm trying to write this java program for a user to input two rational numbers and ask from a menu of options to compute some sort of function A. I'm stuck in a few places and don't know what else to do. I need some guidance. it wont compile. says constructor Rational is undefined and the last default is an invalid label .it is two class files were the driver files uses the rational file. both files are uploaded and separated by text. need help
import java.util.Scanner;
import java.util.*;
public class RationalDriver{
public static void main(String[] args){
int rationalNum1, rationalDen1, rationalNum2, rationalDen2;
Scanner in = new Scanner(System.in);
// first rational
System.out.println(" Input first rational number for the Numerator");
rationalNum1 = in.nextInt();
System.out.println(" Input first rational number for the Denominator");
rationalDen1 = in.nextInt();
if (rationalDen1 == 0){
System.out.println(" Cannont divide by zero ");
System.out.println(" please re enter another number ");
}
System.out.println("Rational Number #1 = ("+rationalNum1+"/"+rationalDen1+")");
//Displays 1st Rational Number
// second rational
System.out.println(" Input 2nd rational number for the 2nd Numerator");
rationalNum2 = in.nextInt();
System.out.println(" Input 2nd rational number for the 2nd Denominator");
rationalDen2 = in.nextInt();
if (rationalDen2 == 0){
System.out.println("Cannont divide by zero");
System.out.println(" please re enter another number");
}
System.out.println("Rational Number #2 = ("+rationalNum2+"/"+rationalDen2+")");
//Displays 2nd Rational Number
Rational r1 = new Rational ( rationalNum1, rationalDen1);
Rational r2 = new Rational ( rationalNum2, rationalDen2);
// System.out.println;//toString
}
public void display_menu() //menu options
{
System.out.print(" Enter the corresponding number for the desired action ");
System.out.println("1) Addition\n2) 2) Subtraction\n3) 3) Multiplication\n4) 4)Division\n5) 5) Test for Eqaulity\n6) 6) Change 1st rational number\n7) 7) Change 2nd rational number");
}
public void question()
{
System.out.println("Do you want to exit? [y/n]"); // ask user if they want to quit with yes or no option
Scanner q = new Scanner(System.in);
switch (q.nextInt())
{
case 'y' :
System.out.println ("Thank you and goodbye.");
break;
case 'n' :
InputMenu();
break;
default:
System.err.println ( "Unrecognized option" );
break;
}
}
public void InputMenu() // keys for the menu
{
Scanner in = new Scanner(System.in);
display_menu();
switch (in.nextInt())
{
case 1: //addition
System.out.println ( "1" );
System.out.println( "("+rationalNum1+"/"+rationalDen1+")"+ " + " + " ("+rationalNum2+"/"+rationalDen2+")" + "=" + r1.add(r2));
break;
case 2: //subtraction
System.out.println ( "2" );
System.out.println( "("+rationalNum1+"/"+rationalDen1+")"+ " - " + "("+rationalNum2+"/"+rationalDen2+")" + "=" + r1.subtract(r2));
break;
case 3: //mulitplication
System.out.println ( "3" );
System.out.println( "("+rationalNum1+"/"+rationalDen1+")"+ " * " + " ("+rationalNum2+"/"+rationalDen2+")" + "=" + r1.multiply(r2));
break;
case 4: //division
System.out.println ( "4" );
System.out.println( "("+rationalNum1+"/"+rationalDen1+")"+ " / " + "("+rationalNum2+"/"+rationalDen2+")" + "=" + r1.divide(r2));
break;
case 5: //compare to
System.out.println ( "5" );
question();
break;
case 6: //change the 1st Rational Number
System.out.println ( "6" );
Scanner in = new Scanner(System.in);
System.out.println(" Input first rational number for the Numerator");
rationalNum1 = in.nextInt();
System.out.println(" Input first rational number for the Denominator");
rationalDen1 = in.nextInt();
if (rationalDen1 == 0){
System.out.println(" Cannont divide by zero");
System.out.println(" please re enter another number");
}
break;
case 7: //change the 2nd Rational Number
System.out.println ( "7" );
System.out.println(" Input 2nd rational number for the 2nd Numerator");
rationalNum2 = in.nextInt();
System.out.println(" Input 2nd rational number for the 2nd Denominator");
rationalDen2 = in.nextInt();
if (rationalDen2 == 0){
System.out.println("Cannont divide by zero");
System.out.println(" please re enter another number");
break;
default:
System.err.println ( "Unrecognized option" );
break;
}
}
}
}
Here is the class file for rational
public class Rational{
private int Numerator;
private int Denominator;
//constructors
public Rational(){
Numerator = 1;
Denominator = 1 ;
}
//setters
//a-numerator
//b-denmonator
//c other.getNumerator
//d-other.getDenominator
public void add (Rational other){ // (ad + bc) / bd
Numerator = (Numerator*other.getDenominator() + Denominator*other.getNumerator());
Denominator = (Denominator*other.getDenominator());
//Normalize();
}
public void subtract (Rational other){ // (ad-bc) / bd
Numerator = (Numerator*other.getDenominator() - Denominator*other.getNumerator());
Denominator = (Denominator*other.getDenominator());
//Normalize();
}
public void multiply (Rational other){ // ac/db
Numerator = (Numerator*other.getNumerator() / other.getDenominator()* Denominator);
// Normalize();
}
public void divide (Rational other){//
}
public int getNumerator(){
return Numerator;
}
public int getDenominator(){
return Denominator;
}
//toString
//public String toString(){
//return toString()+ (rationalNum1 + "/" + rationalDen1);
}
In your main class you have:
Rational r1 = new Rational ( rationalNum1, rationalDen1);
Rational r2 = new Rational ( rationalNum2, rationalDen2);
you are passing 2 integers to a constructer that recives void, so you have to change your constructer (of Rational class) like this:
public Rational(int rationalNumber, int rationalDen){
Numerator = rationalNumber;
Denominator = rationalDen;
}
Hope it helps, let me know if it worked or if there is more something wrong...
Edit: your Scanner and print error.
You have this:
public void question()
{
System.out.println("Do you want to exit? [y/n]"); // ask user if they want to quit with yes or no option
Scanner q = new Scanner(System.in);
switch (q.nextInt()) // here you are assuming that you are reading a int in step
{ // of a string
case 'y' : // ' ' arent used for strings...
System.out.println ("Thank you and goodbye.");
break;
case 'n' :
InputMenu();
break;
default:
System.err.println ( "Unrecognized option" );
break;
}
}
so, what you need is:
public void question()
{
System.out.println("Do you want to exit? [y/n]"); // ask user if they want to quit with yes or no option
Scanner q = new Scanner(System.in);
switch (q.nextLine()) // change nextInt to nextLine, that is the string method
{ // of a string
case "y" : //change ' ' to " "
System.out.println ("Thank you and goodbye.");
break;
case "n" : //change ' ' to " "
InputMenu();
break;
default:
System.err.println ( "Unrecognized option" );
break;
}
}
Hope it help :)
Edit 3:
in your code you have: `
public class RationalDriver{
public static void main(String[] args){
int rationalNum1, rationalDen1, rationalNum2, rationalDen2; // this are local variables, they only exist inside main method
...`
}
So, what you can do is:
public class RationalDriver{
private static int rationalNum1, rationalDen1, rationalNum2, rationalDen2;
public static void main(String[] args){
// your main
}
what i did was take your local variables that only exists in your main and turn them in global variables so when you want change their value or give them a value you just do:
rationalNum1 = your valor;
Please note that if you use any variable without initialize it with a value you will get a null point exception...
you need to create a constructor Rational (int rationalNum1, int rationalDen1){}
In your program you used the constructor Rational ( rationalNum1, rationalDen1)
when you have only declared the default constructor public Rational(), which does no accept any arguments.
It is possible to have multiple constructor for a class and they are differentiated by the type and number of argument they accept.
E.g
class A(int a, int b);
is same as
Class A(int c, int b);
but not
Class(int a, float d)