OutOfBounds Exception ; working with Fractions - java

I'm writing a program called FractionScaler that takes in a fraction from the user using Scanner, and then manipulates it. I've written a fraction class that handles all the calculations. The user is supposed to enter a fraction like this: "2/3" or "43/65" etc... This part works fine, the problem is when there is space between the integers: " 3 / 4 " or "2/ 5" etc... An "OutOfBoundsException: String index out of range: -1" occurs. Let me explain further.
//This is the user inputted fraction. i.e. "2/3" or " 3 / 4"
String frac = scan.next();
//This finds the slash separating the numerator from the denominator
int slashLocate = frac.indexOf("/");
//These are new strings that separate the user inputted string into two parts on
//either side of the "/" sign
String sNum = frac.substring(0,slashLocate); //This is from the beginning of string to the slash (exclusive)
String sDenom = frac.substring(slashLocate+1,frac.length()); //from 1 after slash to end of string
//This trims the white space off of either side of the integers
sNum = sNum.trim(); //Numerator
sDenom = sDenom.trim(); //Denominator
What I thought should be left is just two strings that look like integers, now I need to turn those strings into actual integers.
//converts string "integer" into real int
int num = Integer.parseInt(sNum);
int denom = Integer.parseInt(sDenom);
Now that I have two integers for the numerator and the denominator, I can plug them into a constructor for the fraction class I wrote.
Fraction fraction1 = new Fraction(num, denom);
I doubt this is the best way to go about this, but it is the only way I could think of. When the user inputted fraction has no spaces, EX. "2/3" or "5/6" , the program works fine.
When the user input has spaces of any kind, EX. "3 / 4" or " 3 /4" , the following error is shown:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1.
The terminal points to line 17 of my code which is this line above:
String sNum = frac.substring(0,slashLocate);
I don't know why I'm getting an out of bounds error. Can anyone else figure it out?
If something is unclear or I didn't give enough info, just say so.
Thanks very much.

Try String frac = scan.nextLine();
I think next() won't get anything after a space.

From the documentation:
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace.
That means this won't work, because when entering 2 / 3, frac will just contain the text "2":
String frac = scan.next();
//This finds the slash separating the numerator from the denominator
int slashLocate = frac.indexOf("/");

Related

How can I change 8 digit number's last digit with just using primitive data types?

This is the question.
An alien spaceship broadcasts a frequency of digital signals that can be
converted into 0-1 digits (always a 8 digit combination). In brief, a stream of digits entered via the console is supposed to be caught. It is obvious that the digits we acquire can be converted into base ten - decimal. The situation here is the noise which interferes with the original signal that we are listening to. Signal noise, which negates the last item of the stream, may appear in the very first character of your input stream. All of the characters must be either 0 or 1, otherwise it is a noise. Every first character is always 0. The input stream will be taken as a single set of numeric characters.
I changed too many thing in code and still it is not working with all numbers. But I got the message from these codes:
01000110
21010011
21001000
01000101
01001110
51000101
when we converted these to correct version it'll give the message. For example these give "FRIEND". I found this but program is not working with 00000000. It gives error. How can I correct this.
Scanner inp = new Scanner(System.in);
int frequency = inp.nextInt();
int digit1 = frequency/10000000;
int digit2 = (frequency/1000000)%10;
int digit3 = (frequency/100000)%10;
int digit4 = (frequency/10000)%10;
int digit5 = (frequency/1000)%10;
int digit6 = (frequency/100)%10;
int digit7 = (frequency/10)%10;
int digit8 = frequency%10;
int decimal_version = digit1*10000000 + digit2*1000000 + digit3*100000 + digit4*10000 + digit5*1000 + digit6*100 + digit7*10 + digit8;
System.out.println(decimal_version);
Change the last bit of 8-digit number:
num ^= 1B

calculating numbers after . (dot) in java

