Results 1 to 17 of 17
- 02-11-2012, 10:32 PM #1
Member
- Join Date
- Feb 2012
- Posts
- 19
- Rep Power
- 0
problems with .next() .nextLine(); Loop
hi I am currently having problems with running my program properly. As it it this program works fine except that when user is promt to enter a company name it must not have a space because im using the .next(); but if i use the .nextLine() the question to enter company name will be skipped for the 2nd 3rd and 4th loops. Any help would be appreciated,
Mike
code down below
Java Code:import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.text.*; public class AutoInsurence { /** * Mike Haar * */ public static void main(String[] args) throws IOException { //Creating variables index for finding lowest Total Coverage //String highest set default for blue to be used later for lowest coverage company double index = 9999999.9; String highest = "Blue"; //Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); //Creates a new File called AutoInsurance.txt PrintWriter outputFile = new PrintWriter("AutoInsurance.txt"); //Has user Input data about rates of different insurence copmanies //Writes this data onto the file //The data that is entered is converted to a proper decimal format //Also calculates the total Coverage for each company and prints it to the file //Using .nextLine would skip asking the name again in the loop for (int i = 1; i <= 4; i++) { System.out.print("Enter the name of company (Please use _ for spaces) " + "number " + i + ": "); //if i use String companyName = keyboard.nextLine() it will skip the name on the 2nd loop //keyboard.next(); will not accept Spaces for name inputs String companyName = keyboard.next(); outputFile.println(companyName); System.out .print("Enter the rate for Bodily Injury Liability of company " + "number " + i + ": "); double rateBodily = keyboard.nextDouble(); DecimalFormat rateBodily1 = new DecimalFormat("#.##"); outputFile.println(rateBodily1.format(rateBodily)); System.out .print("Enter the rate for Property Damage Liability of company " + "number " + i + ": "); double rateProperty = keyboard.nextDouble(); DecimalFormat rateProperty1 = new DecimalFormat("#.##"); outputFile.println(rateProperty1.format(rateBodily)); System.out .print("Enter the rate for Uninsured Drivers Coverage of company " + "number " + i + ": "); double rateUninsured = keyboard.nextDouble(); DecimalFormat rateUninsured1 = new DecimalFormat("#.##"); outputFile.println(rateUninsured1.format(rateUninsured)); double totalCost = rateBodily + rateProperty + rateUninsured; DecimalFormat totalCost1 = new DecimalFormat("#.##"); outputFile.println(totalCost1.format(totalCost)); //Determines the lowest total Coverage and assigns the name of the company to a variable if(totalCost < index){ index = totalCost; highest = companyName; } } //Write the lowest total coverage to the file outputFile.println(highest); //Closes the File outputFile.close(); //Opens the file File myFile = new File("AutoInsurance.txt"); Scanner inputFiles = new Scanner(myFile); //This for loop will display the Four Companies... //Names, Annual Rates for: Bodily Injury Liability, Property Damage Liability, //Uninsured Drivers Coverage, as well as the total annual cost of Auto Insurance Coverage for (int i = 1; i <= 4; i++) { String name = inputFiles.next(); System.out.println("Company " + i +" " + name); Double bodily = inputFiles.nextDouble(); System.out.println("Rate for Bodily Injury Liablility " + bodily); Double property = inputFiles.nextDouble(); System.out.println("Rate for Property Damage Liablility " + property); Double uninsured = inputFiles.nextDouble(); System.out.println("Rate for Uninsured Drivers Coverage " + uninsured); Double total = inputFiles.nextDouble(); System.out.println("Total Annual Cost of Coverage " + total); } //Displays the name of the Company that has the Lowest Total Coverage String companyHighest = inputFiles.next(); System.out.println(companyHighest + " has the lowest Total Cost of Coverage"); //Closes the File inputFiles.close(); //Walla End of program } }
- 02-11-2012, 11:14 PM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,548
- Rep Power
- 11
Re: problems with .next() .nextLine(); Loop
Are the company names allowed to include spaces? If so, replace next() with nextLine() and deal with whatever problem arises next.
I'm not sure I understand this. There is a print() statement at the start of the loop which asks this question. How can it be "skipped"? Perhaps you could describe what *does* happen.Using .nextLine would skip asking the name again in the loop
In a similar vein (and assuming nothing is skipped!) a System.out.println() will let you see the value that companyName is given.
The little arrows surrounding companyName are because it may turn out that seeing any whitespace is important in order to understand what is happening.Java Code:for (int i = 1; i <= 4; i++) { System.out.print("Enter the name of company (Please use _ for spaces) " + "number " + i + ": "); String companyName = keyboard.next(); System.out.println("companyName is -->" + companyName + "<--"); outputFile.println(companyName);
- 02-11-2012, 11:22 PM #3
Member
- Join Date
- Feb 2012
- Posts
- 19
- Rep Power
- 0
Re: problems with .next() .nextLine(); Loop
Alright thanks for the quick reply. This is what I mean when it is being skipped. Ok I changed next() to nextLine() and this is what happens during running the program.
Enter the name of company number 1: Company One
companyName is-->Company One<---
Enter the rate for Bodily Injury Liability of company number 1: 1
Enter the rate for Property Damage Liability of company number 1: 1
Enter the rate for Uninsured Drivers Coverage of company number 1: 1
Enter the name of company number 2: companyName is--><---
Enter the rate for Bodily Injury Liability of company number 2:
Once I hit Enter for Unisured Driver Coverage, it prints out "Enter name of company" and "enter rate of Bodily"
- 02-11-2012, 11:45 PM #4
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,548
- Rep Power
- 11
Re: problems with .next() .nextLine(); Loop
OK - it seems that the company name question is being asked, but the keyboard Scanner is not waiting for a response. It is setting companyName to the empty String (presumably because it reads that empty String from the keyboard) and moving on.
Scanner gets its input from a "stream", in this case the stream of keystrokes (including newlines==<Enter>) from the keyboard. Using this class involves being aware not only of what will be read from the stream but, more subtly, where we end up in the stream after the value has been returned.
A method like 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". Note the bit in bold! The scanner will end up just before the newline at the end of the line which will not be read and removed from the stream.
This behaviour is fine if we later use nextDouble() again because "The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token." Ie that newline still in the stream will be skipped.
But nextLine()'s behaviour is different. It "Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line." In your case the scanner is positioned just before the newline, so it advances past that and returns what was skipped: ie it returns an empty string.
What you ought to do is advance past that newline after you have used nextDouble() so it won't be there and cause trouble for a subsequent nextLine(). You do this by calling nextLine() and throwing the result (an empty string) away - ie don't assign it to anything.
That's a long story (that really ought to be told in Oracle's Tutorial, or as a note in the API docs, but isn't). But it is worth trying to understand before using... the following that adds just a single line to your code:
Java Code:for (int i = 1; i <= 4; i++) { System.out.print("Enter the name of company (Please use _ for spaces) " + "number " + i + ": "); //if i use String companyName = keyboard.nextLine() it will skip the name on the 2nd loop //keyboard.next(); will not accept Spaces for name inputs String companyName = keyboard.nextLine(); //System.out.println("companyName is -->" + companyName + "<--"); outputFile.println(companyName); System.out .print("Enter the rate for Bodily Injury Liability of company " + "number " + i + ": "); double rateBodily = keyboard.nextDouble(); DecimalFormat rateBodily1 = new DecimalFormat("#.##"); outputFile.println(rateBodily1.format(rateBodily)); System.out .print("Enter the rate for Property Damage Liability of company " + "number " + i + ": "); double rateProperty = keyboard.nextDouble(); DecimalFormat rateProperty1 = new DecimalFormat("#.##"); outputFile.println(rateProperty1.format(rateBodily)); System.out .print("Enter the rate for Uninsured Drivers Coverage of company " + "number " + i + ": "); double rateUninsured = keyboard.nextDouble(); // // Add this line to position the scanner past the current line // keyboard.nextLine(); DecimalFormat rateUninsured1 = new DecimalFormat("#.##"); outputFile.println(rateUninsured1.format(rateUninsured)); double totalCost = rateBodily + rateProperty + rateUninsured; DecimalFormat totalCost1 = new DecimalFormat("#.##"); outputFile.println(totalCost1.format(totalCost)); //Determines the lowest total Coverage and assigns the name of the company to a variable if(totalCost < index){ index = totalCost; highest = companyName; }Last edited by pbrockway2; 02-11-2012 at 11:50 PM.
- 02-12-2012, 12:00 AM #5
Member
- Join Date
- Feb 2012
- Posts
- 19
- Rep Power
- 0
Re: problems with .next() .nextLine(); Loop
Wow thanks you so much. Had to re read your comments to understand why it was not working. Been experimenting with Scanner class, using a java book and hasn't gone that far in detail yet. Thanks you once again for your knowledgeable input!
- 02-12-2012, 12:23 AM #6
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,548
- Rep Power
- 11
Re: problems with .next() .nextLine(); Loop
You're welcome.
- 02-12-2012, 12:29 AM #7
Member
- Join Date
- Feb 2012
- Posts
- 19
- Rep Power
- 0
Re: problems with .next() .nextLine(); Loop
Arg so just when I thought I had a handle on this my output is not working. The I/O really is killing me due to the fact that Im really not familair with this: here is my code for the output, Error has something to do with spaces for inputs. Sorry for all the trouble trying to learn as much as possible. But once I fix something something else goes wrong.
[code]
for (int i = 1; i <= 4; i++) {
String name = inputFiles.next();
System.out.println("Company " + i +": " + name);
Double bodily = inputFiles.nextDouble();
System.out.println("Rate for Bodily Injury Liablility " + bodily);
Double property = inputFiles.nextDouble();
System.out.println("Rate for Property Damage Liablility "
+ property);
Double uninsured = inputFiles.nextDouble();
System.out.println("Rate for Uninsured Drivers Coverage "
+ uninsured);
Double total = inputFiles.nextDouble();
System.out.println("Total Annual Cost of Coverage " + total);
}
[\code]
- 02-12-2012, 12:43 AM #8
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,548
- Rep Power
- 11
Re: problems with .next() .nextLine(); Loop
It's a good idea when you have a runtime exception to post the stacktrace - and in this case the output you see as well.
The error occurs on line 83: "Double bodily = inputFiles.nextDouble();". And in fact we know it is the first time around the loop because we are dealing with Company 1.Java Code:... Enter the name of company (Please use _ for spaces) number 4: Company Four Enter the rate for Bodily Injury Liability of company number 4: 4 Enter the rate for Property Damage Liability of company number 4: 4 Enter the rate for Uninsured Drivers Coverage of company number 4: 4 Company 1 Company 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 AutoInsurence.main(AutoInsurence.java:83)
I think your guess that it has something to do with spaces in the company name is correct, as company 1 is reported as "Company" although I had entered "Company One" like your previous example.
Although this is output you are reading the file so it involves some input. The problem is exactly the same as the one you encountered when reading from the keyboard. Since the file may contain spaces in the company name you should read name with nextLine() rather than next().
-----
inputFiles is a Scanner just like keyboard was and will show all the same behaviour.
- 02-12-2012, 01:07 AM #9
Member
- Join Date
- Feb 2012
- Posts
- 19
- Rep Power
- 0
Re: problems with .next() .nextLine(); Loop
Sorry, so ive tried what you suggested and the loop runs fine the first time but the second time it will wont go through. . Ive been messing around but I still have not been able to figure it out. Sorry for all the trouble
Company 1: one one
Rate for Bodily Injury Liablility 1.0
Rate for Property Damage Liablility 1.0
Rate for Uninsured Drivers Coverage 1.0
Total Annual Cost of Coverage 3.0
Company 2:
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 AutoInsurence.main(AutoInsurence.java:81)
updated program
Java Code:import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.text.*; public class AutoInsurence { /** * Mike Haarmeyer * Mid Term Exam */ public static void main(String[] args) throws IOException { //Creating variables index for finding lowest Total Coverage //String highest set default for blue to be used later for lowest coverage company double index = 9999999.9; String highest = "Blue"; //Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); //Creates a new File called AutoInsurance.txt PrintWriter outputFile = new PrintWriter("AutoInsurance.txt"); //Has user Input data about rates of different insurence copmanies //Writes this data onto the file //The data that is entered is converted to a proper decimal format //Also calculates the total Coverage for each company and prints it to the file for (int i = 1; i <= 4; i++) { System.out.print("Enter the name of company " + "number " + i + ": "); String companyName = keyboard.nextLine(); outputFile.println(companyName); System.out .print("Enter the rate for Bodily Injury Liability of company " + "number " + i + ": "); double rateBodily = keyboard.nextDouble(); DecimalFormat rateBodily1 = new DecimalFormat("#.##"); outputFile.println(rateBodily1.format(rateBodily)); System.out .print("Enter the rate for Property Damage Liability of company " + "number " + i + ": "); double rateProperty = keyboard.nextDouble(); DecimalFormat rateProperty1 = new DecimalFormat("#.##"); outputFile.println(rateProperty1.format(rateBodily)); System.out .print("Enter the rate for Uninsured Drivers Coverage of company " + "number " + i + ": "); double rateUninsured = keyboard.nextDouble(); keyboard.nextLine(); DecimalFormat rateUninsured1 = new DecimalFormat("#.##"); outputFile.println(rateUninsured1.format(rateUninsured)); double totalCost = rateBodily + rateProperty + rateUninsured; DecimalFormat totalCost1 = new DecimalFormat("#.##"); outputFile.println(totalCost1.format(totalCost)); //Determines the lowest total Coverage and assigns the name of the company to a variable if(totalCost < index){ index = totalCost; highest = companyName; } } //Write the lowest total coverage to the file outputFile.println(highest); //Closes the File outputFile.close(); //Opens the file File myFile = new File("AutoInsurance.txt"); Scanner inputFiles = new Scanner(myFile); //This for loop will display the Four Companies... //Names, Annual Rates for: Bodily Injury Liability, Property Damage Liability, //Uninsured Drivers Coverage, as well as the total annual cost of Auto Insurance Coverage for (int i = 1; i <= 4; i++) { String name = inputFiles.nextLine(); System.out.println("Company " + i +": " + name); Double bodily = inputFiles.nextDouble(); System.out.println("Rate for Bodily Injury Liablility " + bodily); Double property = inputFiles.nextDouble(); System.out.println("Rate for Property Damage Liablility " + property); Double uninsured = inputFiles.nextDouble(); System.out.println("Rate for Uninsured Drivers Coverage " + uninsured); Double total = inputFiles.nextDouble(); System.out.println("Total Annual Cost of Coverage " + total); } //Displays the name of the Company that has the Lowest Total Coverage String companyHighest = inputFiles.next(); System.out.println(companyHighest + " has the lowest Total Cost of Coverage"); //Closes the File inputFiles.close(); //Walla End of program } }Last edited by zniightmare; 02-12-2012 at 01:21 AM.
- 02-12-2012, 01:35 AM #10
Member
- Join Date
- Feb 2012
- Posts
- 19
- Rep Power
- 0
Re: problems with .next() .nextLine(); Loop
tried adding inputFiles.nextLine(), like you did with the previous loop but just seems to run fine but messes up the numbers
- 02-12-2012, 01:39 AM #11
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,548
- Rep Power
- 11
Re: problems with .next() .nextLine(); Loop
Company two's name is missing in that output. Look familiar?
Remember that inputFiles is a Scanner like keyboard with all the same behaviour. So if you are going to use nextLine() to read a company's name after having previously used nextDouble() on the same stream, you had better call nextLine() and remove the newline character.
- 02-12-2012, 01:42 AM #12
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,548
- Rep Power
- 11
Re: problems with .next() .nextLine(); Loop
Our posts crossed. Using nextLine() is the right thing to do. Post the code (or at any rate the loop where you read the file) and the output so we can see what "messes up the numbers" means.
- 02-12-2012, 01:51 AM #13
Member
- Join Date
- Feb 2012
- Posts
- 19
- Rep Power
- 0
Re: problems with .next() .nextLine(); Loop
Sorry about crossed post. Not sure if i placed it correctly. From the looks of it, it seems to have removed word from the company name for lowest total coverage, and the Total cost per company seem to be fine. But the damage liability is posts: what the bodily liability is.
Enter the name of company number 1: one oneJava Code:for (int i = 1; i <= 4; i++) { String name = inputFiles.nextLine(); System.out.println("Company " + i +": " + name); Double bodily = inputFiles.nextDouble(); System.out.println("Rate for Bodily Injury Liablility " + bodily); Double property = inputFiles.nextDouble(); System.out.println("Rate for Property Damage Liablility " + property); Double uninsured = inputFiles.nextDouble(); System.out.println("Rate for Uninsured Drivers Coverage " + uninsured); Double total = inputFiles.nextDouble(); System.out.println("Total Annual Cost of Coverage " + total); inputFiles.nextLine(); }
Enter the rate for Bodily Injury Liability of company number 1: 1.1
Enter the rate for Property Damage Liability of company number 1: 1.2
Enter the rate for Uninsured Drivers Coverage of company number 1: 1.3
Enter the name of company number 2: two two
Enter the rate for Bodily Injury Liability of company number 2: 2.1
Enter the rate for Property Damage Liability of company number 2: 2.2
Enter the rate for Uninsured Drivers Coverage of company number 2: 2.3
Enter the name of company number 3: Th Th
Enter the rate for Bodily Injury Liability of company number 3: 3.1
Enter the rate for Property Damage Liability of company number 3: 3.2
Enter the rate for Uninsured Drivers Coverage of company number 3: 3.3
Enter the name of company number 4: Fo Fo
Enter the rate for Bodily Injury Liability of company number 4: 4.1
Enter the rate for Property Damage Liability of company number 4: 4.2
Enter the rate for Uninsured Drivers Coverage of company number 4: 4.3
Company 1: one one
Rate for Bodily Injury Liablility 1.1
Rate for Property Damage Liablility 1.1
Rate for Uninsured Drivers Coverage 1.3
Total Annual Cost of Coverage 3.6
Company 2: two two
Rate for Bodily Injury Liablility 2.1
Rate for Property Damage Liablility 2.1
Rate for Uninsured Drivers Coverage 2.3
Total Annual Cost of Coverage 6.6
Company 3: Th Th
Rate for Bodily Injury Liablility 3.1
Rate for Property Damage Liablility 3.1
Rate for Uninsured Drivers Coverage 3.3
Total Annual Cost of Coverage 9.6
Company 4: Fo Fo
Rate for Bodily Injury Liablility 4.1
Rate for Property Damage Liablility 4.1
Rate for Uninsured Drivers Coverage 4.3
Total Annual Cost of Coverage 12.6
one has the lowest Total Cost of Coverage
- 02-12-2012, 02:12 AM #14
Member
- Join Date
- Feb 2012
- Posts
- 19
- Rep Power
- 0
Re: problems with .next() .nextLine(); Loop
WOW got one part corrected just by looking at my code. Had wrong variable wrong. Now the only thing that is weird is that the name of the Lowest Total Coverage is only printing out the first word.
- 02-12-2012, 02:21 AM #15
Member
- Join Date
- Feb 2012
- Posts
- 19
- Rep Power
- 0
Re: problems with .next() .nextLine(); Loop
And yet again, had to check myself once again used next instead of nextLine(). ALright well things seems to be working perfectly. Thank you once again for all your patients. Sorry that I seem dumb in java I just get frustrated easily and don't pay attention to the little things. Now I def have a better advantage of using Scanner and input. Thanks again mate!
- 02-12-2012, 02:29 AM #16
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,548
- Rep Power
- 11
Re: problems with .next() .nextLine(); Loop
Not your fault. I only mentioned it because you had posted to say that you used .nextLine() and then I posted to suggest you try that. It would have looked weird to anyone reading the thread unless they realised that I hadn't seen your post before sending mine...Sorry about crossed post.
Excellent. (I was following your pattern and using 1/1/1 2/2/2 etc as the data, so I hadn't seen that. I wouldn't have mentioned it, though, even if I had seen it!)WOW got one part corrected just by looking at my code.
A couple of things. First check the data file to see if the full name of the lowest company is in there in full. (Because we've just seen that if the wrong value is put in there you will get the wrong value out again later.)Now the only thing that is weird is that the name of the Lowest Total Coverage is only printing out the first word.
Next, think about it. Only the first part of the company name is being read from the file. Now, have you ever seen behaviour like that before?
- 02-12-2012, 02:32 AM #17
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,548
- Rep Power
- 11
Similar Threads
-
Loop problems
By amzers in forum New To JavaReplies: 23Last Post: 08-16-2011, 07:18 PM -
Try catch loop problems :'(
By Romally in forum New To JavaReplies: 7Last Post: 11-17-2010, 08:15 PM -
Loop problems
By jim01 in forum New To JavaReplies: 3Last Post: 10-18-2010, 12:49 AM -
Newbie having problems with for loop
By Dannii in forum New To JavaReplies: 4Last Post: 04-13-2009, 11:52 PM -
Problems with while loop
By Albert in forum New To JavaReplies: 2Last Post: 07-04-2007, 07:19 AM


2Likes
LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks