I'm new to java and I decided to write a simple program to practice IFs. Here's what it should do:
Ask the user about the currency.
Ask the user about the amount of money he wants to transfer.
Calculate the commission rate and show the details to the user.
Ask the user for confirmation; if he types "y" , the program should print "A". If he types "n" , the program should print "B".
Here's the code :
import java.util.Scanner;
public class CommissionRate {
static String Confirm;
static byte CommissionRate=10;
static String Commission="1%.";
static double TotalCost;
static double MoneyAmount;
static byte CurrencyNum;
static char CurrencySign;
static Scanner sc = new Scanner(System.in);
public static void Currency(){
System.out.println("Please choose your desired currnecy.");
System.out.println("1.USD");
System.out.println("2.EUR");
System.out.println("3.GBP");
System.out.println("4.CAD");
System.out.println("5.CNY");
System.out.println("6.JPY");
CurrencyNum = sc.nextByte();
if (CurrencyNum==1|CurrencyNum==4) {
CurrencySign= '$';
}
else {
if (CurrencyNum==2){
CurrencySign='€';
}
else {
if (CurrencyNum==3){
CurrencySign='£';
}
else {
if (CurrencyNum==5|CurrencyNum==6){
CurrencySign='¥';
}
}
}
}
}
public static void MoneyAmount() {
System.out.println("Please enter the amount of money you would like to transfer :");
MoneyAmount = sc.nextDouble();
if (MoneyAmount>499 & MoneyAmount<10000){
CommissionRate=5;
Commission="0.5%.";
}
else{
if (MoneyAmount>10000){
CommissionRate= 3;
Commission="0.3%.";
}
}
TotalCost = MoneyAmount + MoneyAmount * CommissionRate/1000;
System.out.println("Please confirm the transfer. ( y/n ) ");
System.out.println("A transfer of "+MoneyAmount+CurrencySign+".");
System.out.println("Commission rate is "+Commission);
System.out.println("You need to pay " + TotalCost+"." );
sc.nextLine();
Confirm = sc.nextLine();
if (Confirm=="y"){
System.out.println("A");
}
else if (Confirm=="n") {
System.out.println("B");
}
}
}
At first , the program wouldn't wait for the user to confirm/abort the transfer and it would print "B". Then , I read this and added the "sc.nextLine()". However the program just ignores the last if and doesn't print anything. Any ideas on what causes the problem and how to solve it ?
p.s.: Here's what I get when running the program:
Please choose your desired currnecy.
1.USD
2.EUR
3.GBP
4.CAD
5.CNY
6.JPY
2 // my input
Please enter the amount of money you would like to transfer :
120 // my input
Please confirm the transfer. ( y/n )
A transfer of 120.0€.
Commission rate is 1%.
You need to pay 121.2.
y // my input
please try
if (Confirm.equals("y")){
and
else if (Confirm.equals("n"))
with == you compare the object references not the values.
Try equals instead of == and one times should be sc.nextLine();
Confirm = sc.nextLine();
if (Confirm.equals("y")){
instead of
sc.nextLine();
Confirm = sc.nextLine();
if (Confirm=="y"){
Related
I am currently experimenting with Java, trying to get the user to input an integer. If the user doesn't enter an integer I want a message to appear saying "You need to enter an Integer: " with a completely new input field to the original one.
Code:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
int counter = 0;
boolean run = true;
int userInput = 0;
while (run) {
System.out.print("Enter an integer: ");
if (inputScanner.hasNextInt()) {
userInput = inputScanner.nextInt();
} else if (!inputScanner.hasNextInt()) {
while (!inputScanner.hasNextInt()) {
System.out.print("You need to enter an Integer: ");
userInput = inputScanner.nextInt();
}
}
System.out.println(userInput);
if (counter == 6) {
run = false;
}
counter++;
}
}
}
At the moment the code above gives an Exception error ("java.util.InputMismatchException"). I have tried to use a try/catch but this doesn't really work because I want the user to see the second message ("You need to enter an Integer") everytime they don't enter an integer and I don't want it to re-loop around the main run loop for the same reason. I'm sure there is a better way to do this, however I am not sure of it. Any help will be massively appreciated, thanks in advance.
In this case it would make more sense for the Scanner to use hasNextLine and then convert the String to an Integer. If that you could do something like this:
try {
new Integer(inputScanner.hasNextLine);
} catch (Exception e) {
System.out.println(“<error message>”)
}
In place of the if(inputScanner.hasNextInt()) due to the fact that the hasNextInt function will error out if there is not an Integer to be read.
I'm writing a java program where the initial part is a scanner. I need the user to enter a folder name and then the program needs to confirm. The scanner is asking the relevant question and accepting the answer. I then need it to confirm Y or N. Y, the program will continue. N, I need the code to loop back and ask the first question again. I've searched around, and I can see a number of solution for integers, but not for text.
import java.util.Scanner;
public class webSiteGenerator {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.println("Please enter a source folder: ");
String sourceFolder = obj.nextLine();
System.out.println("You have selected the folder '" + sourceFolder + "'. Are you sure (Y/N)");
String confirmation = obj.nextLine();
while (!"Y".equalsIgnoreCase(confirmation) && "N".equalsIgnoreCase(confirmation)) {
System.out.println("Response not recognised. Please confirm... Are you sure (Y/N)");
confirmation = obj.next();
}
}
}
The reaponce of "Y' and "N" will be stored in the string sourceFolder, so you just need to compare the string sourcFolder with Y and N.
so your code be like:
int flag = 0;
while (flag!=1){
if(sourceFolder.equals("Y") || sourceFolder.equals("y")){
//Your Code
flag=1;
}else if((sourceFolder.equals("N") || sourceFolder.equals("n")){
flag=1;
} else{
print("Invalid Input! Please choose only between Y or N ");
flag=1;
}
}
P.S flag is actually used for exit the while condition. You can use any word instead of flag.
Ask if anything creates a doubt.
I am trying to make a program which can accept certain integer type input from user, but stop the input as soon the user enters "stop".
I have tried doing so, but it's not working properly. Have a look.
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.io.*;
class Iron {
public static void main(String args[]) throws InterruptedException {
Scanner in = new Scanner(System.in);
System.out.println("Do you wanna play?, type yes to start.");
String a = in.nextLine();
String b; String c="goo";
String d,e="helloWorld";
String al="helloworld";
int f=0,g;
if (a.equalsIgnoreCase("yes")) {
System.out.println("Thanks for staring the game ");
TimeUnit.SECONDS.sleep(1);
System.out.println("-------Welcome to Need For Fun-------");
System.out.println();
TimeUnit.SECONDS.sleep(1);
while (!c.equalsIgnoreCase("yes")) {
System.out.println();
System.out.println("Enter your name_");
b = in.nextLine();
System.out.println("Is your name " + b + "?");
System.out.println("If yes type yes or if not type something else");
c = in.nextLine();
}
TimeUnit.SECONDS.sleep(0);
System.out.println("So, the game is quite similar to hand cricket");
System.out.println("You will win, if your number and Computer's number are equal");
System.out.println("To stop the game any time type start");
System.out.println();
TimeUnit.SECONDS.sleep(1);
System.out.println("So ready to play the game?, type yes to confirm.");
d = in.nextLine();
if(d.equalsIgnoreCase("yes"));
{
while(!al.equalsIgnoreCase("stop")) {
System.out.println();
try {
System.out.println("Type your number");
e = in.nextLine();
f = Integer.parseInt(e);
}
catch(NumberFormatException e1) {
al = in.nextLine();
if(al.equalsIgnoreCase("stop"))
break;
}
if (f < 10) {
g = (int) (Math.random() * 10);
if (f == g)
System.out.println("Congrats, you won. ");
else
System.out.println("Oops!, try again");
} else if (f>10)
System.out.println("Please enter a number between 1-10");
}
System.out.println("Thanks for playing, better luck next Time");
}
}
}
}
It does stops when I type stop, but I need to enter it two times.
Here's the run tab where I executed my program.
Do you wanna play?, type yes to start.
yes
Thanks for staring the game
-------Welcome to Need For Fun-------
Enter your name_
gourav
Is your name gourav?
If yes type yes or if not type something else
yes
So, the game is quite similar to had cricket
You will win, if your number and Computer's number are equal
To stop the game any time type start
So ready to play the game?, type yes to confirm.
yes
Type your number
4
Oops!, try again
Type your number
54
Please enter a number between 1-10
Type your number
4
Oops!, try again
Type your number
stop
3
Oops!, try again
Type your number
stop
stop
Process finished with exit code 0
change this block
catch(NumberFormatException e1) {
al = in.nextLine();
if(al.equalsIgnoreCase("stop"))
break;
}
to
catch(NumberFormatException e1) {
if(e.equalsIgnoreCase("stop"))
break;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm trying to make a USD <-> JPY converter. If the numbers seem off to you, trust me - I did the math. Also, I know the spacing's off, but it doesn't matter. Morph it in N++ if you need to.
import java.util.Scanner;
import java.lang.Math;
public class jpy_usd {
public static void main(String[] args) {
//Initializing variables and the scanner
boolean isSourceUSD;
double usd;
double usdMult = 0.00803568;
int jpy;
double jpyMult = 124.449;
Scanner scanner = new Scanner(System.in);
//Selecting an input currency and checking for valid input arguments
System.out.println("Choose your input currency. Type \'USD\' for U.S. Dollars or \'JPY\' for Japanese Yen.");
while(isSourceUSD != true && isSourceUSD != false) {
if(scanner.nextLine == "USD") {
isSourceUSD = true;
} else if(scanner.nextLine == "JPY") {
isSourceUSD = false;
} else {
System.out.println("Invalid argument. Please use \'USD\' for U.S. Dollars or \'JPY\' for Japanese Yen.");
}
}
//Asking for the input in the chosen currency and converting
if(isSourceUSD) {
System.out.println("Please enter the value to convert");
usd = scanner.nextDouble;
System.out.println(usd " in JPY is " (Math.round(usd * jpyMult)));
} else if(!isSourceUSD) {
System.out.println("Please enter the value to convert");
jpy = scanner.nextInt;
System.out.println(jpy " in USD is " (Math.round(jpy * usdMult)));
}
}
}
If you want me to add the error messages, I suppose I could. Without much explanation, there's 6 errors split evenly across these two lines:
System.out.println(usd " in JPY is " (Math.round(usd * jpyMult)));
System.out.println(jpy " in USD is " (Math.round(jpy * usdMult)));
There's two of each error - one per line - so the similarities in the lines have to be the same issues (duh). So, anybody got any clues?
P.S.: If there's anyhing wrong with the code other than that, please do mention it.
P.S. 2: I know I'm basically making this code public by putting every single character into this block of text, but please don't steal. I know someone's about to do it, but please don't.
~wundr
There are ideally many problems with your code, starting with the Naming conventions to method names, String comparison. Below is the minimal code changes required to make your code work:-
import java.util.Scanner;
import java.lang.Math;
public class jpy_usd {
public static void main(String[] args) {
//Initializing variables and the scanner
String isSourceUSD;
double usd;
double usdMult = 0.00803568;
int jpy;
double jpyMult = 124.449;
Scanner scanner = new Scanner(System.in);
//Selecting an input currency and checking for valid input arguments
System.out.println("Choose your input currency. Type \'USD\' for U.S. Dollars or \'JPY\' for Japanese Yen.");
if(scanner.nextLine() .equalsIgnoreCase( "USD")) {
isSourceUSD = "USD";
} else if(scanner.nextLine() .equalsIgnoreCase( "JPY")) {
isSourceUSD ="JPY" ;
} else {
isSourceUSD="NA";
System.out.println("Invalid argument. Please use \'USD\' for U.S. Dollars or \'JPY\' for Japanese Yen.");
}
//Asking for the input in the chosen currency and converting
if(isSourceUSD.equalsIgnoreCase("USD")) {
System.out.println("Please enter the value to convert");
usd = scanner.nextDouble();
System.out.println(usd +" in JPY is "+ (Math.round(usd * jpyMult)));
} else if(isSourceUSD.equalsIgnoreCase("JPY")) {
System.out.println("Please enter the value to convert");
jpy = scanner.nextInt();
System.out.println(jpy+ " in USD is " +(Math.round(jpy * usdMult)));
}
else{
System.out.println("Do nothing!!!");
}
scanner.close();
}
}
Im working on an assignment for an intro to java class and having some difficulty accounting for a situation when a user needs to give multiple inputs. The problem is given as follows:
"Ask the user to input a number. You should use an input dialog box for this input. Be sure to convert the String from the dialog box into a real number. The program needs to keep track of the smallest number the user entered as well as the largest number entered. Ask the user if they want to enter another number. If yes, repeat the process. If no, output the smallest and largest number that the user entered.
This program outputs the largest and smallest number AT THE END of the program when the user wants to quit.
Also, your program should account for the case when the user only enters one number. In that case, the smallest and largest number will be the same."
My issue is that I cannot figure out how to make the program continuously ask the user if they want to input another number....for as many times as they say yes (obviously). I know I will have to use a loop or something, but I am a beginner with this and do not know where to start. Any help would be appreciated, and thanks in advance!
Here is what I have so far:
package findingminandmax;
import javax.swing.JOptionPane;
public class Findingminandmax
{
public static void main(String[] args)
{
String a = JOptionPane.showInputDialog("Input a number:");
int i = Integer.parseInt(a);
String b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
if ("yes".equals(b)) {
String c = JOptionPane.showInputDialog("Input another number:");
int j = Integer.parseInt(c);
int k = max(i, j);
JOptionPane.showMessageDialog(null, "The maximum between " + i +
" and " + j + " is " + k);
} else {
JOptionPane.showMessageDialog(null, "The maximum number is " + i );
}
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
String b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
while(b.equalsIgnoreCase("yes")){
String c = JOptionPane.showInputDialog("Input another number:");
// your logic
b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
}
// then have your logic to print maximum and minimum number
But to get Yes/No inputs use a Confirm dialogbox rather than a input dialogbox
e.g.
int b = JOptionPane.showConfirmDialog(null, "Would you like to input another number? yes or no", "More Inputs", JOptionPane.YES_NO_OPTION);
while (b == JOptionPane.YES_OPTION) {
// your logic
}
while(true) {
//do stuff
if ("yes".equals(b)) {
//do other stuff
} else { break; }
}