Number Format Exception? - java

if (input.equals("arbitrary"))
{
System.out.println("What is your mass?");
massPerson = Double.parseDouble(input);
System.out.println("What is the planet's weight?");
massPlanet = Double.parseDouble(input);
System.out.println("What is the radius of the planet?");
radiusPlanet = Double.parseDouble(input);
weight = arbitraryPlanetWeight(massPerson, massPlanet, radiusPlanet);
}
I'm trying to run a program where it returns your weight on different planets. Everything is working except for my arbitrary planet. if you type "arbitrary" in the void main(string[]args) it asks "What is your weight" and stops running the args. It says i have a NumberFormatException. How can I fix this?

I have written you a example of what I assume you are trying to do.
Read all the comments and they should help you understand the code.
public static void main(String[] args) {
/*args is a array of String so for example:
["arbitrary"] -> array of length == 1
or
["12.2","11.1","13.3"]
*/
//If there were no elements in the array this code would break but we will assume there is at least one
String input = args[0];//put the first element in the array into input
double weight,massPerson,massPlanet,radiusPlanet;//define variables that we will use
if (input.equals("arbitrary"))//we look is the string equal to "arbitrary"
{
System.out.println("What is your mass?");
//The next commented out line if it where a command could not pass here because you are trying to interpret "arbitrary" as a double value
//double massPerson = Double.parseDouble(input);
//instead you want to user to input the value
Scanner s = new Scanner(System.in);
input = s.nextLine(); //now input is what the user has entered
//we assume that what the user has entered is a number
//if the user input something like "hello" the code would break and you would again get the NumberFormatException
massPerson = Double.parseDouble(input);
System.out.println("What is the planet's weight?");
input = s.nextLine();
massPlanet = Double.parseDouble(input);
System.out.println("What is the radius of the planet?");
input = s.nextLine();
radiusPlanet = Double.parseDouble(input);
s.close();//it is important to close the scanner -> there is also a try syntax to do this closing automatically so google : " try-with-resources Statement"
}
else{//we have something else as the input
//lets assume then that the args[] has 3 values which can all be parsed
//also since we have the values there is no need to ask the user
massPerson = Double.parseDouble(args[0]);//take the first value in the args array and pars it
massPlanet = Double.parseDouble(args[1]);//take the second value in the args array and pars it
radiusPlanet = Double.parseDouble(args[2]);//take the third value in the args array and pars it
}
//we have all the values at this point so we can calculate the weight
weight = arbitraryPlanetWeight(massPerson, massPlanet, radiusPlanet);
}
private static double arbitraryPlanetWeight(double massPerson, double massPlanet, double radiusPlanet) {
System.out.println("Do some calculations");
return 50;//dummy result
}

If your String input is equal to arbitrary, It can't be the representation of a number, then the Double.parseDouble(input) launches a parse exception.
You should have variables for each information you want:
if (input.equals("arbitrary"))
{
System.out.println("What is your mass?");
massPerson = Double.parseDouble(massPersonStr);
System.out.println("What is the planet's weight?");
massPlanet = Double.parseDouble(massPlanetStr);
System.out.println("What is the radius of the planet?");
radiusPlanet = Double.parseDouble(radiusPlanetStr);
weight = arbitraryPlanetWeight(massPerson, massPlanet, radiusPlanet);
}

Related

How to make user inputed string have the value of a double variable

