Comparing doubles' fractions - java

I'm struggling with the following code which supposed to compare numbers fractions and output some text to user informing him whether the fractions of numbers are the same, i.e.
User inputs two doubles: 3.14 and 4.14
Output: Fractions are the same
User input two double: 3.14 and 4.15
Output: Franctions are not the same
Somehow I've managed to compile the following code but once I tried to run it in Eclipse IDE I came accross the following notifications:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at comparison.main(comparison.java:12)
import java.util.Scanner;
class comparison
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double a,b;
a = scan.nextDouble();
b = scan.nextDouble();
compare(a,b);
}
public static void compare(double n, double m)
{
if(n- Math.floor(n) == m - Math.floor(m))
System.out.println("Fractions are the same");
else
System.out.println("Fractions are no the same");
}
}
I would love to obtain any proper explanation of my problems, I guess there are variety of different ways to solve this case in different way but can you please stick with my idea and help me out with this ?
Thanks in advance!

try
Double.toString (n).split ("\\.")[1].equals(Double.toString (m).split ("\\.")[1])
but to fix your problem change to
a = scan.nextDouble();
scan.nextLine (); // consume CR
b = scan.nextDouble();

The documentation for InputMismatchException states:
Thrown by a Scanner to indicate that the token retrieved does not
match the pattern for the expected type, or that the token is out of
range for the expected type.
So, basically, your scanner is trying to get a double, and you apparently entered something that either was not a double or was out of the range of a double.
The best way to handle this would probably be to get Strings from the scanner, and then check to see if they can be converted to doubles. Output an error message if not.
Edit - in agreement with #scary-wombat - use BigDecimal - it has a constructor that takes a String. Be sure to catch NumberFormatException, which will be thrown if what you enter cannot be converted.

Related

java.util.NoSuchElementException when using Scanner.nextInt() [duplicate]

I am very new to Java but am working through the book Java: How to program (9th ed.) and have reached an example where for the life of me I cannot figure out what the problem is.
Here is a (slightly) augmented version of the source code example in the textbook:
import java.util.Scanner;
public class Addition {
public static void main(String[] args) {
// creates a scanner to obtain input from a command window
Scanner input = new Scanner(System.in);
int number1; // first number to add
int number2; // second number to add
int sum; // sum of 1 & 2
System.out.print("Enter First Integer: "); // prompt
number1 = input.nextInt(); // reads first number inputted by user
System.out.print("Enter Second Integer: "); // prompt 2
number2 = input.nextInt(); // reads second number from user
sum = number1 + number2; // addition takes place, then stores the total of the two numbers in sum
System.out.printf( "Sum is %d\n", sum ); // displays the sum on screen
} // end method main
} // end class Addition
I am getting the 'NoSuchElementException' error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Addition.main(Addition.java:16)
Enter First Integer:
I understand that this is probably due to something in the source code that is incompatible with the Scanner class from java.util, but I really can't get any further than this in terms of deducing what the problem is.
NoSuchElementException Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.
http://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html
How about this :
if(input.hasNextInt() )
number1 = input.nextInt(); // if there is another number
else
number1 = 0; // nothing added in the input
You should use hasNextInt() before assigning value to variable.
NoSuchElementException will be thrown if no more tokens are available. This is caused by invoking nextInt() without checking if there's any integer available. To prevent it from happening, you may consider using hasNextInt() to check if any more tokens are available.
I faced this Error with nextDouble(), when I input numbers such as 5.3, 23.8 ... I think that was from my PC depending on computer settings that use Arabic (23,33 instead 23.33), I fixed it with add:
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
You must add input.close() at the end...
This error is mostly occur in case of 0nline IDE's on which you are testing your code. It is not configured properly, as if you run the same code on any other IDE/Notepad it works properly because the online IDE is not designed such a way that it will adjust the input code of your format, So you have to take input as the Online IDE supports.
If I may, I solved this issue today by realizing that I had multiple functions that used an instance of a Scanner, each. So basically, try refactoring so that you have only one instance opened and then closed in the end - this should work.
For anyone using gradle's application plugin, you must wire it to the standard console in build.gradle(.kts) otherwise it will keep throwing the NoSuchElementException error if you try to use scanner.
For groovy:
run {
standardInput = System.in}
For gradle kotlin dsl:
tasks.withType<JavaExec>() {
standardInput = System.`in`}
Integer#nextInt throws NoSuchElementException - if input is exhausted
You should check if there is a next line with Integer#hasNextLine
if(sc.hasNextLine()){
number1=sc.nextInt();
}
I added a single static scanner (sc) at the top of my class and closed it (sc.close()) when coming out of the whole class wherever I used return statements. Again that's one instance of scanner as suggested by another answer, which should be static.
package com.example.com;
import java.util.Scanner;
public class someClass {
static Scanner sc = new Scanner(System.in);
//Whole world of methods using same sc.
//sc.close()); return;
}
Other than that you can add #SuppressWarnings("resource") on the top of the troubling method to make the warning go away. But be careful about resource leaks.

