How do I make my calculator restart after giving the answers - java

So I've tried to make a Java calculator on console, and it's works decent, but when I get the result, I want it to restart like a loop, but I can't figure it out.
import java.util.Scanner;
public class calculator {
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
try {
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if (c.equals("*")) {
System.out.println("the total is " + x * y);
} else if (c.equals("+")) {
System.out.println("the total is " + (x + y));
} else if (c.equals("-")) {
System.out.println("the total is " + (x - y));
} else if (c.equals("/")) {
System.out.println("the total is " + (x / y));
} else {
System.out.println("you are an idiot");
}
} catch (Exception e) {
System.out.println("Please enter correct value.");
}
}
}

Use while + break. Below is the working version:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
while (true) {
try {
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if (c.equals("*")) {
System.out.println("the total is " + x * y);
} else if (c.equals("+")) {
System.out.println("the total is " + (x + y));
} else if (c.equals("-")) {
System.out.println("the total is " + (x - y));
} else if (c.equals("/")) {
System.out.println("the total is " + (x / y));
} else {
System.out.println("you are an idiot");
}
} catch (Exception e) {
System.err.println("Please enter correct value.");
}
System.out.println("Do you wish to continue(y/n)?");
if (test.next().equals("n")) {
break;
}
}
}
}

You can use a while loop:
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
while(true) {
....
}
When you want to stop the calculator, you need enter ctrl - c.
Another way, use a boolean flag and let user dicide whether to continue:
public static void main(String[] args0) {
boolean flag = true;
Scanner test = new Scanner(System.in);
while(flag) {
....
System.out.println("enter y for continue, n for exit");
c = test.next();
if (c.equals("n")) {
flag = false;
}
}
}

Insert while loop before try and put everything below in it.put while(true) and this will repeat infinitely. If you want to press some key to stop make if condition and put break in it.
Scanner sc=new Scanner(System.in);
while(true){
...
if(sc.next()=='q') break; //this is if you want to quit after pressing q
...
}

Related

How do I exit a for or a while loop with user input in java