I am creating an project where when the user inputs a word, the word will have the value of an already existing double variable. How would I make the word be able to equal the double variable when the user types it in? After the user types the word in, the input will be put into another math equation.
double answer = 5.5;
System.out.print("1st number: ");
System.out.print("Enter first number: ");
first = scanner.nextDouble();
// user inputs "Previous" , and the value is of the answer variable
System.out.print("Enter second number: ");
second = scanner.nextDouble();
// user inputs 1.1
answer = first + second;
//5.5+1.1=6.6
You could take the input as a String and convert it to a double.
double first = Double.parseDouble(scanner.nextLine());
EDIT:
To handle if the user selects "previous" or inputs a number, you could use a try catch. parseDouble throws an exception if it cannot turn a String into a double. So if Double.parseDouble("previous") would throw an exception, while Double.parseDouble("3.55") would not.
This would look something like:
first = scanner.nextLine();
double firstNumber;
try{
firstNumber = Double.parseDouble(first);
}
catch(NumberFormatException e){
if(first.equals("previous")){
firstNumber=answer;
}

Currency Exchanger

I am trying to write a code that will exchange between AED,MYR,USD. I got to the following code and I cant fix the error.
It looked like the system.in isn't closing so I wrote the inclose(). But I still get the same results.
My problem might be something else and am not seeing it.
EDIT: this is the current code with changes.
import java.util.Scanner;
public class CurrencyConverter
{
protected static long amount;
static long Namount ;
static int commesion;
static String to;
public static void main( String[] args )
{
CurrencyConverterM MSg=new CurrencyConverterM();
CurrencyConverterM account1 = new CurrencyConverterM( );
String from ;
for(int i=0 ;i<3; i++)
{
System.out.println("Please enter your currency (USD, AED, or MYR only): ");
Scanner in = new Scanner( System.in );
from = in.nextLine();
System.out.println("What currency do you want?: ");
String to = in.nextLine();
System.out.println("How much you want to convert?: ");
amount= in.nextLong();
//in.close();
if ("USD".equals(from)) {
amount=((long) (amount*0.27));
amount=account1.converter(to, amount);
}
else if ("MYR".equals(from)) {
amount=((long) (amount * 1.14));
amount =account1.converter(to, amount);
}
else {
if(mmount >= 900) {
Namount = (amount-50);
commesion =50;
}
else
{
Namount = (amount - 10);
commesion = 10;
}
}
System.out.println(MSg.getMsg());
}
}
}
the output should be as follows.
asking for current currency:
asking to what currency u want it:
asking about the amount.
am converting any amount to AED so I make it the main unit, then converting to the wished unit.
EDIT
public class CurrencyConverterM extends CurrencyConverter
{
long am;
#SuppressWarnings("static-access")
long converter (String to,long amount)
{
if ("MYR".equals(to)) {
am=(super.amount*=0.88);
}
else if ("MYR".equals(to)) {
am=(super.amount*=3.7);
}
return am ;
}
#SuppressWarnings("static-access")
public String getMsg()
{
return ("Thank you. The converted amount is "+(super.amount) + ". We will take" +super.commesion + " commission, and you will get "+ super.Namount);
}
}
before it didn't read the user's input, now its not converting the values.
I tried to print out my vales after each calculation but it looks like that the variable am is not being calculated correctly and its being multiplied by a 0 or divided by one ( the last result is always 0 ) but the amount that is in the main class is not 0 and its not converted to AED as well.
So I am getting this :Thank you. The converted amount is 0.0 1000.0. We will take50 commission, and you will get 0.0
String comparison is wrong.
from=="MYR" should be from.equals("MYR") rather I would recommend equalsIgnoreCase which is not case sensitive.
You should call scanner.nextLine() (in.nextLine()) and not in.toString()
Also you can use the same scanner and not to create 3 different scanners.
See the following part of your code updated with one Scanner (in):
System.out.println("Please enter your currency (USD, AED, or MYR only): ");
Scanner in = new Scanner( System.in );
from = in.nextLine();
System.out.println("What currency do you want?: ");
String to = in.nextLine();
System.out.println("How much you want to convert?: ");
amount= in.nextLong();
System.out.println(from + " " + to);
in.close();
by doing in.nextLine() you read the next line of user input.
From java 8 javadocs:
nextLine
public String nextLine()
Advances this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
The above will solve the issue that no input is read by your code.
Later you will have issues comparing the String user entered:
from=="USD" should be changed to "USD".equals(from)
Tip: Prefer to use "String".equals(variable) to avoid null pointer exceptions when variable is null.

reading files from java?

I have an assignment where I have to make a simple banking application. i need to store the customers information in a file with first and last name,customer id and balance. i then need to create a menu option to check balance,withdraw,deposit and quit. The problem i am currently having is trying to show the balance when they user wants to check balance. balance is on the forth line of my file and i am not sure how to only show the fourth line and then be able to use that number to add or subtract a number. I am trying to do this in case 1 in the switch statement. Any hints would be appreciated.
import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.*;
public class bank {
public static void main(String[] args) throws IOException {
String fileName; // stores the name of the file
String bankCustomer; // used to display the customers bank information
int menuOption = 0; // allows the user to enter a number so they can select what they want to do
Scanner keyboard = new Scanner(System. in );
// enter the file name to see customer information
System.out.print("enter file name ");
fileName = keyboard.nextLine();
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
// read customer information from file i need this
while (inputFile.hasNext()) {
bankCustomer = inputFile.nextLine();
System.out.println(bankCustomer);
}
System.out.println("Please enter the number for the following:\n 1) Balance \n 2) Deposit + \n 3) Withdrawal \n 4) Quit ");
menuOption = keyboard.nextInt();
switch (menuOption) {
case 1:
// need to show balance how do i do that?
while (inputFile.hasNext()) {
bankCustomer = inputFile.nextLine();
System.out.println(bankCustomer);
}
break;
default:
System.out.println("Invalid choice");
}
inputFile.close();
}
}
There are many ways to do this. One way is to read all the lines from the Scannerobject and convert it into a List (ArrayList) or String Array. That is each item in the Array or List corresponds to a line of the file.
The index of the list or array will then provide with the contents of the that particular file.
=============================================================================
Ok based on your comment, now that you still have not learn Arrays you can do it the way your reading your bank Customer name
String bankCustomer = inputFile.nextLine();
//Assuming second line contains account number
String bankAccountNumber = inputFile.nextLine();
// Assuming third line contains account type.
String bankAccountType = inputFile.nextLine();
// Fourth line has your account balance
String bankAccountBalanceStr = inputFile.nextLine();
double bankAccountBalance = 0d;
if(null != bankAccountBalanceStr && 0 > bankAccountBalanceStr.length()){
bankAccountBalance = Double.parseDouble(bankAccountBalanceStr);
}
Of course the answer is just indicative and does not do all the null checks and assumes the file format is exactly as you have told.
Without recreating your data and code, it appear that you are reading the entire line of data to bankcustomer. If your data file structure IS comma-delimited, you could then split the line into components. Define a data class
public static class customer {
public String first;
public String last;
public String customer_i;
public double balance:
}
Once you have the line translated into the data class, you can reference each by:
balance = customer.balance. etc.
This is approximate but I hope it helps.
The easiest way is to simply read and ignore the first three lines, by doing something like:
for (int i = 0; i < 3; i++)
inputFile.nextLine();
and then reading the fourth line as an integer with the Integer.parseInt () method.
int total = Integer.parseInt (inputFile.nextLine ());
Note that in both snippets error and exception handling was omitted.
You can either read 3 lines and not save their values,
or search each line for a keyword:
int balance;
if(!bankCustomer.indexOf("balance") != -1)
{
balance = Integer.parseInt(bankCustomer);
}

How to insist that a users input is an int?

Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.
I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
And continue on with my program, and everything works fine.
Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).
How can I make the code more robust, where it would verify that only an int was entered?
These are the results I'm hoping for:
Lets say the input was:
23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc
Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.
In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
scan.next();
}
int input = scan.nextInt();
Here's a simple example with prompts and comments.
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: "); // Initial prompt for input
// Repeat until next item is an integer
while (!scan.hasNextInt())
{
scan.next(); // Read and discard offending non-int input
System.out.print("Please enter an integer: "); // Re-prompt
}
// At this point in the code, the user has entered an integer
int input = scan.nextInt(); // Get the integer
// And now you can use the input variable.
Use scan.hasNextInt() to make sure the next input is an int.
I have written an example that ensures that the program will continue only if a number and not an invalid value is entered. Do not worry, I added the desired explanation.
The program asks the user to input a number. A loop ensures that the processing will not go on until a valid number is entered. Before that I have defined a variable "inputAccepted" that has false as default value. If he enters a number, the variable "inputAccepted" is set to true and the program leaves the loop. But if he enters something else than a number, an exception is thrown right in this moment, and the line that sets the variable "inputAccepted" to true will not be executed. Instead a message will be printed out that tells the user that his input is not valid. Since "inputAccepted" could not be set to true, the loop will do the same stuff again until the string can be converted to a number.
You can test the program here.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean inputAccepted = false;
while (!inputAccepted) {
try {
System.out.print("Please enter a number: ");
Integer.valueOf(input.nextLine());
inputAccepted = true;
} catch (NumberFormatException e) {
System.out.println("Not a valid number.");
}
}
System.out.println("Thank you!");
}
}
Just get "anything" and parse it:
Scanner scan = new Scanner(System.in);
Integer number = null;
while (number == null) {
try {
number = Integer.parseInt(scan.next());
} catch (NumberParseException e) {
System.out.println("bad input: " + input);
}
}
Without any code and just in English, I'd say there's two things you have to test or look out for. First that the input is an int, second that the int is within the correct range.
In terms of pseudocode, the first thing to do is make sure it's an int. Declaring an int named "input", I would put a try / catch block, where you try to scan in the user input as an int, with parseInt(). If the try part fails, you know it's not an int and can return an error message.
Then, now that you know that "input" is an int, you can test whether it is less than 1 or more than 150, and return an error message if so!
public class Sample {
/**
* author CLRZ
*/
public static void main(String[] args) {
int a; // variable
Scanner in = new Scanner(System.in); // scans your input
System.out.println("Enter your number's choice:");
int sem1 = in.nextInt(); // reads next integer
if (sem1 == 1) // conditioned if your choice number is equal to 1
System.out.println("Hello World1"); // output wil be Hello World
int b;
System.out.println("Enter your number's choice:");
int sem2 = in.nextInt();
if (sem2 == 2)
System.out.println("Hello World2");
int c;
System.out.println("Enter your number's choice:");
int sem3 = in.nextInt();
if (sem3 == 3)
System.out.println("Hello World3");
}
}

