while loop keeps ending without initiating the if-statement - java

I'm trying to create a simple calculator program on Java as a simple first project as I learn Java.
Problem: After I run the program and after doing my calculation, I wanted to give the user the option on whether they want to end the program or do some more calculations. for some reason the program is not using the (if) statements that I have placed in it, it seems to skip it and end my program without allowing the user to input his choice at the end.
I'm really sorry if my question is not clear, I couldn't find a solution for my problem online, and I do apologize if my code looks really messy.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double fnum, snum, answer;
String choice, name, in;
System.out.println("Hello, whats your name?");
name = input.nextLine();
System.out.println("");
System.out.println("Oh so your name is " + name + "!");
System.out.println("");
System.out.println("This program is a calculator that will do simple calculation of two numbers");
System.out.println("There are four different options to choose from:");
boolean running = true;
CAL:
while (running) {
System.out.println("type a for Addition, b for subtraction, c for multiplication and d for division");
System.out.println("Then press enter!");
choice = input.nextLine();
while (!choice.equals("a") &&
!choice.equals("A") &&
!choice.equals("b") &&
!choice.equals("B") &&
!choice.equals("c") &&
!choice.equals("C") &&
!choice.equals("d") &&
!choice.equals("D")) {
System.out.println("Wrong choice, Please try again");
System.out.println("type a for Addition, b for subtraction, c for multiplication and d for division");
choice = input.nextLine();
}
if (choice.equals("a") || choice.equals("A")) {
System.out.println(name +" You have chosen Addition");
System.out.println("Type the first number:");
fnum = input.nextDouble();
System.out.println("Type the second number:");
snum = input.nextDouble();
System.out.println("your answer is:");
Addition addy = new Addition(fnum,snum);
System.out.println(addy.getans());
}
if (choice.equals("b") || choice.equals("B")) {
System.out.println(name +" You have chosen Subtraction");
System.out.println("Type the first number:");
fnum = input.nextDouble();
System.out.println("Type the second number:");
snum = input.nextDouble();
answer = fnum - snum;
System.out.println("your answer is:"
+ answer);
}
if (choice.equals("c") || choice.equals("C")) {
System.out.println(name +" You have chosen Multiplication");
System.out.println("Type the first number:");
fnum = input.nextDouble();
System.out.println("Type the second number:");
snum = input.nextDouble();
answer = fnum * snum;
System.out.println("your answer is:"
+ answer);
}
if (choice.equals("d") || choice.equals("D")) {
System.out.println(name +" You have chosen Addition");
System.out.println("Type the first number:");
fnum = input.nextDouble();
while (fnum == 0) {
System.out.println("invalid try again!");
fnum = input.nextDouble();
}
System.out.println("Type the second number:");
snum = input.nextDouble();
answer = fnum / snum;
System.out.println("your answer is:"
+ answer);
}
System.out.println("");
System.out.println("Thank you " + name + " for using this simple calculator :)");
System.out.println("If you would like to try again press a the press Enter, if you wish to exit press any botton and then press enter");
in = input.nextLine();
if (in.equals("a")) {
System.out.println("");
System.out.println("Thank you, please choose again");
System.out.println("");
} else {
System.out.println("Thank you and goodbye");
break;
}
}
}
}

It's a simple problem caused by nextInt/Double/etc behaviour.
Those methods don't read the following new-line character so the next nextLine will always return an empty string (the rest of the current line).
Try to change those (e.g. the addition case) with Double.parseDouble(input.nextLine());
if (choice.equals("a") || choice.equals("A")) {
System.out.println(name + " You have chosen Addition");
System.out.println("Type the first number:");
fnum = Double.parseDouble(input.nextLine());
System.out.println("Type the second number:");
snum = Double.parseDouble(input.nextLine());
System.out.println("your answer is:");
Addition addy = new Addition(fnum, snum);
System.out.println(addy.getans());
}
you can notice debugging that the last in = input.nextLine(); called to ask for user input will always be empty string.

Related

Illegal start of expression on my function public static void

