While loop with hasNext(); not fully looping - java

I'm in the process of creating a program that reads data from an external file, compares it with other data within the file then prints the results to a new external file. I am having problems with the while loop section of my code. I am unsure whether it is the while loop itself or the for loop which is nested within. Here is the code:
public class WageCalculator {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader("TestData.txt")); //Scanner for external file
PrintWriter output = new PrintWriter("wagedaily.txt");
float RecommendedMaximum;
RecommendedMaximum = Float.parseFloat(JOptionPane.showInputDialog(null, "Enter the recommended maximum journey cost:"));
String ShipID, JourneyID; //Variables
int JourneyLength, Crew;
double RateOfPay, CrewCost, TotalCost;
while (input.hasNext()) { //EOF-Controlled While Loop
ShipID = input.nextLine();
JourneyID = input.nextLine();
JourneyLength = input.nextInt();
Crew = input.nextInt();
CrewCost = 0; //Default Values Set
TotalCost = 0;
for (int x = Crew; x > 0; x--) { //For Loop updates the above values
RateOfPay = input.nextDouble();
CrewCost = RateOfPay * JourneyLength;
TotalCost = TotalCost + CrewCost;
}
if (TotalCost < RecommendedMaximum) { //if-else statements to compare values
System.out.println("The total cost of...");
output.println("The total cost of...");
} else if (TotalCost == RecommendedMaximum) {
System.out.println("The total cost of...");
output.println("The total cost of...");
} else {
System.out.println("The total cost of...");
}
}
output.close(); //Close both Scanner and Printwriter
input.close();
}
}
The error I get is this:
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.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at (package).WageCalculator.main(WageCalculator.java:30)
The error says it's line 30 in my code that is the problem but I am not so sure.
Incase anyone needs to see the TestData.txt file:
Monarch //ShipID
M141 //JourneyID
16 //JourneyLength
6 //Crew
10.5 //RateOfPay -
10.5
20
20
20
30 //- RateOfPay
Princess //ShipID
P103 //JourneyID
18 //JourneyLength
5 //Crew
40 //RateOfPay -
45
45
60
80 //- RateOfPay
Any help would be appreciated :)

You're making a bunch of input.nextXXX() calls within the loop after checking input.hasNext() only once at the top of the loop. Don't do that as this is very unsafe and bound to fail and as there should always be a one-to-one correspondence between a check and a get. For instance, if you want to get a next line, there should be one input.HasNextLine() called before calling calling input.nextLine(). Same for input.next() or input.nextInt().
Myself, I'd read line by line by checking hasNextLine() and then once reading in the nextLine(), and then manipulating the String received.
while (input.hasNextLine()) {
String line = input.nextLine();
// now do not use input further within the loop
}
You could then within the loop use a second Scanner using the line received, or split the line via String#split(String regex) or do whatever you need to do with it.
Or you could use String replaceAll(...) and regular expressions to get rid of all white space followed by "//" followed by any chars. e.g.,
while (input.hasNextLine()) {
String line = input.nextLine();
// get rid of white space followed by "//" followed by anything
line = line.replaceAll("\\s+//.*", "");
System.out.println(line);
}
Edit
I've looked a bit more into your question and your data, and I am going to amend my answer. If you're absolutely sure of the integrity of your data file, you could consider checking for nextline once per obtaining data of an entire ship. For example:
public static void main(String[] args) {
InputStream inStream = GetData.class.getResourceAsStream(DATA_FILE);
List<Cruise> cruiseList = new ArrayList<>();
Scanner input = new Scanner(inStream);
while (input.hasNext()) {
String name = getLine(input);
String id = getLine(input);
int length = Integer.parseInt(getLine(input));
int crew = Integer.parseInt(getLine(input));
// assuming a class called Cruise
Cruise cruise = new Cruise(name, id, length, crew);
for (int i = 0; i < crew; i++) {
cruise.addPayRate(Double.parseDouble(getLine(input)));
}
cruiseList.add(cruise);
}
input.close();
}
private static String getLine(Scanner input) {
String line = input.nextLine();
// get rid of white space followed by "//" followed by anything
line = line.replaceAll("\\s+//.*", "");
return line;
}