I am new to Java. creating calculator which calculates number from user input.
I have 2 Jtextfield in my application where user input numbers.
For example in first field user input 45678.230 and in second field 23214.210 which gives me subtraction result is 22464 but everything i want is full result followed by .(dot) so my answer should be 22464.02
String n1opn = n1open.getText();
String n1clsd = n1close.getText();
double n1intopen = (int) Double.parseDouble(n1opn);
double n1intclose = (int) Double.parseDouble(n1clsd);
double n1ltr = n1intclose - n1intopen;
System.out.println("output "+ n1ltr);
You seem to be casting your inputs to an int. Integers don't have any decimal bits so using double is correct for your case!

Parsing string to double/float throwing errors

I am extracting couple of values like 1234, 2456.00 etc from UI as string. When I try to parse this string to float, 1234 is becoming 1234.0 and when I tried to parse as double its throwing error. How can I solve this?
I am using selenium web driver and java. Below are few things I tried.
double Val=Double.parseDouble("SOQ");
double Val=(long)Double.parseDouble("SOQ");``
I think you mixed it up a bit when trying to figure out how to parse the numbers. So here is an overview:
// lets say you have two Strings, one with a simple int number and one floating point number
String anIntegerString = "1234";
String aDoubleString = "1234.123";
// you can parse the String with the integer value as double
double integerStringAsDoubleValue = Double.parseDouble(anIntegerString);
System.out.println("integer String as double value = " + integerStringAsDoubleValue);
// or you can parse the integer String as an int (of course)
int integerStringAsIntValue = Integer.parseInt(anIntegerString);
System.out.println("integer String as int value = " + integerStringAsIntValue);
// if you have a String with some sort of floating point number, you can parse it as double
double doubleStringAsDoubleValue = Double.parseDouble(aDoubleString);
System.out.println("double String as double value = " + doubleStringAsDoubleValue);
// but you will not be able to parse an int as double
int doubleStringAsIntegerValue = Integer.parseInt(aDoubleString); // this throws a NumberFormatException because you are trying to force a double into an int - and java won't assume how to handle the digits after the .
System.out.println("double String as int value = " + doubleStringAsIntegerValue);
This code would print out:
integer String as double value = 1234.0
integer String as int value = 1234
double String as double value = 1234.123
Exception in thread "main" java.lang.NumberFormatException: For input string: "1234.123"
Java will stop "parsing" the number right when it hits the . because an integer can never have a . and the same goes for any other non-numeric vales like "ABC", "123$", "one" ... A human may be able to read "123$" as a number, but Java won't make any assumptions on how to interpret the "$".
Furthermore: for float or double you can either provide a normal integer number or anything with a . somewhere, but no other character besides . is allowed (not even , or ; and not even a WHITESPACE)
EDIT:
If you have a number with "zeros" at the end, it may look nice and understandable for a human, but a computer doesn't need them, since the number is still mathematically correct when omitting the zeros.
e.g. "123.00" is the same as 123 or 123.000000
It is only a question of formatting the output when printing or displaying the number again (in which case the number will be casted back into a string). You can do it like this:
String numericString = "2456.00 "; // your double as a string
double doubleValue = Double.parseDouble(numericString); // parse the number as a real double
// Do stuff with the double value
String printDouble = new DecimalFormat("#.00").format(doubleValue); // force the double to have at least 2 digits after the .
System.out.println(printDouble); // will print "2456.00"
You can find an overview on DecimalFormat here.
For example the # means "this is a digit, but leading zeros are omitted" and 0 means "this is a digit and will not be omitted, even if zero"
hope this helps
Your first problem is that "SOQ" is not a number.
Second, if you want create a number using a String, you can use parseDouble and give in a value that does not have a decimal point. Like so:
Double.parseDouble("1");
If you have a value saved as a long you do not have to do any conversions to save it as a double. This will compile and print 10.0:
long l = 10l;
double d = l;
System.out.println(d);
Finally, please read this Asking a good question
The problem is you cannot parse non-numeric input as a Double.
For example:
Double.parseDouble("my text");
Double.parseDouble("alphanumeric1234");
Double.parseDouble("SOQ");
will cause errors.
but the following is valid:
Double.parseDouble("34");
Double.parseDouble("1234.00");
The number you want to parse into Double contains "," and space so you need first to get rid of them before you do the parsing
String str = "1234, 2456.00".replace(",", "").replace(" ", "");
double Val=Double.parseDouble(str);