import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("-------Welcome to the Radius calculator-------");
String input = new String (" ");
while(input.equals("END")==false) {
for (int i = 1; i < 5; i++)
for (int e = 5; e > 0; e--)
{
{
System.out.println("-----------------------------");
System.out.println("Hey you can use this calcultor " + e + " more time(s) till yoh have to purchase our full version only 3.99");
}
System.out.println("Please enter your Radius if not just type in END at any stage during the program");
Double num =sc.nextDouble();
System.out.println("Enter 1 if you would like to get the area");
System.out.println("Enter 2 if you would like to get the circumfrence");
int num1 = sc.nextInt();
if (num1 == 1) {
System.out.println("The area of the circle with the radius " + num + " is :" + (Math.PI) * (num * num));
} else if (num1 == 2) {
System.out.println("The circumfrence of the circle with the radius " + num + " is :" + (2) * (Math.PI) * (num));
} else {
System.out.println("No answer for you boss");
System.out.println("Try again!");
}
System.out.println("You have used this calculator effiently " + i + " time(s)");
System.out.println("-----------------------------");
}
}
}
}
Heres my code it works but when i type in END an ERROR comes up.(https://i.stack.imgur.com/ZZxEW.png)](https://i.stack.imgur.com/ZZxEW.png)
If theres any othere tips to make my code for effecient would be much appriciated too.
You forgot to ask for the end input during the loops.
The best way to ask for an input of different types is to use BufferedReader Class
BufferedReader reader =new BufferedReader(newInputStreamReader(System.in));
String input = null;
try {
input = reader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
if (input.equals("END")) {
break;
}
After that you can use :
Integer.parseInt(input);
to cast from String to Integer
And don't forget to clean and simplify your code.

Is it possible to create a text file and then on the same run or runtime of the code also read and write in these files? Java

I was working on a Uni project for the end of the semester. The program is a simple bank system. My issue is that when the program first launches it creates a "Log" folder. Then when an account object is created using a Constructor a new txt file is created in the folder with the name of the account holder. Up until here I have managed to do it.
The issue is that when closing the program via the option menu but before closing the program, all the details from all the created objects (which are stored in a array) are written in their respective files following the order they are stored in the object array but on the first run the files are created but nothing is written in them.
Then on the 2nd run if I close the program again the details are written correctly. Can I have some suggestions please I could not find anything regarding this online?
import java.util.Scanner;
import java.io.*;
public class FileManagement {
static String pathnameFile = "src\\Log";
static File directory = new File(pathnameFile);
static String[] allFiles = directory.list();
public static void createFolder() {
File logFile = new File(pathnameFile);
if (!logFile.exists()) {
logFile.mkdir();
}
}
public static void writeFiles() throws IOException {
FileWriter writer;
for (int i = 0; i < allFiles.length; i++) {
writer = new FileWriter(pathnameFile + "\\" + allFiles[i]);
writer.write("accountName= " + eBanking.accounts[i].getAccountName() + "\n");
writer.write("PIN= " + eBanking.accounts[i].getPIN() + "\n");
writer.write("balance= " + Integer.toString(eBanking.accounts[i].getBalance()) + "\n");
writer.write("Object ID stored in RAM= " + eBanking.accounts[i].toString() + "\n");
writer.close();
}
}
//original method
/*public static void readFiles() {
Scanner reader;
for (int i = 0; i < allFiles.length; i++) {
reader = new Scanner(pathnameFile + allFiles[i]);
}
}*/
//My solution
public static void readFiles() throws IOException{
if(directory.exists() == false || allFiles == null) {
return;
}
Scanner reader;
File currentFile;
String[] data = new String[4];
for(int i = 0; i < allFiles.length; i++) {
currentFile = new File(pathnameFile + "\\" +allFiles[i]);
reader = new Scanner(currentFile);
int count = 0;
while(reader.hasNextLine()) {
if(!reader.hasNext()) {
break;
}
reader.next();
data[count] = reader.next();
count++;
}
reader.close();
String accountName = data[0];
String PIN = data[1];
int balance = Integer.parseInt(data[2]);
eBanking.accounts[i] = new eBanking(accountName, PIN, balance);
}
}
}
import java.util.Scanner;
import java.io.*;
public class App {
public static eBanking currentAccount;
public static void mainMenu() throws Exception{
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("""
--------------------------------------------------------
1. Log in
2. Register
0. Exit.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
System.out.println("Please enter your account name and PIN below.");
System.out.print("Account name: ");
String accountName = input.next();
System.out.print("PIN: ");
String PIN = input.next();
System.out.println();
for (int i = 0; i < eBanking.accounts.length; i++) {
if (accountName.equals(eBanking.accounts[i].getAccountName()) && PIN.equals(eBanking.accounts[i].getPIN())) {
eBanking.accounts[i].welcome();
currentAccount = eBanking.accounts[i];
break;
}
}
menu();
}
case 2 -> {
System.out.println("Please enter the account name, PIN and inital balance of your new account.");
System.out.print("Account name:");
String accountNameRegister = input.next();
System.out.print("PIN: ");
String registerPIN = input.next();
System.out.print("Initial balance: ");
int initialBalance = input.nextInt();
currentAccount = new eBanking(accountNameRegister, registerPIN, initialBalance);
menu();
}
default -> {
FileManagement.writeFiles();
System.exit(0);
}
}
}
}
public static void menu() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("""
--------------------------------------------------------
1. Show your balance.
2. Withdraw money.
3. Deposit money.
4. Change your PIN.
5. Transfer money to another person.
0. Back.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
currentAccount.showBalance();
}
case 2 -> {
System.out.println("Please enter the amount you want to withdraw: ");
int withdrawAmount = input.nextInt();
currentAccount.withdraw(withdrawAmount);
}
case 3 -> {
System.out.println("Please enter the amount you want to deposit: ");
int depositAmount = input.nextInt();
currentAccount.deposit(depositAmount);
}
case 4 -> {
currentAccount.changePIN();
}
case 5 -> {
System.out.println("Please enter the amount you want to send: ");
int amount = input.nextInt();
System.out.println("Please enter the account number you want to send the money to: ");
String transferAccount = input.next();// Me nextLine(); duhet ta shkruaj 2 here qe ta marri, duke perdor next(); problemi evitohet (E kam hasur edhe tek c++ kete problem)
System.out.println("The amount of money is completed");
currentAccount.transfer(amount, transferAccount);
}
case 0 -> {
return;
}
default -> {
System.out.println("Please enter a number from the menu list!");
}
}
}
}
public static void main(String[] args) throws Exception {
FileManagement.createFolder();
FileManagement.readFiles();
mainMenu();
}
}
import java.util.Scanner;
import java.io.*;
public class eBanking extends BankAccount {
// Variable declaration
Scanner input = new Scanner(System.in);
private String accountName;
private String accountID;
public static eBanking[] accounts = new eBanking[100];
// Methods
public String getAccountName() {
return accountName;
}
public void welcome() {
System.out.println("---------------------------------------------------------------------------------------");
System.out.println("Hello " + accountName + ". Welcome to eBanking! Your account number is: " + this.accountID);
}
public void transfer(int x, String str) {
boolean foundID = false;
withdraw(x);
if (initialBalance == 0) {
System.out.println("Transaction failed!");
} else if (initialBalance < x) {
for(int i = 0; i < numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += initialBalance;
System.out.println("Transaction completed!");
foundID = true;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += initialBalance;
return;
}
} else {
for(int i = 0; i <= numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += x;
System.out.println("Transaction completed!");
foundID=true;
return;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += x;
return;
}
}
}
// Constructors
public eBanking(String name){
int firstDigit = (int)(Math.random() * 10);
int secondDigit = (int)(Math.random() * 10);
int thirdDigit = (int)(Math.random() * 10);
int forthDigit = (int)(Math.random() * 10);
accountID = this.toString();
PIN = Integer.toString(firstDigit) + secondDigit + thirdDigit + forthDigit; //Nuk e kuptova perse nese i jap Integer.toString te pares i merr te gjitha
balance = 0; //dhe nuk duhet ta perseris per the gjitha
accountName = name;
accounts[numberOfAccount] = this;
numberOfAccount++;
System.out.println("---------------------------------------------------------------------------------------");
System.out.println(accountName + ": Your balance is " + balance + ", your PIN is: " + PIN + " and your account number is: " + accountID);
}
public eBanking(String name, String pin, int x){
if (checkPIN(pin) == false) {
System.out.println("Incorrect PIN format!");
return;
}
accountID = this.toString();
accountName = name;
balance = x;
PIN = pin;
accounts[numberOfAccount] = this;
numberOfAccount++;
welcome();
}
}
import java.util.Scanner;
public abstract class BankAccount {
// Variable declaration
protected String PIN;
protected int balance;
public static int numberOfAccount = 0;
protected static int initialBalance; // E kam perdorur per te bere menune me dinamike sidomos per metoden transfer();
//Methods
//Balance
public int getBalance() {
return balance;
}
public void showBalance() {
System.out.println("The total balance of the account is " + balance);
}
public void withdraw(int x) {
initialBalance = balance;
if (balance == 0) {
System.out.println("The deduction has failed due to lack of balance!");
return;
}
if (balance < x) {
balance = 0;
System.out.println("The deduction of " + initialBalance + " from your balance is completed!");
} else {
balance -= x;
System.out.println("The deduction of " + x + " from your balance is completed!");
}
}
public void deposit(int x) {
balance += x;
System.out.println("You have made a deposit of " + x + " and your current balance is " + balance);
}
//PIN
public String getPIN() {
return PIN;
}
public void changePIN() {
Scanner input = new Scanner(System.in);
System.out.print("Please enter your previous PIN: ");
String tryPIN = input.nextLine();
if (tryPIN.equals(PIN)) {
System.out.print("Please enter your new PIN: ");
String newPIN = input.nextLine();
if (checkPIN(newPIN) == false) {
System.out.println("The PIN is not in the correct format!");
} else {
System.out.println("The PIN has been changed");
PIN = newPIN;
}
} else {
System.out.println("The PIN does not match!");
}
}
protected static boolean checkPIN(String str) {
boolean isValid;
if(str.length() != 4) {
isValid = false;
} else {
try {
int x = Integer.parseInt(str);
isValid = true;
} catch (NumberFormatException e) {
isValid = false;
}
}
return isValid;
}
//Kjo metode duhet per testim
public void getDetails() {
System.out.println(balance + " and PIN " + PIN);
}
}
I have updated the post showing how I fixed it and providing all my classes. Please do not mind the messy code as I am first trying it out with a switch and then will ditch that when the time comes and use GUI as soon as I learn how to use it. Also I know that the classes can be organized better but BankAccount and eBanking are 2 salvaged classes I used on a different exercise.
I think I have found a solution. I just remembered that when using FileWriter if a file does not exist it creates one automatically. So i have cancelled the method which creates a file whenever a new object is created and now whenever the program is closed the files are created if needed or overwritten if they already exist.
I have provided all the current code on my program and the fix I implemented on FileManagment class