Double.parseDouble not accounting for locale [duplicate]

I want to convert some numbers which I got as strings into Doubles, but these numbers are not in US standard locale, but in a different one. How can I do that?
Try java.text.NumberFormat. From the Javadocs:
To format a number for a different Locale, specify it in the call to getInstance.
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
You can also use a NumberFormat to parse numbers:
myNumber = nf.parse(myString);
parse() returns a Number; so to get a double, you must call myNumber.doubleValue():
double myNumber = nf.parse(myString).doubleValue();
Note that parse() will never return null, so this cannot cause a NullPointerException. Instead, parse throws a checked ParseException if it fails.
Edit: I originally said that there was another way to convert to double: cast the result to Double and use unboxing. I thought that since a general-purpose instance of NumberFormat was being used (per the Javadocs for getInstance), it would always return a Double. But DJClayworth points out that the Javadocs for parse(String, ParsePosition) (which is called by parse(String)) say that a Long is returned if possible. Therefore, casting the result to Double is unsafe and should not be tried!
Thanks, DJClayworth!
NumberFormat is the way to go, but you should be aware of its peculiarities which crop up when your data is less than 100% correct.
I found the following usefull:
http://www.ibm.com/developerworks/java/library/j-numberformat/index.html
If your input can be trusted then you don't have to worry about it.
Just learning java and programming. Had similar question. Found something like this in my textbook:
Scanner sc = new Scanner(string);
double number = sc.nextDouble();
The book says that a scanner automatically decodes what's in a String variabel and that the Scanner class automatically adapts to the language of the set Locale, system Locale being the default, but that's easy to set to something else.
I solved my problem this way. Maybe this could work for the above issue instead of parsing?
Addition: The reason I liked this method was the fact that when using swing dialouge boxes for input and then trying to convert the string to double with parse I got a NumberFormatException. It turned out that parse exclusively uses US-number formatting while Scanner can handle all formats. Scanner made the input work flawlessly even with the comma (,) decimal separator. Since the most voted up answer uses parse I really don't see how it would solve this particular problem. You would have to input your numbers in US format and then convert them to your locale format. That's rather inconvenient when ones numeric keybord is fitted with a comma.
Now you're all free to shred me to pieces ;)
You use a NumberFormat. Here is one example, which I think looks correct.
Use NumberFormat.getNumberInstance(Locale)
This should be no problem using java.text.DecimalFormat.
Do you know which locale it is? Then you can use
DecimalFormat format = DecimalFormat.getInstance(theLocale);
format.parse(yourString);
this will even work for scientific notations, strings with percentage signs or strings with currency symbols.
Here is how you use parseDouble to convert a String to a Double:
doubleExample.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class doubleExample {
public static void main(String[] args) {
Double myDouble = new Double("0");
System.out.println("Please enter a number:");
try
{
//get the number from console
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
myDouble = Double.parseDouble(br.readLine());
}
//if invalid value was entered
catch(NumberFormatException ne)
{
System.out.println("Invalid value" + ne);
System.exit(0);
}
catch(IOException ioe)
{
System.out.println("IO Error :" + ioe);
System.exit(0);
}
System.out.println("Double value is " + myDouble);
}
}