Changing Word to Numbers Java

For my current code, I'm creating a word calculator where words are inputted to represent numbers and the calculations are done within the code. The requirements is to input two numbers and an operator into the console. I was able to parse the input into three parts, the first number, the operator, and the second number.
My question is how should I approach when I convert the word into number form? For example, if a user inputted:
seven hundred eighty-eight plus ninety-five
How can I turn that into 788 and 95 so I can do the calculations within the code? My input needs to go up to 1000.
This is part of my code for dividing up the input.
import java.util.Scanner;
public class TextCalc2 {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String in = input.nextLine();
in = in.toLowerCase();
while (!in.equals("quit")) {
if (in.contains("plus")){
String number1 = in.substring(0, in.indexOf("plus") - 1);
String number2 = in.substring(in.indexOf("plus") + 5, in.length());
String operator = in.substring(in.indexOf("plus"),in.indexOf("plus") + 5);
System.out.println(number1);
System.out.println(operator);
System.out.println(number2);
}
}
First of all there are problems in the way you are splitting the input (you have hard coded the operation). I would suggest splitting your input with " " (space) and then analyzing each part of the input separately.
You will have different types of words in your input, one is a single digit number, double digit number, operations and "hundred".
Then you should find which category first word of your input belongs to, if it has "-" it will be double digit, else look into other categories and search for it till you find it. Then based on category decide what you should do with it, if its a single digit, replace it with its equivalent. if its double digit, split and then replace each digit, if its operation store it and cut your input array from there so that you have separated the first value and second one, and if its hundred multiply previous single digit by 100.
After this parsing steps you will have something like this {"700","88"} , {"95"} and plus operation. now its easy to convert each string to its integer value using parse method and then apply the operation.
BTW, it would be easier to use Enum for your constants and just use their ordinal value. Also use the comment that Jared made for your double digit values.
Let me know if you still have question.

Java Convert from Scientific Notation to Float

I have a program that I am working on which would effectively convert binary, decimal, or hex numbers to other formats (don't ask why I'm doing this, I honestly don't know). So far I only have a binary - decimal conversion going, and it works fine however whenever the binary number entered is 8 digits or more it crashes.
As far as I can tell when I input the number 10011001 it gets translated to scientific notation and becomes 1.0011001E7 which wouldn't really be a problem, except that the way I am converting the numbers involves creating a string with the same value as the number and breaking it into individual characters. Unfortunately, this means I have a string valued "1.0011001E7" instead of "10011001", so when I cut up the characters I hit the "." and the program doesn't know what to do when I try to make calculations with that. So basically my question comes down to this, how do I force it to use the not-scientific notation version for these calculations?
Thanks for all your help, and here is the code if it helps at all:
//This Splits A Single String Of Digits Into An Array Of Individual Digits
public float[] splitDigits(float fltInput){
//This Declares The Variables
String strInput = "" + fltInput;
float[] digit = new float[strInput.length() - 2];
int m = 0;
//This Declares The Array To Hold The Answer
for (m = 0; m < (strInput.length() - 2); m++){
digit[m] = Float.parseFloat(strInput.substring(m, m + 1)); //Breaks here
}
//This Returns The Answer
return digit;
}
Just use BigDecimal
BigDecimal num = new BigDecimal(fltInput);
String numWithNoExponents = num.toPlainString();
Note here the fltInput will be automatically converted to a double.

Categories