Trying to read double data from the file that has different contents. For example if it is a double then the message should be "Double number is 23.5". and if it is not double number the message should be "Sixty three is not a double number". The file contents are
97.9
100.1
Three
Sixty three
77
12.4
3002.4
76
Cool
34.6
This is it
............
The code i wrote opens the file and scans next line But does not seem to properly work.
class ReadDouble
{
Scanner scan = new Scanner(System.in);
try
{
File textFile = new File ("doubleData.txt");
Scanner scanFile = new Scanner (textFile);
String str = scan.nextLine();
while(scanFile.hasNextLine())
{
double num = Double.parseDouble(str);
if(str == num)
{
System.out.println("Double number is" + str);
}
}//end while
}//end try
catch (NumberFormatException nfe)
{
System.out.println(str + "Is not a Double number");
}
}
}//end class
your try-catch should be inside the while loop, else it will come out in the first exception and rest of the lines will be ignored.
First, you should call String str = scan.nextLine(); within the loop otherwise you only ever read the first line. Also, your try / catch block should be wrapped around double num = Double.parseDouble(str); within the while loop otherwise you will not make another call to scan.nextLine() after you encounter your first non-double.
Finally, you shouldn't do if(str == num) as this will always be false. If Double.parseDouble(str) does not throw an exception, it contains the double found on that line.
Here is a solution that reads from standard in:
import java.util.Scanner;
public class ReadDouble {
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
while(scan.hasNextLine()){
String str = scan.nextLine();
try {
num = Double.parseDouble(str);
System.out.println("Double number is " + num);
} catch (NumberFormatException nfe) {
System.out.println(str + " is not a Double number");
}
}
}
}
Another option is to use Scanner to see if the next element is a double if it is read it using nextDouble() otherwise read using nextLine().
Given your file format, I would not bother with Scanner. Just read each line, pass it to Double.valueOf(String) and catch the exception if it is not a double.
Related
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()){
String line = scan.nextLine().toLowerCase();
System.out.println(line);
}
} finally {
scan.close();
}
}
Just wondering how I can terminate the program after I have completed entering the inputs?
As the scanner would still continue after several "Enter" assuming I am going to continue entering inputs...
I tried:
if (scan.nextLine() == null) System.exit(0);
and
if (scan.nextLine() == "") System.exit(0);
They did not work.... The program continues and messes with the original intention,
The problem is that a program (like yours) does not know that the user has completed entering inputs unless the user ... somehow ... tells it so.
There are two ways that the user could do this:
Enter an "end of file" marker. On UNIX and Mac OS that is (typically) CTRL+D, and on Windows CTRL+Z. That will result in hasNextLine() returning false.
Enter some special input that is recognized by the program as meaning "I'm done". For instance, it could be an empty line, or some special value like "exit". The program needs to test for this specifically.
(You could also conceivably use a timer, and assume that the user has finished if they don't enter any input for N seconds, or N minutes. But that is not a user-friendly way, and in many cases it would be dangerous.)
The reason your current version is failing is that you are using == to test for an empty String. You should use either the equals or isEmpty methods. (See How do I compare strings in Java?)
Other things to consider are case sensitivity (e.g. "exit" versus "Exit") and the effects of leading or trailing whitespace (e.g. " exit" versus "exit").
String comparison is done using .equals() and not ==.
So, try scan.nextLine().equals("").
You will have to look for specific pattern which indicates end of your input say for example "##"
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()){
String line = scan.nextLine().toLowerCase();
System.out.println(line);
if (line.equals("##")) {
System.exit(0);
scan.close();
}
}
} finally {
if (scan != null)
scan.close();
}
In this case, I recommend you to use do, while loop instead of while.
Scanner sc = new Scanner(System.in);
String input = "";
do{
input = sc.nextLine();
System.out.println(input);
} while(!input.equals("exit"));
sc.close();
In order to exit program, you simply need to assign a string header e.g. exit. If input is equals to exit then program is going to exit. Furthermore, users can press control + c to exit program.
You can check the next line of input from console, and checks for your terminate entry(if any).
Suppose your terminate entry is "quit" then you should try this code :-
Scanner scanner = new Scanner(System.in);
try {
while (scanner.hasNextLine()){
// do your task here
if (scanner.nextLine().equals("quit")) {
scanner.close();
}
}
}catch(Exception e){
System.out.println("Error ::"+e.getMessage());
e.printStackTrace();
}finally {
if (scanner!= null)
scanner.close();
}
Try this code.Your terminate line should be entered by you, when you want to close/terminate the scanner.
With this approach, you have to explicitly create an exit command or an exit condition. For instance:
String str = "";
while(scan.hasNextLine() && !((str = scan.nextLine()).equals("exit")) {
//Handle string
}
Additionally, you must handle string equals cases with .equals() not ==. == compares the addresses of two strings, which, unless they're actually the same object, will never be true.
Here's how I would do it. Illustrates using a constant to limit array size and entry count, and a double divided by an int is a double produces a double result so you can avoid some casting by declaring things carefully. Also assigning an int to something declared double also implies you want to store it as a double so no need to cast that either.
import java.util.Scanner;
public class TemperatureStats {
final static int MAX_DAYS = 31;
public static void main(String[] args){
int[] dayTemps = new int[MAX_DAYS];
double cumulativeTemp = 0.0;
int minTemp = 1000, maxTemp = -1000;
Scanner input = new Scanner(System.in);
System.out.println("Enter temperatures for up to one month of days (end with CTRL/D:");
int entryCount = 0;
while (input.hasNextInt() && entryCount < MAX_DAYS)
dayTemps[entryCount++] = input.nextInt();
/* Find min, max, cumulative total */
for (int i = 0; i < entryCount; i++) {
int temp = dayTemps[i];
if (temp < minTemp)
minTemp = temp;
if (temp > maxTemp)
maxTemp = temp;
cumulativeTemp += temp;
}
System.out.println("Hi temp. = " + maxTemp);
System.out.println("Low temp. = " + minTemp);
System.out.println("Difference = " + (maxTemp - minTemp));
System.out.println("Avg temp. = " + cumulativeTemp / entryCount);
}
}
You can check if the user entered an empty by checking if the length is 0, additionally you can close the scanner implicitly by using it in a try-with-resources statement:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter input:");
String line = "";
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNextLine()
&& (line = scan.nextLine().toLowerCase()).length() != 0) {
System.out.println(line);
}
}
System.out.println("Goodbye!");
}
}
Example Usage:
Enter input:
A
a
B
b
C
c
Goodbye!
I have program that is suppose to ask the user what txt file, go through the txt file and find all parsable ints and average them. I have the following code below, but it's giving me a bunch of errors. What is the cause of all these errors?
The txt file is:
5
15
312
16
eight seven 44
eighty-five thousand and sixty-two 13 98
93
import java.util.Scanner;
public class Ch12Pt2 {
public static void main(String[] args) throws NumberFormatException {
Scanner input = new Scanner(System.in);
System.out.print("Enter filename: ");
String filename = input.nextLine();
Scanner file = new Scanner(filename);
if(file.nextLine().equals(""))
{
System.err.println("Could not find file:" + filename);
System.exit(1);
}
do {
try {
int total = 0;
int count = 0;
int num = file.nextInt();
total = num + total;
//Display the results
System.out.println("The number of parsable numbers: " + count);
System.out.println("Average values: " + (total / count));
}
catch (NumberFormatException ex) {
System.out.println("Cannot parse " + num + " as an integer.");
file.nextInt();
}
} while (file.hasNextInt());
// Close the files
input.close();
file.close();
}
}
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Ch12Pt2.main(Ch12Pt2.java:21)
If you look at the JavaDoc for the constructor you used, you will that it "Constructs a new Scanner that produces values scanned from the specified string." What you want is Scanner#Scanner(File source), "...a new Scanner that produces values scanned from the specified file".
Do not use do-while, it will through a null pointer if your file does not have any integers. Use while instead. Also, do not initialize any of your variables inside the loop. This will cause them to re-initialize at ever iteration.
What is the point of file.nextInt(); in your catch block? It causes the program to skip an extra integer. Remove it. Furthermore, do not call input.close();, you do not want to close System.in.
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("Enter filename: ");
File file = new File(input.nextLine());
/*
* Check file existence before constructing your scanner. This will prevent a
* FileNotFoundException. Notice, I used File#exists and the NOT operator '!'
*/
if (!file.exists()) {
System.err.println("Could not find file: " + file.getName());
System.exit(0);
}
Scanner scanner = new Scanner(file);
// Initialize variables outside of loop.
int num = 0;
int total = 0;
int count = 1;
// No do-while
while (scanner.hasNextInt()) {
try {
num = scanner.nextInt();
total += num;
// Display the results
System.out.println("The number of parsable numbers: " + count);
System.out.println("Average values: " + (total / count));
// count is pointless unless you increase it after every number.
count++;
} catch (NumberFormatException ex) {
System.out.println("Cannot parse " + num + " as an integer.");
}
}
// Close the files
scanner.close();
Finally, as Mad Programmer pointed out, "eight seven" and "eighty-five thousand and sixty-two" are not numbers, thus Scanner#nextInt will not include them. A work around is to use Scanner#nextLine and parse accordingly. Something like this: How to convert words to a number?
Your code is all most all wrong. I have reworked it now it works.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Ch12Pt2 {
public static void main(String[] args) throws NumberFormatException, FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.print("Enter filename: ");
String filename = input.nextLine();
Scanner file = new Scanner(new FileReader(filename));
int num =0;
int count =0;
int total =0;
if(file.nextLine().equals(""))
{
System.err.println("Could not find file:" + filename);
System.exit(1);
}
while (file.hasNextInt()){
try {
num = file.nextInt();
total = num + total;
count++;
}
catch (NumberFormatException ex) {
System.out.println("Cannot parse " + num + " as an integer.");
}
}
// Close the files
input.close();
file.close();
System.out.println("The number of parsable numbers: " + count);
System.out.println("Average values: " + (total / count));
}
}
Scanner file = new Scanner(filename);
Exception in thread "main" java.util.NoSuchElementException
If you're reading data from a text file using a Scanner you need to specify a File, not a string, which is why you're getting the above error.
Use:
Scanner scanner = new Scanner(new FileReader("foo.txt"));
And then recursively go through the text file like this:
while(scanner.hasNext())
Your code:
while (file.hasNextInt());
Will not work because the hasNextInt() method will stop processing the text file when it encounters anything other than an integer.
System.out.println("Cannot parse " + num + " as an integer.");
Variable num is defined in a different scope to the body that handles the exception. An additional error will be thrown because num is not defined within the NumberFormatException body.
The txt file is: 5 15 312 16 eight seven 44 eighty-five thousand and sixty-two 13 98 93
If the items in the text file are on the same line it would be better to use the split method to get all elements and then detect whether they're numbers or not.
String line = sc.nextLine();
String elements = line.split(" ");
for (String e : elements) {
// add if int, or continue iteration
}
Otherwise, try something along the lines of:
int sum = 0;
int numElements = 0;
Scanner scanner = new Scanner(new FileReader("path-to-file"));
while (scanner.hasNext()) {
try {
int temp = Integer.parseInt(sc.nextLine());
sum += temp;
numElements += 1;
}catch(NumberFormatException e) {
continue;
}
}
System.out.println("Mean: "+ (sum/numElements));
I'm trying to create a program that reads in a list of integers from a file, and adds them all together and displays to the user. I can get this program to work properly but what I want to do is have it so if there is an invalid entry in the file (say, a word or anything that isn't a number) it will alert the user and ignore the invalid data and skip to the next available number. Here is my code so far:
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class IntegerReadIn {
public static void main(String[] args) {
int sum = 0;
try {
File myFile = new File("IntegerReadIn.txt");
Scanner scan = new Scanner(myFile);
while (scan.hasNextInt()) {
sum = sum + scan.nextInt();
}
System.out.println("Total = " + sum);
scan.close();
} catch (FileNotFoundException e) {
System.err.println("No such file name");
} catch (InputMismatchException e) {
System.err.println("Invalid entry found - integers only.");
}
}
}
First use nextLine() to read the entire line. after that Use Integer.parseInt() method to validate the integer input.
Scanner scan = new Scanner(myFile);
String s = scan.nextLine();
try{
Integer.parseInt(s);
}
catch(NumberFormatException ex){
System.out.println("Error....");
}
Perhaps instead of using your while for only hasNextInt() you should loop for haxNext()
That way you can explicitly check if you get an integer or not (and thus you can provide feedback to the user)
while (scan.hasNext()) {
if (scan.hasNextInt()) {
sum = sum + scan.nextInt();
} else {
System.out.println("Invalid Entry: " + scan.next());
}
}
Having this in consideration you will not be needing the InputMismatchException
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()){
String line = scan.nextLine().toLowerCase();
System.out.println(line);
}
} finally {
scan.close();
}
}
Just wondering how I can terminate the program after I have completed entering the inputs?
As the scanner would still continue after several "Enter" assuming I am going to continue entering inputs...
I tried:
if (scan.nextLine() == null) System.exit(0);
and
if (scan.nextLine() == "") System.exit(0);
They did not work.... The program continues and messes with the original intention,
The problem is that a program (like yours) does not know that the user has completed entering inputs unless the user ... somehow ... tells it so.
There are two ways that the user could do this:
Enter an "end of file" marker. On UNIX and Mac OS that is (typically) CTRL+D, and on Windows CTRL+Z. That will result in hasNextLine() returning false.
Enter some special input that is recognized by the program as meaning "I'm done". For instance, it could be an empty line, or some special value like "exit". The program needs to test for this specifically.
(You could also conceivably use a timer, and assume that the user has finished if they don't enter any input for N seconds, or N minutes. But that is not a user-friendly way, and in many cases it would be dangerous.)
The reason your current version is failing is that you are using == to test for an empty String. You should use either the equals or isEmpty methods. (See How do I compare strings in Java?)
Other things to consider are case sensitivity (e.g. "exit" versus "Exit") and the effects of leading or trailing whitespace (e.g. " exit" versus "exit").
String comparison is done using .equals() and not ==.
So, try scan.nextLine().equals("").
You will have to look for specific pattern which indicates end of your input say for example "##"
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()){
String line = scan.nextLine().toLowerCase();
System.out.println(line);
if (line.equals("##")) {
System.exit(0);
scan.close();
}
}
} finally {
if (scan != null)
scan.close();
}
In this case, I recommend you to use do, while loop instead of while.
Scanner sc = new Scanner(System.in);
String input = "";
do{
input = sc.nextLine();
System.out.println(input);
} while(!input.equals("exit"));
sc.close();
In order to exit program, you simply need to assign a string header e.g. exit. If input is equals to exit then program is going to exit. Furthermore, users can press control + c to exit program.
You can check the next line of input from console, and checks for your terminate entry(if any).
Suppose your terminate entry is "quit" then you should try this code :-
Scanner scanner = new Scanner(System.in);
try {
while (scanner.hasNextLine()){
// do your task here
if (scanner.nextLine().equals("quit")) {
scanner.close();
}
}
}catch(Exception e){
System.out.println("Error ::"+e.getMessage());
e.printStackTrace();
}finally {
if (scanner!= null)
scanner.close();
}
Try this code.Your terminate line should be entered by you, when you want to close/terminate the scanner.
With this approach, you have to explicitly create an exit command or an exit condition. For instance:
String str = "";
while(scan.hasNextLine() && !((str = scan.nextLine()).equals("exit")) {
//Handle string
}
Additionally, you must handle string equals cases with .equals() not ==. == compares the addresses of two strings, which, unless they're actually the same object, will never be true.
Here's how I would do it. Illustrates using a constant to limit array size and entry count, and a double divided by an int is a double produces a double result so you can avoid some casting by declaring things carefully. Also assigning an int to something declared double also implies you want to store it as a double so no need to cast that either.
import java.util.Scanner;
public class TemperatureStats {
final static int MAX_DAYS = 31;
public static void main(String[] args){
int[] dayTemps = new int[MAX_DAYS];
double cumulativeTemp = 0.0;
int minTemp = 1000, maxTemp = -1000;
Scanner input = new Scanner(System.in);
System.out.println("Enter temperatures for up to one month of days (end with CTRL/D:");
int entryCount = 0;
while (input.hasNextInt() && entryCount < MAX_DAYS)
dayTemps[entryCount++] = input.nextInt();
/* Find min, max, cumulative total */
for (int i = 0; i < entryCount; i++) {
int temp = dayTemps[i];
if (temp < minTemp)
minTemp = temp;
if (temp > maxTemp)
maxTemp = temp;
cumulativeTemp += temp;
}
System.out.println("Hi temp. = " + maxTemp);
System.out.println("Low temp. = " + minTemp);
System.out.println("Difference = " + (maxTemp - minTemp));
System.out.println("Avg temp. = " + cumulativeTemp / entryCount);
}
}
You can check if the user entered an empty by checking if the length is 0, additionally you can close the scanner implicitly by using it in a try-with-resources statement:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter input:");
String line = "";
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNextLine()
&& (line = scan.nextLine().toLowerCase()).length() != 0) {
System.out.println(line);
}
}
System.out.println("Goodbye!");
}
}
Example Usage:
Enter input:
A
a
B
b
C
c
Goodbye!
How can I say the following:
while(input is not an int){
do this
}
I tried this code but I know it's wrong:
int identificationnumber;
Scanner sc3 = new Scanner(System.in);
identificationnumber = sc3.nextInt();
while( identificationnumber != int){ // this line is wrong
Scanner sc4 = new Scanner(System.in);
identificationnumber = sc4.nextInt();
}
Any suggestions please.Thanks.
Javadocs are your friend: http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html
nextInt() throws an exception if the next token isn't an int. You're probably looking for hasNextInt()
Also, why are you creating a new Scanner every time you loop? (Or at all - you already have one before the loop)
try :
while (! scanner.hasNextInt()) { // while the next token is not an int...
scanner.next(); // just skip it
}
int i = scanner.nextInt(); // then read the int
Scanner throws an exception before getting to that line
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextInt()
The following code will work:
int i = 0;
while(true){
Scanner scan = new Scanner(System.in);
try{
i = scan.nextInt();
}catch (Exception e) {
break;
}
}
You want this?
String identificationnumber;
Scanner scanner = new Scanner(System.in);//Only one Scanner is needed
while (scanner.hasNext()) { // Is there has next input?
identificationnumber = scanner.next();//Get next input
try {
Integer.parseInt(identificationnumber);//Try to parse to integer
System.out.println(identificationnumber + " is a number!");
} catch (NumberFormatException e) {
System.out.println(identificationnumber + " is not a number!");
}
}
By writing sc3.nextInt() I assume you always get an int back, so checking for a non int seems a bit strange.
Maybe its better to return a string with the number inside. If the string is empty stop (you can just check against "") and otherwise convert it to an integer.
Use nextInt() method of scanner class.
It throws,
InputMismatchException - if the next token does not match the
Integer regular expression, or is out of range
You should be doing this:
if (sc3.hasNextInt())
Check this out: How to use Scanner to accept only valid int as input
With regards to class/type comparison, read this: What is the difference between instanceof and Class.isAssignableFrom(...)?