How to print a string with an int

I am trying to get this code to run and basically solve an equation. So, I asked the user to write an equation. It looked like this:
System.out.println("Write an equation and I will solve for x.");
int answer = in.nextLine();
But I can't get the user to write a string and an int. Do I need to say String answer or int answer?
An int is used when you want the user to enter a number, but here you're looking for a combination of numbers and other characters, so you will need to use a string. When you have the equation stored in a string, you can use other methods to split up the equation into something solvable, then set int answer to whatever the answer comes out to be.
On a simpler side, String will be required input from the user, User will enter the equation.
Then comes the complex part of solving/computing the equation.
1.) create your own parser to pass operands/operator.
2.) Provide a equation with values to some API, you can make use of MVEL or ANTLR
Here's a little program that demonstrates one way to get the equation and divide into numeric / non-numeric values provided the equation input is space delimited. You can then determine what the non-numeric values are and proceed from there.
import java.util.Scanner;
public class SolveX{
public static void main(String[] a){
Scanner in = new Scanner(System.in);
System.out.println("Write an equation and I will solve for x.");
String input = "";
while( in.hasNext() ){
input = in.next();
try{
double d = Double.parseDouble(input);
System.out.println("Double found at: " + input);
// Do what you need to with the numeric value
}
catch(NumberFormatException nfe){
System.out.println("No double found at: " + input);
// Do what you need to with the non numeric value
}
}
}//end main
}//end SolveX class

How to accept strings or integers in the same user input

I want to accept user input as either an integer or a string in Java but I always get an error no matter what I do.
My code is very simple (I'm a beginner):
System.out.println(
"Enter the row number (or enter e to quit the application):"
);
Scanner rowInput = new Scanner(System.in);
int row1 = rowInput.nextInt();
I want the user also to be able to press "e" to exit.
I have tried several things:
1) To convert row1 to a String and and say:
if((String)(row1).equals("e"){
System.out.println("You have quit") }
2) To convert "e" to an integer and say:
if(row1 == Integer.ParseInt("e"){
System.out.println("You have quit") }
3) To do the switch statement but it said I had incompatible types (String and an int).
My errors usually say: Exception in thread "main" java.util.InputMismatchException
Is there somebody who could help me?
Many thanks in advance!
You can try something like this
Scanner rowInput = new Scanner(System.in);
String inputStr = rowInput.nextLine();
try{
int row1 = Integer.parseInt(inputStr);
} catch (NumberFormatException e) //If exception occurred it means user has entered 'e'
{
if ("e".equals(inputStr)){
System.out.println("quiting application");
}
}
you should read the input from your scanner as String type and the try to convert that String input into integer using Integer.parseInt().
If its successful in parsing, it means user has input an Integer.
And If it fails, it will throw an exception NumberFormatException which will tell you that its not an Integer. So you can go ahead and check it for e if it is, do whatever you want as per your requirement.
You can't use nextInt() if you aren't sure that you will have a number coming in. Also, you can't parse e as an integer, because it is not an integer, it's either char or string (I'll suggest string in this case).
That means, your code should look like:
System.out.println("Enter the row number (or enter e to quit the application):");
Scanner rowInput = new Scanner(System.in);
string row1 = rowInput.next();
Then you have the data in a string. You can simply check if the string is e:
if (row1.Equals("e")) ...
It is also a good idea to check if the input is actually an integer then. Good way to check it is described here:
How to check if a String is numeric in Java
1) you should say Integer.parseInt() instead of Integer.ParseInt()
2) if you pass "e" to Integer.parseInt() you'll get java.lang.NumberFormatException
3) get your input as a string this way (cause it's safer)*:
Scanner rowInput = new Scanner(System.in);
String row = rowInput.next();
if (row.equals("e")) {
//do whatever
}
else if(row.matches("\\d+$")) {
//do whatever
}
*In your approach if user enters a non-integer input you'll encounter java.util.InputMismatchException
I have tried several things ....
Attempting to solve this problem by "trying things" is the wrong approach.
The correct approach is to understand what is going on, and then modify your solution to take this into account.
The problem you have is that you have a line of input that could be either a number or the special value e which means quit. (And in fact, it could be a couple of other things too ... but I will come to that.)
When you attempt to either:
call Scanner.nextInt() when the next input is not an integer, OR
call Integer.parseInt(...) on a String that is not an integer
you will get an exception. So what do you do?
One way is to change what you are doing so that you don't make those calls in those situations. For example:
call Scanner.hasInt() to see if the next token is an integer before calling nextInt(), or
test for the "e" case before you attempt to convert the String to an integer.
Another way to deal with this is to catch the exception. For example, you could do something like this:
String s = ...
try {
number = Integer.parseInt(s);
} catch (NumberFormatException ex) {
if (s.equals("e")) {
...
}
}
Either way will work, but I'm going to leave you to work out the details.
But the real point I'm trying to make is that the right way to solve this is to understand what is happening in your original version / versions, and based on your understanding, modify what you were doing. If you just randomly "try" alternatives that you found with Google, you won't progress to the point of being a productive programmer.
I said there were other cases. They are:
The user types something that is neither a number of your special e character. It could be anything. An empty line, hi mum ...
The user types the "end of file" character; e.g. CTRL-D on Linux or CTRL-Z on windows.
If you want your program to be robust you need to deal with these cases too.
Try this:
public class Demo{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String choice = null;
System.out.println("Enter e to exit or some other key to stay:");
choice=s.next();
if(choice.equals("e"))
{
System.out.println("quits");
System.exit(0);
}
else
{
System.out.println("stays");
}
}
}
You can't convert a string into integer, use char ASCII codes instead.