My code is about looping and method, A program that will let user either compute an area or use the 4 basic math operations. the (Triangle, Square,Rectangle) with their choice of process: Addition, Subtraction, Multiplication and Division.
I think i properly closed the addition function there and i already check the closing every functions they seem work well other than the addtion function since thats the only error i got.
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//WHILE LOOP FOR CHOICES
while(true){//CHOICES LOOP
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("1 - Addition process");
System.out.println("2 - Subtraction process");
System.out.println("3 - Multiplication process");
System.out.println("4 - Division process");
System.out.println("5 - Compute process");
System.out.println("Your choice: ");
int option = scan.nextInt();
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if(option == 1){
Add();
}
else if(option == 2){
Sub();
}
else if(option == 3){
Mul();
}
else if(option == 4){
Div();
}
else if(option == 5){
Com();
}
else if((option>=6)&&(option<=100)){//INVALID
System.out.println("Invalid Input, Please Input Choice Again.");
}
else{//- if user input other number, the program will break and stop from looping
break;
}
Here Im getting a error here im not sure what is it
public static void Add(){
System.out.println("ADDITION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int add1=scan.nextInt();
System.out.println("2nd number: ");
int add2=scan.nextInt();
int addtotal=add1+add2;
if(addtotal>100){// In addition, if the sum is higher than 100, print the answer the word high. if equal and below 100, print low
System.out.println("Total is "+addtotal+" High");
}
else if(addtotal<100){
System.out.println("Total is "+addtotal+" Low");
}
}
public static void Sub(){//SUBTRACTION
System.out.println("SUBTRACTION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int sub1=scan.nextInt();
System.out.println("2nd number: ");
int sub2=scan.nextInt();
int subtotal=sub1-sub2;
if(subtotal<0){// In subtraction, if the difference is negative, print invalid. If 0 or above, print the difference and the word valid.
System.out.println("Invalid ");
}
else if(subtotal>0){
System.out.println("Total is "+subtotal+" Valid");
}
}
public static void Mul(){//MULTIPLICATION
System.out.println("MULTIPLICATION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
double multi1=scan.nextDouble();//In multiplication, make it accepts decimal value
System.out.println("2nd number: ");
double multi2=scan.nextDouble();
double multitotal=multi1*multi2;
System.out.println("Total is "+multitotal);
}
public static void Div(){
System.out.println("DIVISION");
System.out.println("Enter two numbers: ");
System.out.println("1st number: ");
int div1=scan.nextInt();
System.out.println("2nd number: ");
int div2=scan.nextInt();
int divtotal= div1 / div2;
int divremainder= div1 % div2;//In division, if it has remainder, print the answer and the remainder.
System.out.println("Total is "+divtotal);
System.out.println("Remainder is "+divremainder);
}
public static void Com(){// If user choose 5, the user needs to choose again on a ,b or c. If other letter, print invalid and then go pack on choosing of process.
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
System.out.println("Input Choice of Process");
System.out.println("a - Rectangle");
System.out.println("b - Square");
System.out.println("c - Triangle");
System.out.println("Your choice: ");
Scanner Keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
char choice = Keyboard.nextLine().charAt(0);
System.out.println("∘₊✧─────────────────────────────────────✧₊∘");
if (choice == 'A' || choice == 'a')//rectangle
{
System.out.println("Enter length of rectangle's base: ");
double base = input.nextDouble();
System.out.println("Enter length of rectangle's height: ");
double height = input.nextDouble();
double rArea = base * height;
System.out.println("The area of a rectangle with a base length of " + base + " and a height of " + height + " is " + rArea + ".");
}
else if (choice == 'B' || choice == 'b') //square
{
System.out.println("Enter length of square's sides: ");
double sSide = input.nextDouble();
double sArea = sSide * sSide;
System.out.println("The area of a square with a side length of " + sSide + " is " + sArea + ".");
}
else if (choice == 'C' || choice == 'c') //traingle
{
System.out.println("Enter traingle's side length: ");
double tSide = input.nextDouble();
double tArea = tSide * tSide * tSide;
System.out.println("The area of a triangle with a side length of " + tSide + " is " + tArea + ".");
}
else //invalid
{
System.out.println("You've entered an invalid character.");
}
}
}
You haven't got a closing brace for your main method

how to write while loop

I am currently making a simple ATM program in java.
I want to write a while loop where when user enters wrong pin it will prompt the user to enter again until the pin is matched. When the pin is matched, it will display the main menu.
I tried by myself, but I don't know how to fix it.
while(userPIN != savedPIN)
{
System.out.print("Please enter your correct PIN : ");
Scanner again = new Scanner(System.in);
int pass = again.nextInt();
break;
}
Remove the `break;' statement and update userPIN with the new pin as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int savedPIN = 4444;
Scanner input = new Scanner(System.in);
System.out.println("Enter password");
int userPIN = input.nextInt();
double withdraw = 0.0, amount = 0.0, deposit = 0.0;
while (userPIN != savedPIN) {
System.out.print("Please enter your correct PIN : ");
Scanner again = new Scanner(System.in);
userPIN = again.nextInt();
}
while (userPIN == savedPIN) {
System.out.println(" 1 - Inquire Balance \n 2 - Withdraw \n 3 - Deposit \n 0 - Quit ");
Scanner inputNum = new Scanner(System.in);
int number = inputNum.nextInt();
switch (number) {
case 1:
System.out.println("The current balance is $" + amount);
break;
case 2:
System.out.println("Enter the amount to withdraw : ");
withdraw = input.nextDouble();
if (amount >= withdraw) {
amount = amount - withdraw;
System.out.println("The current balance is $" + amount);
} else {
System.out.println("Insufficient balance");
}
break;
case 3:
System.out.println("Enter the amount to deposit : ");
deposit = input.nextDouble();
amount = amount + deposit;
System.out.println("The current balance is $" + amount);
break;
case 0:
System.exit(4);
}
}
}
}
Ok 2 errors:
1)you test userPIN != savedPIN but you accept the value into variable pass with which you do nothing.
2)remove the break in the first loop it will always exit without looping.
it should look like :
while(pass!= savedPIN)
{
System.out.print("Please enter your correct PIN : ");
Scanner again = new Scanner(System.in);
int pass = again.nextInt();
}

How would I let the user select an Item from this list and have it complete the function rather than parsing through all of them one by one?

I have implemented a calculator, however, I only want the user to be able to pick two options then close the program. My code is having the user cycle through each operation. I would like the user to pick a number 1 through 6 and have it complete the operation the selected. Also if someone knows how to get the program to exit if they press 0 at the menu that would be fantastic.
import java.util.*;
public class Calculator
{
private int option = -1; // option is initially not 0
to 6
private Scanner scan; // we’ll use scan to read input
// constructor for class
public Calculator()
{
System.out.println ("java Homework1");
System.out.println ("Welcome to Math Calculator!");
System.out.println ("Please choose an option:");
System.out.println (" ");
System.out.println ("1 - add two real numbers");
System.out.println ("2 - subtract two real numbers");
System.out.println ("3 - multiply two real numbers");
System.out.println ("4 - divide two real numbers");
System.out.println ("5 - get the factorial of an
number");
System.out.println ("6 - menu");
System.out.println ("0 - exit");
scan = new Scanner(System.in); // creates scan
}
// entry point for class
public void run()
{
// stick code for calculator in here...may want to
create
// other functions to make code more readable
int selection1;
Scanner first = new Scanner(System.in);
selection1 = first.nextInt();
if (selection1 == 1);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
+ secondnum));
}
if (selection1 == 2);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
- secondnum));
}
if (selection1 == 3);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
* secondnum));
}
if (selection1 == 4);
{
System.out.println ("Enter 1st value: ");
int firstnum = scan.nextInt();
System.out.println ("Enter 2nd value: ");
int secondnum = scan.nextInt();
System.out.println ("your answer is: " + (firstnum
/ secondnum));
}
if (selection1 == 5);
System.out.println ("Enter the number you would
like the factorial of: ");
int factorialnum = scan.nextInt();
int i,start = 1;
for (i = 1; i <= factorialnum;i++)
{
start = start*i;
}
System.out.println ("your answer is: " + start);
}
}
The problem is with the if conditions. The following if condition is not correct. It will have no effect on the section following it, since it is ended with the semicolon (;)
if (selection1 == 1); //This condition will have no effect on the section following it
This is the correct way to write the if condition.
if (selection1 == 1){
//your logic here
}
Also, note the last if condition for factorial. It does not have braces for the code following it.

How to call a statement over and over again in Java

import java.util.*;
public class TestProject
{
public static void theMath()
{
double add = 1;
double subtract = 2;
double multiply = 3;
double divide = 4;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Pick first number
System.out.println("Please enter a number: ");
int intOne = input.nextInt();
// Pick second number
System.out.println("Please enter another number: ");
int intTwo = input.nextInt();
//User chooses operator
System.out.println("Now please choose an operator (1 for add, 2 for subtract, 3 for mulitply, 4 for divide): ");
int userChoice = input.nextInt();
// Add
if (userChoice == add)
System.out.println("Your answer is: " + (intOne + intTwo));
// Subtract
else if (userChoice == subtract)
System.out.println("Your answer is: " + (intOne - intTwo));
// Multiply
else if (userChoice == multiply)
System.out.println("Your answer is: " + (intOne * intTwo));
// Divide
else if (userChoice == divide)
System.out.println("Your answer is: " + (intOne / intTwo));
// If wrong input
else
{
System.out.println("Nothing happens!");
System.out.println("Please make sure you entered a number and an operator.");
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
theMath();
System.out.println("Would you like to do another calculation?");
String redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}
}
I was wondering how I could recall the main method an infinite amount of times if I wanted to. What I was doing was just copying and pasting it over and over again but there has to be a better way. And also, I would like to know how to return a value has a decimal(so I could do 25/6 and get the correct answer).
Why not put only the statements that should be repeated inside a loop?
String redo;
do{
System.out.println("Would you like to do another calculation?");
redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}while(redo.equals("yes"))
As for the other part of your question. If you have two int values and want to get a decimal from a division, you can do it like this:
int x = 2;
int y = 3;
double result = (double)x/y;
System.out.println(result);
This is called casting.

Can someone figure out whats wrong with my code?

I've run a debugger and everything, but I can't find out whats wrong! I run the code, and it accepts a as an asnwer, but if i put b, it runs the code saying "This is not an A or a B"
import java.util.Scanner;
public class messingAround {
public static void main(String[] args){
Scanner ques = new Scanner(System.in);
String question;
System.out.println("Would you like to:");
System.out.println("A: Solve a math problem");
System.out.println("B: Display Pi");
System.out.println("Type A or B (no caps)");
question = ques.next();
if(!(question.equals("a")) || question.equals("b")){
System.out.println("Sorry that isn't an A or a B");
System.out.println("Try running the code again");
}else if(question.equals("a")) {
double fnum, snum, answer;
String type;
Scanner intString = new Scanner(System.in);
System.out.println("Enter your first number: ");
fnum = intString.nextDouble();
System.out.println("Enter your second number: ");
snum = intString.nextDouble();
System.out.println("What would you like to do? (+ - * /)");
type = intString.next();
if(type.equals("*")){
answer = fnum * snum;
System.out.println("The product is: " + answer);
}else if(type.equals("+")) {
answer = fnum + snum;
System.out.println("The sum is: " + answer);
}else if(type.equals("-")) {
answer = fnum - snum;
System.out.println("The difference is: " + answer);
}else if(type.equals("/")) {
answer = fnum / snum;
System.out.println("The dividend is: " + answer);
}
}else if(question.equals("b")) {
System.out.println("3.14159265359");
}
}
}
if(!(question.equals("a")) || question.equals("b")){
parens are a bit off. Try this:
if(!(question.equals("a") || question.equals("b"))){

Categories