Are my loops preventing me from getting the expected output?

My goal is to determine, for a pair of integers, whether the second integer is a multiple of the first. My code is as follows:
import java.util.Scanner;
public class Multiples {
public static void main(String [] args) {
boolean run = true;
while(run) {
Scanner input = new Scanner(System.in);
System.out.print("Enter one number:");
int num1 = input.nextInt();
System.out.print("Enter a second number:");
int num2 = input.nextInt();
boolean result = isMultiple(num1, num2);
if(result) {
System.out.println(num2 + " is a multiple of " + num1);
} else {
System.out.println(num2 + " is not a multiple of " + num1);
}
System.out.print("Do you want to enter another pair(y/n)?");
run = YesOrNo(input.next());
}
}
public static boolean YesOrNo(String a) {
if(a.equals("y"))
return true;
else
return false;
}
public static boolean isMultiple (int x , int y) {
if(y % x == 0)
return true;
else
return false;
}
}
This is my output:
This is the expected output:
The expected output is confusing me.

Java multiplication using Recursion

I am writing a simple code in Java that is using recursion. I want to show the product of two numbers that a user will enter. I managed to do that using recursion, but stuck at the point where I want to show that the product could be written as (example) 10*5 = 5+5+5+5+5+5+5+5+5+5 (10 times), or 12*3 = 3+3+3+3+3+3+3+3+3+3+3+3 (12 times). Here is my code so far. In the code i put a comment where it should be written (example). Thanks.
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a, b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.println("The product of " + a + " and "
+ b + " is: " + multiRec(a, b));
System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
return x + (multiRec(x, y - 1));
}
}
}
}
A StringBuilder should be defiend as
StringBuilder buf = new StringBuilder (a);
Pass this StringBuilder paramater into multiRec
and then change multiRec to be
public static int multiRec(int x, int y, StringBuilder buf) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
buf.append (" + ").append (x);
return x + (multiRec(x, y - 1, buf));
}
}
}
}
Then when completed simply printout its value
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a , b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.printf("%d %s %d %s",a , "*" , b ,"= ");
System.out.println("\nThe product of " + a + " and "
+ b + " is: " + multiRec(b, a));
// System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
System.out.print(x+" ");
if (y == 1) {
return x;
} else {
System.out.print(" + ");
return x + (multiRec(x, y - 1));
}
}
}
}

