When I run this code the console throws a NoSuchElementException. Why is that? Isn't the file being opened? The error says it corresponds to the line 34. Why?
Is Scanner reading the input from the file? Please help.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class standardDeviation {
public static void main(String[] args) throws FileNotFoundException{
// TODO Auto-generated method stub
File myFile = new File("input_data.txt");
PrintWriter output = new PrintWriter(myFile);
output.print("78.76 96.7 65.65 95.64 68.5 6.54 54.6");
output.close();
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String fileName = input.nextLine();
double sd = deviation(myFile);
System.out.println("The standard deviation of the values in this file is: " + sd);
}
public static double deviation(File myFile) throws FileNotFoundException{
Scanner in = new Scanner(myFile);
int i = 0;
double sum = 0;
double sigmaXI2 = 0;
while(i != -1){
double num = in.nextDouble();
sum += num;
sigmaXI2 += Math.pow(num, 2);
i++;
}
double sigmaXI_2 = Math.pow(sum, 2);
double s = Math.sqrt((sigmaXI2 - (sigmaXI_2)/i)/(i-1));
return s;
}
}
When do you expect the end of loop?
while(i != -1)
i keeps increasing and no there is no break.
According to JavaDoc of Scanner.nextDouble()
Scans the next token of the input as a double. This method will throw
InputMismatchException if the next token cannot be translated into a
valid double value. If the translation is successful, the scanner
advances past the input that matched.
If the next token matches the Float regular expression defined above
then the token is converted into a double value as if by removing all
locale specific prefixes, group separators, and locale specific
suffixes, then mapping non-ASCII digits into ASCII digits via
Character.digit, prepending a negative sign (-) if the locale specific
negative prefixes and suffixes were present, and passing the resulting
string to Double.parseDouble. If the token matches the localized NaN
or infinity strings, then either "Nan" or "Infinity" is passed to
Double.parseDouble as appropriate. Returns:the double scanned from the
input Throws: InputMismatchException - if the next token does not
match the Float regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed
When all token is exhausted due to infinite loop, NoSuchElementException is thrown.
To solve the problem, use hasNextDouble() method as the checking condition.
Related
I'm trying to read a list of tokens from a text file into separate variables by using a while loop.
Each line in the text file goes: String, Double, Int, Int, Boolean, and there are 11 lines, but I receive an InputMisMatchException for the double line after the String line.
The txt file reads as
AC 120.99 423 70 false
Toaster 18.99 101 30 true
Toaster 11.97 201 100 false
Yoyo 5.99 223 68 false
etc.
I've tried reading the file with .hasNext and .hasNextLine. When changing the double to String I get the error for the next Int and changing that to String again takes the error to the next Int but changing that does not move the exception further.
while (infp.hasNextLine() && count < LIMIT) {
String Product_description = infp.next();
double cost_per_item = infp.nextDouble(); //line 43
int product_id = infp.nextInt();
int quantity_at_hand = infp.nextInt();
boolean domestic_origin = infp.hasNext();
items[count] = new Item(Product_description, cost_per_item,
product_id, quantity_at_hand,
domestic_origin);
count++;
}
It's supposed to read all the tokens into variables and just create separate objects for each line in the text file. But from the error I believe it is only reading the first String then throwing the exception for the double.
The exception on line 43:
Exception in thread "main"
java.util.InputMismatchException at
java.util.Scanner.throwFor(Unknown Source) at
java.util.Scanner.next(Unknown Source) at
java.util.Scanner.nextDouble(Unknown Source) at DB_Master.main(DB_Master.java:43)
as you know nextDouble method is teruning a double value
double nextDouble()
Returns the next token as a long. If the next token is not a float or is out of range, InputMismatchException is thrown.
try give input in this format
like: 34,2 instead of 34.2
or try convert your Scanner with locale
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the Locale.getDefault() method; it may be changed via the useLocale(java.util.Locale) method
The localized formats are defined in terms of the following parameters, which for a particular locale are taken from that locale's DecimalFormat object, df, and its and DecimalFormatSymbols object, dfs.
for more ref see java docs
still not working try parsing by checking input type.
//************************************************************************
// MixedTypeInput
// This application demonstrates testing before reading to be
// sure to use the correct input method for the data.
//************************************************************************
import java.io.*;
import java.util.Scanner;
public class MixedTypeInput
{
public static void main(String[] args)
{
double number;
Scanner in = new Scanner(System.in);
System.out.println("Enter your gross income: ");
if (in.hasNextInt())
{
number = (double)in.nextInt();
System.out.println("You entered " + number);
}
else if (in.hasNextFloat())
{
number = (double)in.nextFloat();
System.out.println("You entered " + number);
}
else if (in.hasNextDouble())
{
number = in.nextDouble();
System.out.println("You entered " + number);
}
else
System.out.println("Token not an integer or a real value.");
}
}
Below is the script I have at the moment
import java.util.Arrays;
import java.util.Scanner;
public class SeeWhatTo
{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in); //define scan
int a = scan.nextInt();
int sum =0;
while (a>0 )
{
sum = sum +a;
a = scan.nextInt();
}
System.out.println(sum); //print out the sum
}
}
Currently, it stores an input value in a and then adds it to sum and once a negative or zero is given as an input, it suspends itself and outputs the sum.
I was wondering if there's an integer equivalent of isEmpty so that i can do while (! a.isEmpty() ) so when there's no input but an enter, then it would stop and prints out the sum.
A natural followup from that would be, is there a way to assign an input integer to a and check if it is empty or not at the same time in the while condition as in while ( ! (a=scan.nextInt()).isEmpty() )
Scanner can do 2 things:
Read line-by-line (nextLine).
Read token-by-token (next or e.g. nextInt).
These are really two different functionalities of Scanner, and if you're reading tokens then your Scanner basically doesn't know about empty lines.
If you call nextInt, Scanner does two things:
Finds the next token (default: delimited by any whitespace).
Tries to turn it in to an int.
The tokenizing behavior is an important feature of Scanner. If you enter 1 2\n and call nextInt twice, you get 1 and 2. However, if you enter an empty line, the tokenizing Scanner just skips it as whitespace and keeps looking for another token.
So the straightforward answer is "no": you can never get an "empty" int from a call to nextInt in a simply way and still retain the token-by-token behavior. (That's beyond the fact that a primitive variable in Java can't be "empty".)
One easy way to do what you're asking is to use line-by-line reading instead and call parseInt yourself:
Scanner systemIn = new Scanner(System.in);
int sum = 0;
String line;
while (!(line = systemIn.nextLine()).isEmpty()) {
sum += Integer.parseInt(line);
}
But you lose the tokenizing behavior. Now, if you enter 1 2\n, an exception is thrown because nextLine finds 1 2.
You can still read token-by-token with nextInt, but it's more complicated, using a second Scanner:
Scanner systemIn = new Scanner(System.in);
int sum = 0;
String nextLine;
while (!(nextLine = systemIn.nextLine()).isEmpty()) {
Scanner theInts = new Scanner(nextLine);
while (theInts.hasNextInt()) {
sum += theInts.nextInt();
}
}
Here, we can enter 1 2\n, get 1 2 as our next line, then ask the second Scanner to tokenize it.
So yes, you can program the functionality you're looking for, but not in an easy way, because Scanner is more complicated.
edit
Possibly another way is to use a delimiter on the line separator:
// use System.getProperty("line.separator") in 1.6
Scanner systemIn = new Scanner(System.in).useDelimiter(System.lineSeparator());
int sum = 0;
while (systemIn.hasNextInt()) {
sum += systemIn.nextInt();
}
Now, nextInt tokenizes the same way as nextLine. This will break the loop for any input that's not an int, including empty tokens. (Empty tokens aren't possible with the default delimiter.) I'm never really sure if people actually expect Scanner's default delimiting to work the way it does or not. It's possible creating a Scanner in this way makes it behave closer to what people seem to expect for reading the console, just line-by-line.
There isn't an equivalent in the sense that you describe, since String is a variable-length collection of characters, and having zero characters is still a valid String. One integer cannot contain zero integers, since by definition, it is already an integer.
However, your problem revolves around how Scanner works, rather than how int works.
Take a look at scan.hasNextInt(), which returns true if there is an int to read, and false otherwise. This may give you what you want, using something like:
Scanner scan = new Scanner(System.in);
int sum = 0;
while(scan.hasNextInt())
{
int a = scan.nextInt();
sum = sum + a;
}
System.out.println(sum);
Hello I have a bit of a problem with calculating numbers from a file.
My input is the following rawData.txt:
19.95
5
The output however is this:
49.0 57
My code looks like this:
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.PrintStream;
class ReadAndWrite
{
public static void main(String args[])
throws FileNotFoundException {
Scanner diskScanner = null;
diskScanner = new Scanner(new FileReader("rawData.txt"));
PrintStream diskWriter = new PrintStream("cookedData.txt");
double total;
double unitPrice = diskScanner.findWithinHorizon(".", 0).charAt(0);
System.out.println(unitPrice);
int quantity = diskScanner.findWithinHorizon(".", 0).charAt(0);
System.out.println(quantity);
total = unitPrice * quantity;
diskWriter.println(total);
diskScanner.close();
}
}
Eventually the cookedData.txt file contains the number 2793.0
Please help
You are fetching only the first character of each line - because of the charAt(0), then cast it to a double (casting char to double!!)
I can't understand what you are trying to do, but converting char to double using casting is almost always NOT what you should do.
Try using Double.parseDouble instead. see it here: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)
diskScanner.findWithinHorizon(".",0).charAt(0);
means that you are getting any character, because the first parameter of findWithinHorizon is a regular expression, and "." means one character. From that string you take the first char, i.e. 1. The ascii value of 1 is... 49.
I am trying to get input from user by using Scanner and DataInputStream. Here is my code that I'm using:
Scenario 1:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double d1 = scanner.nextDouble();
Scenario 2:
DataInputStream din = new DataInputStream(System.in);
System.out.print("Enter a number: ");
double d2 = Double.parseDouble(in.readLine());
When providing input as some characters like abc:
In scenario 1, I'm getting InputMismatchException.
In scenario 2, I'm getting NumberFormatException.
Why Scanner throws different exception? Can someone please clarify.
The JavaDoc of Scanner.nextDouble() says:
Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.
Returns:
The double scanned from the input
Throws:
InputMismatchException - if the next token does not match the Float regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed
Check your Scanner.class source:
public double nextDouble() {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Double)) {
double val = ((Double)typeCache).doubleValue();
useTypeCache();
return val;
}
setRadix(10);
clearCaches();
// Search for next float
try {
return Double.parseDouble(processFloatToken(next(floatPattern())));
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
When trying to parse, if Double.parseDouble() throws NumberFormatException (as per your Scenario 2), then Scanner.nextDouble() throw InputMismatchException (as per your Scenario 1).
I'm reading in two lines of a .txt file (ui.UIAuxiliaryMethods; is used for this) to calculate the BodyMassIndex(BMI) of patients, but I get a inputmismatchexception when the patientLenght is reached. These are my two lines of input, seperated by a \t:
Daan Jansen M 1.78 83
Sophie Mulder V 1.69 60
It's sorted in Name - Sex - Length - Weight. This is my code to save all elements in strings, doubles and integers:
package practicum5;
import java.util.Scanner;
import java.io.PrintStream;
import ui.UIAuxiliaryMethods;
public class BodyMassIndex {
PrintStream out;
BodyMassIndex() {
out = new PrintStream(System.out);
UIAuxiliaryMethods.askUserForInput();
}
void start() {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
String lineDevider = in.nextLine(); //Saves each line in a string
Scanner lineScanner = new Scanner(lineDevider);
lineScanner.useDelimiter("\t");
while(lineScanner.hasNext()) {
String patientNames = lineScanner.next();
String patientSex = lineScanner.next();
double patientLength = lineScanner.nextDouble();
int patientWeight = lineScanner.nextInt();
}
}
in.close();
}
public static void main(String[] args) {
new BodyMassIndex().start();
}
}
Somebody got a solution for this?
Your name has two tokens not one, so lineScanner.next() will only get the token for the first name.
Since a name can have more than 2 tokens theoretically, consider using String.split(...) instead and then parsing the last two tokens as numbers, double and int respectively, the third from last token for sex, and the remaining tokens for the name.
One other problem is that you're not closing your lineScanner object when you're done using it, and so if you continue to use this object, don't forget to release its resource when done.
Your name field has two token. and you are trying to treat them as one. that;s creating the problem.
You may use a " (double quote) to separate the name value from others. String tokenizer may do your work.
I changed the dots to commas in the input file. Hooray.