NumberFormatException while multiplying - java

I'm trying to 'Run Configurations' in Eclipse.
When I pass something like '1 + 2', or '123 - 321', or '123 / 321' it works well.
The problem appears when I try to do multiplying. In this case I get
Exception in thread "main" java.lang.NumberFormatException: For input string: ".project"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Main.main(Main.java:15)
Here's the code:
public class Main {
public static void main(String[] args) {
double aNum;
double bNum;
char operator;
String result = "Error";
Calculator calc = new Calculator();
if (args.length == 0) {
System.out.println("No parameters were entered");
}
else {
aNum = Double.parseDouble(args[0]);
bNum = Double.parseDouble(args[2]);
operator = args[1].charAt(0);
result = calc.calculate(aNum, bNum, operator);
System.out.println(result);
}
}
}
public class Calculator {
public String calculate(double aNum, double bNum, double operator) {
String result = "Error";
if(operator=='+'){
result = String.valueOf(aNum+bNum);
}
else if (operator=='-') {
result = String.valueOf(aNum-bNum);
}
else if (operator=='*') {
result = String.valueOf(aNum*bNum);
}
else if (operator=='/') {
if (bNum==0) {
System.out.println("Forbidden operation: div by zero!");
}
else {
result = String.valueOf(aNum/bNum);
}
}
else {
System.out.println("Unhandled operator. Please use '+-*/' as operators");
result = "Error";
}
return result;
}
}

The problem is how you're invoking the program. If you run:
java Calculator 5 * 10
then in some command shells, the * will be automatically expanded to all filenames in the current directory. You should be able to fix this with quoting, e.g.
java Calculator 5 '*' 10
Or ask for the values from within the calculator, instead of taking them from the command line.

Related

Java Input Validation