same functionality but without using continue and break?

how would you restructure this code so it doesnt use continue and break? i have tried but have had no luck. thanks
import java.util.*;
public class q6 {
public static void main(String args[]) {
int Number;
Scanner sc = new Scanner(System.in);
while (true) // seemingly an infinite loop
{
System.out.print("Enter a positive integer ");
System.out.println("or 0 to exit ");
Number = sc.nextInt();
if (Number == 0)
break;
else if (Number < 0);
System.out.print("Squareroot of " + Number);
System.out.println(" = " + Math.sqrt(Number));
//continue lands here at end of current iteration
}
//break lands here
System.out.println("a zero was entered");
}
}
import java.util.*;
public class q6 {
public static void main(String args[]) {
int Number;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer ");
System.out.println("or 0 to exit ");
Number = sc.nextInt();
while (Number>0)// looping while number >0
{
System.out.print("Squareroot of " + Number);
System.out.println(" = " + Math.sqrt(Number));
Number = sc.nextInt();
}
System.out.println("a zero was entered");
}
import java.util.*;
class q6 {
public static void main(String args[]) {
int Number;
Scanner sc = new Scanner(System.in);
while (instruct() && (Number=sc.nextInt())!=0) // seemingly an infinite loop
{
if (Number < 0);
System.out.print("Squareroot of " + Number);
System.out.println(" = " + Math.sqrt(Number));
//continue lands here at end of current iteration
}
//break lands here
System.out.println("a zero was entered");
}
static boolean instruct()
{
System.out.print("Enter a positive integer ");
System.out.println("or 0 to exit ");
return true;
}
}

Categories