how can I parse "30.0" or "30.00" to Integer?

I using:
String str="300.0";
System.out.println(Integer.parseInt(str));
return an exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: "300.0"
How can I parse this String to int?
thanks for help :)
Here's how you do it:
String str = "300.0";
System.out.println((int) Double.parseDouble(str));
The reason you got a NumberFormatException is simply that the string ("300.00", which is a floating point number) could not be parsed as an integer.
It may be worth mentioning, that this solution prints 300 even for input "300.99". To get a proper rounding, you could do
System.out.println(Math.round(Double.parseDouble("300.99"))); // prints 301
I am amazed no one has mentioned BigDecimal.
It's really the best way to convert string of decimal's to int.
Josuha Bloch suggest using this method in one of his puzzlers.
Here is the example run on Ideone.com
class Test {
public static void main(String args[]) {
try {
java.math.BigDecimal v1 = new java.math.BigDecimal("30.0");
java.math.BigDecimal v2 = new java.math.BigDecimal("30.00");
System.out.println("V1: " + v1.intValue() + " V2: " + v2.intValue());
} catch(NumberFormatException npe) {
System.err.println("Wrong format on number");
}
}
}
You should parse it to double first and then cast it to int:
String str="300.0";
System.out.println((int)(Double.parseDouble(str)));
You need to catch NumberFormatExceptions though.
Edit: thanks to Joachim Sauer for the correction.
You can use the Double.parseDouble() method to first cast it to double and afterwards cast the double to int by putting (int) in front of it. You then get the following code:
String str="300.0";
System.out.println((int)Double.parseDouble(str));
Integer.parseInt() has to take a string that's an integer (i.e. no decimal points, even if the number is equivalent to an integer. The exception you're getting there is essentially saying "you've told me this number is an integer, but this string isn't in a valid format for an integer!"
If the number contains a decimal component, then you'll need to use Double.parseDouble(), which will return a double primitive. However, since you're not interested in the decimal component you can safely drop it by just casting the double to an int:
int num = (int)Double.parseDouble(str);
Note however that this will just drop the decimal component, it won't round the number up at all. So casting 1.2, 1.8 or 1.999999 to an int would all give you 1. If you want to round the number that comes back then use Math.round() instead of just casting to an int.

Categories

Resources