The reason it gives you trouble is because when the user enters an integer then hits enter, two things have just been entered - the integer and a "newline" which is \n. The method you are calling, "nextInt", only reads in the integer, which leaves the newline in the input stream. But calling nextLine() does read in newlines, which is why you had to call nextLine() before your code would work. You could have also called next(), which would also have read in the newline.
Also read the Documentation of Scanner class for further understanding :
Here is the Corrected Code :
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class WageCalculator {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader("TestData.txt")); //Scanner for external file
PrintWriter output = new PrintWriter("wagedaily.txt");
float RecommendedMaximum;
RecommendedMaximum = Float.parseFloat(JOptionPane.showInputDialog(null,
"Enter the recommended maximum journey cost:"));
String ShipID, JourneyID; //Variables
int JourneyLength, Crew;
double RateOfPay, CrewCost, TotalCost;
while (input.hasNext()) { //EOF-Controlled While Loop
System.out.println("While Enter"); // For debugging purpose
ShipID = input.nextLine();
JourneyID = input.nextLine();
JourneyLength = input.nextInt();
input.nextLine(); // Enter this to read the data of skipped Line
Crew = input.nextInt();
input.nextLine();
CrewCost = 0; //Default Values Set
TotalCost = 0;
for (int x = Crew; x > 0; x--) { //For Loop updates the above values
System.out.println("While Under if Enter");// For debugging purpose
RateOfPay = input.nextDouble();
input.nextLine();
CrewCost = RateOfPay * JourneyLength;
TotalCost = TotalCost + CrewCost;
System.out.println("While Under if Exit");// For debugging purpose
}
if (TotalCost < RecommendedMaximum) { //if-else statements to compare values
output.println("The total cost of...");
} else if (TotalCost == RecommendedMaximum) {
System.out.println("The total cost of...");
output.println("The total cost of...");
} else {
System.out.println("The total cost of...");
}
System.out.println("While Exit"); // For debugging purpose
}
output.close(); //Close both Scanner and Printwriter
input.close();
}
}

Related

no output after infinite while loop with hasNext() java [duplicate]

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 to use Scanner in both main and method

I'm trying to get input in both my main and other methods, but I'm not clear on how to get the scanner working in both.
It gives me a weird error:
Exception in thread "main"
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at Hwk11.getRainData(Hwk11.java: 28)
at Hwk11.main(Hwk11.java: 18)
Code:
import java.util.Scanner;
public class Hwk11 {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
System.out.println("How many weeks of data do you have?");
int numWeeks = stdin.nextInt();
if (numWeeks <= 0 || numWeeks > 52) {
System.out.println("Invalid number of weeks.");
}
else {
double[] rainWeeks = new double [numWeeks];
getRainData(rainWeeks);
showRain(rainWeeks);
}
}
public static void getRainData(double[] rainFall) {
Scanner stdin = new Scanner(System.in);
System.out.println("Enter the weekly rainfall for each week.");
for (int index = 0; index < rainFall.length; index++) {
System.out.println("Week number " + (index + 1) + ":");
rainFall[index] = stdin.nextDouble();
}
}
public static void showRain(double[] rainFall) {
for (int index = 0; index < rainFall.length; index++) {
System.out.print(rainFall[index] + " ");
}
}
}
People are saying "works for me".
The problem that the behavior (whether it works or not) depends on exactly how input is provided.
If you provide input interactively, it will probably work.
If you provide input by redirecting standard input like this:
java Hwk11 < input.txt
then it won't.
The problem is that a Scanner will read-ahead and buffer any characters available from its input stream. That is fine normally, but in your code you have created two distinct Scanner objects to read from System.in. Thus when standard input is redirected:
The first Scanner.nextInt call will cause most / all of the input to be buffered in the first Scanner
When the second Scanner is created and Scanner.nextDouble is called, it won't see the input buffered in the first Scanner and that will lead to an exception ... when it runs out of input characters "too soon".
The solution is to NOT create multiple Scanner objects for the same input stream. Use one Scanner and either put it in a field, or pass it as a parameter to all of the places that it needs to be used.
Works for me. Don't enter anything but a double if you asking for next double so no "2.3 cm", just pass 2.3 and add cm when you print in
I am assuming your showRain(double[] rainFall) method probably executes before getRaindata(double[] rainFall) is able to finish and populate the array. Array you passsing to showRain(double[] rainFall) might be empty.
Try putting your method call for showRain(double[] rainFall) after loop in getRanData(double[] rainFall)
Alternitivly try passing the whole Scanner object to method.
public static void getRainData(double[] rainFall, Scanner stdin) {
//Scanner stdin = new Scanner(System.in);
System.out.println("Enter the weekly rainfall for each week.");
for (int index = 0; index < rainFall.length; index++) {
System.out.println("Week number " + (index + 1) + ":");
rainFall[index] = stdin.nextDouble();
}
showRain(rainFall);
}
Don't forget to close it when you done with scanner.