String replace function not replacing characters correctly - Java

I am trying to replace a specific character '8' with a '2' in a string. I think I have everything set up correctly and when I look online for examples, this looks like it should. When I print the string though, it is just as I entered it. To run it, test it with "80802" or some similar input. Thanks!
import java.util.Scanner;
class PhoneNumber {
public static void main(String[] args) {
String number = null;
Scanner scan = new Scanner(System.in);
// Prompt the user for a telephone number
System.out.print("Enter your telephone number: ");
// Input the user's name
number = scan.nextLine();
// Replace the relevant letters with numbers
number.replace('8', '2');
System.out.println("Your number is: " + number );
}
}
A common mistake... You want:
number = number.replace('8', '2');
String.replace() doesn't change the String, because Strings are immutable (they can not be changed). Instead, such methods return a new String with the calculated value.
number.replace() returns a new string. It does not change `number'.
number.replace('8','2'); returns the correct string it does not modify number. To get your desired functionality you must type
number = number.replace('8','2');
public static void main(String[] args) {
String number = null;
Scanner scan = new Scanner(System.in);
// Prompt the user for a telephone number
System.out.print("Enter your telephone number: ");
// Input the user's name
number = scan.nextLine();
// Replace the relevant letters with numbers
number = number.replace('8', '2');
System.out.println("Your number is: " + number );
}
Hope this helps.

Categories