So I am working with a program that is supposed to incorporate try-catch blocks for exception handling. What I can't figure out is how to write a simple if statement for checking input from the user via Scanner to make sure it is a double and not a letter or a character so that if it is the program will catch it, display the error message, and tell the user to re-enter another value until a suitable input is entered. What I am looking for is a simple if(_width equals a letter/character) then return false along with an error message to go along with my already present if statement that checks whether the input is greater than zero.
my current code is below:
public class Rectangle {
//two double data fields width and height, default values are 1 for both.
private double width = 1;
private double height = 1;
private String errorMessage = "";
//no-arg constructor creates default rectangle
public Rectangle() {
}
//fpzc, called by another program with a statement like Rectangle rec = new Rectangle(#, #);
public Rectangle (double _width, double _height) throws Exception {
setWidth(_width);
setHeight(_height);
}
//get functions
public double getArea(){
return (width * height);
}
public double getPerimeter() {
return (2*(width + height));
}
public String getErrorMessage() {
return errorMessage;
}
//set functions
public void setWidth(double _width) throws Exception {
if( !isValidWidth(_width)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
width = _width;
}
public void setHeight(double _height) throws Exception {
if ( !isValidHeight(_height)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
height = _height;
}
//isValid methods
public boolean isValidWidth(double _width) {
if(_width > 0){
return true;
}
else {
errorMessage = "Invalid value for width, must be greater than zero";
return false;
}
if ()
}
public boolean isValidHeight(double _height) {
if(_height > 0){
return true;
}
else {
errorMessage = "Invalid value for height, must be greater than zero";
return false;
}
}
}
My class is being called by another test program that i have written correctly. Any help is appreciated! Thank you.
maybe something like:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
try {
Double.parseDouble(str);
}
catch( Exception e ){
System.out.println(errorMessage);
}
or iterate through the input and check if each character is digit:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
for(int i=0;i<str.length();i++){
char token = str.charAt(i);
if(!Character.isDigit(token) && token!='.' ) {
System.out.println(token + " doesnt work");
break;
}
}
On declaring your scanner you could also:
double num;
String errorMessage = "error";
while(true) {
Scanner in = new Scanner(System.in);
if (in.hasNextDouble()) {
num = in.nextDouble();
System.out.println(num);
break;
}
else System.out.println(errorMessage);
}
Maybe this code helps you:
double Input=0;
while(!(Input > 0)){{
System.out.println("Enter Valid Number");
Input = new Scanner(System.in).nextDouble();
}

Rounding double or scientific notation

I want to round my number if it exceeds 8 character long.
For example,
// Big number rounding using scientific notation
double myDouble1 = 123456789;// desired output: 1.23e+08
Another situation
// Rounding
double myDouble2 = 12345.5678901234; // Desired output: 12345.57
I've tried using String.format() with %.2g and %.7, but I couldn't achieve the desired output.
Here's the code that I've tried to come up with.
public String parseResult(String val){
String formatted = val;
try{
if(formatted.length() > 8){
double temp = Double.parseDouble(val);
if(temp % 1 == 0){
formatted = String.format("%.2g", temp);
}else{
formatted = String.format("%.7g", temp);
}
}
}
catch(NumberFormatException e)
{
}
return formatted;
}
public class SolutionMain
{
public static void main(String[] args)
{
double myDouble1 = 123456789; // Desired output: 1.23e+08
double myDouble2 = 12345.5678901234; // Desired output: 12345.57
System.out.println(parseResult(myDouble1));
System.out.println(parseResult(myDouble2));
}
public static String parseResult(Double myDouble)
{
DecimalFormat format = null;
if(myDouble.toString().length() > 8)
{
if(myDouble % 1 == 0)
format = new DecimalFormat("0.00E00");
else
format = new DecimalFormat("#.00");
}
return format.format(myDouble);
}
}
For more pattern format details: Customizing Formats
class ScientificNot
{
public static String getScientifiNotation(double n)
{
int n1=(int)n;
String s0=String.valueOf(n-(double)n1);
String s1=String.valueOf((double)((int)n));
int in=s1.indexOf(".");
String mantissa=null,exp=null;
if(n>=10000000.0)
{
if(s1.length()>8)
{
mantissa=s1.substring(0,3);
exp=s1.substring(3);
double man=Double.parseDouble(mantissa)/100.0;
return(man+"e"+exp.length());
}
else
return s1;
}
else if(s0.length()>8)
{
double num=(((double)((int)(n*1000))));
int dp=((int)num%1000);
if(dp%10>=5)
dp=(dp-(dp%10))+10;
return String.valueOf(((int)num/1000)+"."+(dp/10));
}
else{
s1=""+n;
}
return s1;
}
}

Print to file from within a method

I am taking an input file with various infix expressions, calculating them, and printing them back to another output file with each line formatted as:
THE MODULO 10 VALUE OF %%%%% IS %
The output text and modulo 10 answer are both correct; however, I cannot get the program to reprint the entire expression in between "OF" and "IS."
I tried putting output.write(token) in the getToken() method, but I got a "cannot find symbol" error. So I understand that I can't access the BufferedWriter from another method since it is declared in main, but how can I get around that?
import java.io.*;
public class Lab1
{
public static char token;
public static String expr;
public static int k = 0;
public static void main (String[] args)
{
int exprValue;
String line;
try
{
BufferedReader input = new BufferedReader(new FileReader("inputfile.txt"));
BufferedWriter output = new BufferedWriter(new FileWriter("outputfile.txt"));
while ((line = input.readLine()) != null)
{
output.write("THE MODULO 10 VALUE OF ");
expr = line;
getToken();
output.write(token);
exprValue = expression();
output.write(" IS " + exprValue);
output.newLine();
output.newLine();
k = 0;
}
input.close();
output.close();
}
catch (IOException ex)
{
System.err.println("Exception:" + ex);
}
}
public static void getToken()
{
k++;
int count = k-1;
if(count < expr.length())
{
token = expr.charAt(count);
}
}
public static int expression()
{
int termValue;
int exprValue;
exprValue = term();
while(token == '+')
{
getToken();
termValue = term();
exprValue = (exprValue + termValue)%10;
}
return exprValue;
}
public static int factor()
{
int factorValue = token;
if(Character.isDigit(token))
{
factorValue = Character.getNumericValue(token);
getToken();
}
else if(token == '(')
{
getToken();
factorValue = expression();
if(token == ')')
{
getToken();
}
}
return factorValue;
}
public static int term()
{
int factorValue;
int termValue;
termValue = factor();
while(token == '*')
{
getToken();
factorValue = factor();
termValue = (termValue * factorValue)%10;
}
return termValue;
}
}
Currently my input is:
(3*6+4)*(4+5*7)
3*((4+5*(1+6)+2))
My output is:
THE MODULO 10 VALUE OF ( IS 8
THE MODULO 10 VALUE OF 3 IS 3
Solved the problem. In the while loop in the main method, replace output.write(token) with output.write(expr)

Java.lang.NumberFormatException thrown

I am trying to write a program for converting positive binary inputs into hex.
Why am i getting this errors while compiling my binary to hex converter..
Exception in thread "main" java.lang.NumberFormatException: For input string: "148.0"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:441)
at BinToHex.convertbintohex(BinToHex.java:24)
at Test.main(Test.java:4)
Here is my BinToHex class
import java.io.*;
public class BinToHex {
double tempDec,fractionpart;
long longofintpart,templongDec;
String inpu ="1001.01";
String hexOutput,intpart,tempDecString,hex = null;
static int i = 1;
public void convertbintohex() {
if (inpu.contains(".")) {
int placesAfterPoint = inpu.length() - inpu.indexOf(".") - 1;//every thing
long numerator = Long.parseLong(inpu.replace(".", ""), 2);//goes
double decimalOfInput = ((double) numerator) / (1L << placesAfterPoint);//alright till here
while (true) {
tempDec = decimalOfInput * 16;
if ((int)tempDec == tempDec) {
tempDecString = String.valueOf(tempDec);
templongDec = Long.parseLong(tempDecString, 10);
hexOutput = Long.toHexString(templongDec);
break;
} else {
intpart = String.valueOf((long)tempDec);
longofintpart = Long.valueOf(intpart).longValue();
if(i==1){
hex=Long.toHexString(longofintpart);
hexOutput = hex + ".";
i=i+1;
}else{
hexOutput = hexOutput + hex;
}
fractionpart = tempDec-(int)tempDec;
decimalOfInput = fractionpart;
}
}
} else {
// this part is ok
tempDecString = String.valueOf(Integer.parseInt(inpu, 2));
templongDec = Long.parseLong(tempDecString, 10);
hexOutput = Long.toHexString(templongDec);
}
System.out.println(hexOutput);
}
}
and my Test class..
public class Test{
public static void main(String args[]){
BinToHex i = new BinToHex();
i.convertbintohex();
}
}
sorry for such a question ;-)
really need help
Long.parseLong "Parses the string argument as a signed long". 148.0 is a double.
You're using a cast in the "if" statement, but not afterwards:
if ((int)tempDec == tempDec) {
tempDecString = String.valueOf(tempDec);
templongDec = Long.parseLong(tempDecString, 10);
instead, try:
if ((long)tempDec == tempDec) {
tempDecString = String.valueOf((long)tempDec);
templongDec = Long.parseLong(tempDecString, 10);
You're already doing that later on in the else statement, you just missed it above. I think there are other issues in this code but this should answer the original question.

I get an error message as follows: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

I get an error message as follows: Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at emp.MainClass.main(MainClass.java:52)
Using the following code, how do I alleviate this problem?
public class MainClass {
//main class
public static void main(String[] args){
// variable
String input;
boolean salaryError = true;
boolean dependentError = true;
boolean nameError = true;
boolean charError = true;
Employee emp1 = new Employee();
displayDivider("EMPLOYEE INFORMATION");
do{
input = getInput(" First Name");
nameError = nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setfirstName(input);
do{
input = getInput(" Last Name");
nameError =nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setlastName(input);
do{
input = getInput(" Gender: M or F");
charError = characterChecker(input.charAt(0));
if(!charError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!charError);
char g = input.charAt(0);
emp1.setgender(g);// validates use of M or F for gender
do{
input = getInput(" number of dependents");
dependentError = integerChecker(input);
if(!dependentError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!dependentError);
emp1.setdependents(Integer.parseInt(input));
do{
input = getInput(" annual salary");
salaryError = doubleChecker(input);
if(!salaryError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
} while(!salaryError);
emp1.setannualSalary(Double.parseDouble(input));
emp1.displayEmployee();//displays data for emp1
Employee emp2 = new Employee("Speed","Racer",'M',1,500000.00);
displayDivider("EMPLOYEE INFORMATION");
emp2.displayEmployee();// displays data for emp2
terminateApplication(); //terminates application
System.exit(0);//exits program
}//end of main
// gets Input information
public static String getInput(String data)
{
String input = "";
input = javax.swing.JOptionPane.showInputDialog(null,"Enter your " + data);
return input;
}// end getInput information
// The display divider between employees
public static void displayDivider(String outputLab)
{
System.out.println("********" + outputLab + "********");
}// end display divider
// Terminates the application
public static void terminateApplication()
{ javax.swing.JOptionPane.showMessageDialog(null,"Thanks for the input!");
}// end terminateApplication
public static boolean doubleChecker(String inStr){
boolean outBool = true;
double tmpDbl = 0.0;
try{
tmpDbl = Double.parseDouble(inStr);
if(tmpDbl <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean integerChecker(String intStr){
boolean outBool = true;
int tmpInt = 0;
try{
tmpInt = Integer.parseInt(intStr);
if(tmpInt <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean nameValidate(String str){
for(char ch : str.toCharArray()){
if(!Character.isDigit(ch)){
return true;
}
}
return false;
}
public static boolean characterChecker(char gen){
boolean outBool = true;
try{
if(!( gen ==( 'M') || gen ==('F')))
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
}//end of Main Class
Your string is length 0. Make sure string.length() > 0 before accessing its elements. The problem is at the line the exception says the problem is on.
Better answer: are you using an IDE? If so, observe the line the exception tells you you have an error on. Set a breakpoint before that line, debug, and note the contents of the object on which the error happened (in this case the string). Then check the javadoc for the method that threw the exception to see if there is any problem calling that method on that string.
If you are not using an IDE, you will either need to use one or find a standalone debugger. Having a good debugger is a requirement of Java development.
This should save you a lot of SO questions going forward.
StringIndexOutofBoundsException means you're try to access the String using an index and the index is either negative or greater than the size of the string.
You're wrong in this part:
charError = characterChecker(input.charAt(0));
Because you're not check if the input length is 0.
Try to change that line to this:
charError = input != null && input.length() > 0 && characterChecker(input.charAt(0));

Categories