Parsing through a file that uses whitespace as a delimiter -java. (I dont understsand it)

Could someone help me understand what I am doing wrong please?
I have to read through a file with 11 integers and doubles on each line, each line needs to become its own object and stored in an arrayList. However, the delimiter is a single space. And I have used this code, but it doesnt seem to work and I am not sure what I am doing wrong.
package p2_0000000;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
public class P2_000000 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Which file year would you like to analyze:\n"
+ "1) 2007\n"
+ "2) 2011\n"
+ "3) 2013\n"
+ "(Enter number for choice)");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
ArrayList<dwellingClass> alist = new ArrayList<dwellingClass>();
if (choice == 1) {
try {
File file = new File("2007.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] info = line.split(" ");
int age = Integer.parseInt(info[0]);
int region = Integer.parseInt(info[1]);
double lmed = Double.parseDouble(info[2]);
double fmr = Double.parseDouble(info[3]);
double extremelyLowIncome = Double.parseDouble(info[4]);
double veryLowIncome = Double.parseDouble(info[5]);
double lowIncome = Double.parseDouble(info[6]);
int bedrooms = Integer.parseInt(info[7]);
double value = Double.parseDouble(info[8]);
int rooms = Integer.parseInt(info[9]);
double utility = Double.parseDouble(info[10]);
dwellingClass dwelling = new dwellingClass(age, region, lmed, fmr, extremelyLowIncome, veryLowIncome, lowIncome, bedrooms, value, rooms, utility);
alist.add(dwelling);
}
scanner.close();
} catch (Exception a) {
a.printStackTrace();
System.exit(0);
};
for (dwellingClass each : alist) {
System.out.println(each);
}
}
System.out.println(alist.get(0).getAge());
}
}
I get these errors:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
Thank you everyone for the help!
I also figured out that this could also work for anyone who reads this post later:
public class P2_0000000 {
public static void main(String[] args) {
// TODO code application logic here
ArrayList<dwellingClass> alist = new ArrayList<dwellingClass>();
try {
File file = new File("2007.txt");
Scanner input = new Scanner(file);
while (input.hasNext()) {
int age = input.nextInt();
int region = input.nextInt();
double lmed = input.nextDouble();
double fmr = input.nextDouble();
double extremelyLowIncome = input.nextDouble();
double veryLowIncome = input.nextDouble();
double lowIncome = input.nextDouble();
int bedrooms = input.nextInt();
double value = input.nextDouble();
int rooms = input.nextInt();
double utility = input.nextDouble();
dwellingClass dwelling = new dwellingClass(age, region, lmed, fmr, extremelyLowIncome, veryLowIncome, lowIncome, bedrooms, value, rooms, utility);
alist.add(dwelling);
}
input.close();
} catch (Exception a) {
a.printStackTrace();
System.exit(0);
};
for (dwellingClass each : alist) {
System.out.println(each.getAge() + each.getRegion());
}
System.out.println(alist.get(0).getAge());
}
}
First you can read the file this way:
Scanner in = new Scanner(new FileReader("2007.txt"));
Secondly to parse white spaces you will need to use something like this:
yourString.split("\\s+");
So your this line should become:
String[] info = line.split("\\s+");
Then you can access your String the way you did it.
But make sure that you are passing the right values i.e. the right types to each of the methods otherwise yo will get the error you are getting.
You should do a number validation of the string you read from the file and make sure that it matches the requirements for building your dwellingClass object.
String line = scanner.nextLine();
String[] info = line.split("\\s+");
boolean validInput = true;
//loop through your info array and check each number is valid beforehand
for(int i = 0; i < info.length; i++)
{
if(!info[i].matches("\\d"))
{
validInput = false;
break;
}
}
//now we want to make sure our input was valid or else we don't create the object
if(info.length == 11 && validInput == true)
{
dwellingClass dwelling = new dwellingClass(
Integer.parseInt(info[0]),
Integer.parseInt(info[1]),
Double.parseDouble(info[2]),
Double.parseDouble(info[3]),
Double.parseDouble(info[4]),
Double.parseDouble(info[5]),
Double.parseDouble(info[6]),
Integer.parseInt(info[7]),
Double.parseDouble(info[8]),
Integer.parseInt(info[9]),
Double.parseDouble(info[4]));
alist.add(dwelling);
}
If you put this inside your while loop it will only create objects with lines read from the file that contain only numbers and contains 11 digits, other lines will simply be ignored. This would allow execution of the file even if a line is not formatted correctly.
You are creating a NEW file, not loading your file. To load a file, you need to use a file input stream. your Scanner wont find anything in a new file and thus its all Null
I stand corrected, the syntax is correct and this would load an existing file. As others have mentioned above its a data issue

how to only allow one argument at a time

I am allowing the user to enter numbers via command line. I would like to make it so when the user enters more then one number on the command line at a time it displays a message asking for one number then press enter. then carries on.
here is my code. If someone could show me how to implement this I would appreciate it.
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
class programTwo
{
private static Double calculate_average( ArrayList<Double> myArr )
{
Double sum = 0.0;
for (Double number: myArr)
{
sum += number;
}
return sum/myArr.size(); // added return statement
}
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
String inputs = scan.nextLine();
while (!inputs.matches("[qQ]") )
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
try{
myArr.add(scan2.nextDouble());
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
catch (InputMismatchException e) {
System.out.println("Stop it swine! Numbers only! Now you have to start over...");
main(args);
return;
}
inputs = scan.nextLine();
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
}
As suggested in the comments to the question: Just do not scan the line you read for numbers, but parse it as a single number instead using Double.valueOf (I also beautified the rest of your code a little, see comments in there)
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
// we can use a for loop here to break on q and read the next line instead of that while you had here.
for (String inputs = scan.nextLine() ; !inputs.matches("[qQ]") ; inputs = scan.nextLine())
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
try{
myArr.add(Double.valueOf(inputs));
count++; //that'S even shorter than count += 1, and does the exact same thing.
System.out.println("Please enter another number or press Q for your average");
}
catch (NumberFormatException e) {
System.out.println("You entered more than one number, or not a valid number at all.");
continue; // Skipping the input and carrying on, instead of just starting over.
// If that's not what you want, just stay with what you had here
}
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
(Code untested, so there may be errors in there. Please notify me if you got one ;))
String[] numbers = inputs.split(" ");
if(numbers.length != 1){
System.out.println("Please enter only one number");
}

How to terminate Scanner when input is complete?

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!

Categories