Java: 2 runtime errors I can't figure out - java

I am working on a homework assignment, and I am going a little "above and beyond" what is called for by the assignment. I am getting a run-time error in my code, and can not for the life of me figure out what it is that I have done wrong.
Here is the assignment:
Write a program that displays a simulated paycheck. The program should ask the user to enter the date, the payee’s name, and the amount of the check. It should then display a simulated check with the dollar amount spelled out.
Here is my code:
CheckWriter:
/* CheckWriter.java */
// Imported Dependencies
import java.util.InputMismatchException;
import java.util.Scanner;
public class CheckWriter {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
// Try to get the name
String name = "";
NameValidator validateName = new NameValidator();
while (validateName.validate(name) == false) {
System.out.println("Enter the name: ");
name = keyboard.nextLine();
if (validateName.validate(name) == false) {
System.out.println("Not a valid name.");
}
}
// Get the date
String date = "";
DateValidator validateDate = new DateValidator();
while (!validateDate.validate(date)) {
System.out.println("Enter the date (dd/mm/yyyy): ");
date = keyboard.nextLine();
if (!validateDate.validate(date)) {
System.out.println("Not a valid date.");
}
}
// Try to get the amount of the check
String checkAmount = "";
CurrencyValidator validateCurrency = new CurrencyValidator();
while (!validateCurrency.validate(checkAmount)) {
System.out.print("Enter the Check Amount (XX.XX): $");
checkAmount = keyboard.nextLine();
if (!validateCurrency.validate(checkAmount)) {
System.out.println("Not a valid check amount.");
}
}
String checkWords = checkToWords(checkAmount); // ERROR! (48)
System.out
.println("------------------------------------------------------\n"
+ "Date: "
+ date
+ "\n"
+ "Pay to the Order of: "
+ name
+ " $"
+ checkAmount
+ "\n"
+ checkWords
+ "\n"
+ "------------------------------------------------------\n");
}
private static String checkToWords(String checkAmount) {
/**
* Here I will use the string.split() method to separate out
* the integer and decimal portions of the checkAmount.
*/
String delimiter = "\\.\\$";
/* Remove any commas from checkAmount */
checkAmount.replace(",", "");
/* Split the checkAmount string into an array */
String[] splitAmount = checkAmount.split(delimiter);
/* Convert the integer portion of checkAmount to words */
NumberToWords intToWord = new NumberToWords();
long intPortion = Long.parseLong(splitAmount[0]); // ERROR! (84)
intToWord.convert(intPortion);
String intAmount = intToWord.getString() + " dollars";
/* Convert the decimal portion of checkAmount to words */
String decAmount = "";
long decPortion = Long.parseLong(splitAmount[1]);
if (decPortion != 0) {
NumberToWords decToWord = new NumberToWords();
decToWord.convert(Long.parseLong(splitAmount[1]));
decAmount = " and " + decToWord.getString() + " cents.";
}
return (intAmount + decAmount);
}
}
Note that I am using external class files to handle validation of the name, date, currency, and conversion from numbers to words. These class files all work as intended.
The error I am getting is:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at CheckWriter.checkToWords(CheckWriter.java:82)
at CheckWriter.main(CheckWriter.java:46)
I have commented the lines in my code that are causing the errors that I am experiencing.
Could someone please assist me in figuring where my code is going wrong? I can include the other class files if you feel that it would be needed.
EDIT: When I run the code, it asks for the name and date. Before asking for the check amount is when it throws the error.
EDIT 2: A huge thank you to cotton.m! Thanks to his advice, I have changed the while statements to look like this:
while(!validateDate.validate(date) && date == "")
This has now fixed my issue. It would appear that when validating data with a regex expression, an empty string will return true.

The String you are trying to parse in an empty length string.
My suggestion would be to
1) Check the value of checkAmount at the start of checkToWords - if it is blank there's your problem
2) Don't do that split. Just replace the $ like you did the , (I think this is your real problem)
Also you are going to have another issue in that 10000.00 is not a long. I see you are splitting out the . but is that really what you want?

It is NumberFormatException, the value in checkAmount (method parameter) is not a valid Number.
You need to set checkAmount=checkAmount.replace(",", "");
Otherwise checkAmount will still have , inside and causes NumberFormatExcpetion.

Your issue is with your delimiter regex, currently you are using \.\$ which will split on a literal . followed by a literal $. I'm assuming that what you are actually intending to do is to split on either a . or a $, so change your delimiter to one of the following:
String delimiter = "\\.|\\$"
or
String delimiter = "[\\.\\$]"
As your code is now, checkAmount.split(delimiter) is not actually successfully splitting the string anywhere, so Long.parseLong(splitAmount[0]) is equivalent to Long.parseLong(checkAmount).

It should be:
String delimiter = "[\\.\\$]";
and then you have to check that splitWord[i] is not empty.

Related

What is wrong in my file reading with Scanner class?

Every time I run it, gives this message (( InputMismatchException )) where is the problem from ?
File f = new File("nameList.txt");
try {
PrintWriter out;
out = new PrintWriter(f);
for (int i = 0; i < 4; i++) {
out.printf("Name : %s Age : %d ", "Rezaee-Hadi", 19);
out.println("");
}
out.close();
} catch (IOException ex) {
System.out.println("Exception thrown : " + ex);
}
try {
Scanner in = new Scanner(f);
String name = in.nextLine();
int age = in.nextInt();
for (int i = 0; i < 4; i++) {
System.out.println(name);
System.out.println(age);
}
in.close();
} catch (FileNotFoundException ex) {
System.out.println("Exception thrown : " + ex);
}
You are creating your data file in the following data format:
Name : Rezaee-Hadi Age : 19
Now, it really doesn't matter (to some extent) how you format your data file as long as you realize that you may need to parse that data later on. You really don't need to maintain a header with your data on each file line. We already know that the first piece of data on any file line is to be a Name and the second piece of data on any file line is to be the Age of the person the Name relates to. So, the following is sufficient:
Rezaee-Hadi, 19
If you want, you can place a header as the very first line of the data file so that it can easily be determined what each piece of data on each line relates to, for example:
Name, Age
Rezaee-Hadi, 19
Fred Flintstone, 32
Tom Jones, 66
John Smith, 54
This is actually a typical format for CSV data files.
Keeping with the file data format you are already using:
There is nothing wrong with using the Scanner#nextLine() method. It's a good way to go but you should be iterating through the file line by line using a while loop because you may not always know exactly how many actual data lines are contained within the file, for example:
Scanner in = new Scanner(f);
String dataLine;
while (in.hasNextLine()) {
dataLine = in.nextLine().trim();
// Skip Blank Lines
if (dataLine.equals("")) {
continue;
}
System.out.println(dataLine);
}
This will print all the data lines contained within your file. But this is not what you really want is it. You want to separate the name and age from each line which means then that you need to parse the data from each line. One way (in your case) would be something like this:
String dataLine;
Scanner in = new Scanner(f);
while (in.hasNextLine()) {
dataLine = in.nextLine().trim();
// Skip Blank Lines
if (dataLine.equals("")) {
continue;
}
String[] dataParts = dataLine.replace("Name : " , "").split(" Age : ");
System.out.println("The Person's Name: " + dataParts[0] + System.lineSeparator()
+ "The Person's Age: " + dataParts[1] + System.lineSeparator());
}
In the above code we iterate through the entire data file one line at a time using a while loop. As each line is read into the dataLine string variable it is also trimmed of any leading or trailing whitespaces. Normally we don't want these. We then check to make sure the line is not blank. We don't normally want these either and here we skip past those blank lines by issuing a continue to the while loop so as to immediately initiate another iteration. If the file line line actually contains data then it is held within the dataLine variable.
Now we want to parse that data so as to retrieve the Name and the Age and place them into a String Array. We do this by using the String#split() method but first we get rid of the "Name : " portion of the line using the String#replace() method since we don't want to deal with this text while we parse the line. In the String#split() method we supply a string delimiter to split by and that delimiter is " Age : ".
String[] dataParts = dataLine.replace("Name : " , "").split(" Age : ");
Now when each line is parsed, the Name and Age will be contained within the dataParts[] string array as elements located at index 0 and index 1. We now use these array elements to display the results to console window.
At this point the Age is a string located in the dataParts[] array at index 1 but you may want to convert this age to a Integer (int) type value. To do this you can utilize the Integer.parseInt() or Integer.valueOf() methods but before you do that you should validate the fact the the string you are about to pass to either of these methods is indeed a string numerical integer value. To do this you would utilize the String#matches() method along with a simple little Regular Expression (RegEx):
int age = 0;
if (dataParts[1].matches("\\d+")) {
age = Integer.parseInt(dataParts[1]);
// OR age = Integer.valueOf(dataParts[1]);
System.out.println("Age = " + age);
}
else {
System.out.println("Age is not a numerical value!");
}
The regular expression "\\d+" placed within the String#matches() method basically means, "Is the supplied string a string representation of a integer numerical value?". If the method finds that it is not then boolean false is returned. If it finds that the value supplied is a string integer numerical value then boolean true is returned. Doing things this way will prevent any NumberFormatException's from occurring.
Replace this:
int age=0;
while (in.hasNext()) {
// if the next is a Int,
// print found and the Int
if (in.hasNextInt()) {
age = in.nextInt();
System.out.println("Found Int value :"
+ age);
}
}
in place of this:
int age = in.nextInt();
Then you will not get "InputMismatchException" anymore..

Error in reading a file in java

I've been trying to practice I/O file programming and I'm still at the basics. Writing into a file using the java was simple enough but reading to a file is beginning to give me a headache. Here's a simple program I tried to run(btw, I based the program from a book by Liang) .
import java.util.Scanner;
import java.io.File;
public class Reading {
private static Scanner n;
public static void main(String[] args) throws Exception
{
File files = new File("samples.txt");
n = new Scanner(files);
while(n.hasNext())
{
String firstName = n.next();
String mi = n.next();
String lastName = n.next();
int score = n.nextInt();
System.out.println(
firstName + " " + mi + " " + lastName + " " + score);
}
n.close();
}
}
Here's the 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.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at OOPFinals.Reading.main(Reading.java:17)
How do I make this program work?
Help!
The NoSuchElementException is thrown by Scanner.next() and means there are no more tokens to be found in the file.
The problem here is that your while() loop only guarantees that there is at least ONE token left to read from the file, however on each iteration of the loop you are reading in FIVE tokens.
What is happening in your code, you are trying to read from the Scanner although there's nothing left there to read.
What you should do - You need to check n.hasNext() before each call to n.next() or n.nextInt(), or just read the entire line (which seems exactly what you want):
while (n.hasNextLine()) {
String line = n.nextLine();
System.out.println(line);
}
Your code is working given that the right input file "samples.txt" is provided. For example, given the following input:
Richard Phillips Feynman 100
Paul Adrien Dirac 90
Everything works fine, however if you use the following:
Richard Feynman 100
Paul Adrien Dirac 90
then you obtain the NoSuchElementException. In the last example, I removed the middle name that your program is expecting. As such, we can conclude that you are expecting to read information in a file with no information left to read. I recommend something like the following:
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.File;
public class Reading {
private static Scanner n;
public static void main(String[] args) throws Exception
{
File files = new File("samples.txt");
n = new Scanner(files);
String data;
while(n.hasNextLine() && !(data = n.nextLine()).equals(""))
{
StringTokenizer st = new StringTokenizer(data);
if(st.countTokens() >= 4) {
String firstName = (String) st.nextElement();
String mi = (String) st.nextElement();
String lastName = (String) st.nextElement();
int score = Integer.parseInt( (String) st.nextElement());
System.out.println(
firstName + " " + mi + " " + lastName + " " + score);
} else {
System.err.println("This line is malformed!");
}
}
n.close();
}
}
In this program, you can have a sample file that has empty lines and it expects to read 4 tokens per line or else it prints an error message informing you that a line has malformed input.
Sometimes when you're reading a file you'll run into various characters. Some are letters, some are numbers, and some are integers. You need to check whether it's a letter, number, or an integer because the following line assumes you are passing an integer:
int score = n.nextInt();
It can be resolved by checking for integers:
int score = 0;
if(n.hasNextInt()) { score = n.nextInt(); }
When you're reading from the program, make sure to take Cathial's answer into consideration. By using hasNext(), you're only checking if there is one string, also known as a token. You should check if there are n strings available where n is the number of .next() functions in your loop.

I need help on the Java Scanner Code

So I need help on this code. This code is all in one so ignore the spaces but I need to write another scanner in the way bottom of the code and if I do add
String feeling = in.nextLine(); at the very end it does not work. I need a it so that I can write my feelings so that I can make jarvis answer but the string does not work and java ignores the string and goes right on to the next part. It starts from the middle.
Scanner in = new Scanner(System.in);
System.out.println("Type User Name:");
String userName = in.nextLine();
System.out.println("PASSWORD:");
int passcodeFromUser=in.nextInt();
int passcode = 2015;
if (passcodeFromUser == passcode) {
System.out.println("Welcome Mr." + userName + "!");
Random random = new Random(userName.hashCode());
System.out.println("Mr." + userName + ", You are now recognized and you are now able to command me.");
System.out.println("I was created by John Choi");
System.out.println("JARVIS stands for Just A Rather Very Intelligent System");
System.out.println("How are you today Mr." + userName + "?");
}
So if I add this code at the back it does not work. It ignores and says Oh. Mr is feeling.
String feeling = in.nextLine();
System.out.println("Oh. Mr." + userName + "is feeling" + feeling + ".")
That is because your nextInt invocation does not actually parse a line feed.
Quoting the API, Scanner#nextInt:
Scans the next token of the input as an int.
(focus on the token part here)
Here's one (but not the only) way to fix it:
Integer passcodeFromUser = null;
try {
passcodeFromUser= Integer.parseInt(in.nextLine());
}
catch (NumberFormatException nfe) {
// TODO handle non-numeric password
}
... instead of int passcodeFromUser=in.nextInt();.
You can also loop the parsing of the Integer so that you print an error message when catching the NumberFormatException and don't break the loop until you have a valid numeric passcode.
You can consume the \n character:
in.nextLine();
String feeling = in.nextLine();
So just putting in.nextLine() before the code you were going to add will easily fix your problem.

NoSuchElement Exception Error

I seem to be having some trouble getting my code to run properly here. What this is supposed to do is it is supposed to read from a text file and find the name, quantity, and price of an item on each line then format the results. The tricky bit here is that the items have names that consist of two words, so these strings have to be differentiated from the quantity integer and price double. While I was able to get this working, the problem that I am having is with a singe space that is at the very end of the text file, right after the last item's price. This is giving me a java.util.NoSuchElement Exception: null, and I cannot seem to move past it. Can someone help me to work out a solution? The error is on thename = thename + " " + in.next();
while (in.hasNextLine())
{
String thename = "";
while (!in.hasNextInt())
{
thename = thename + " " + in.next();
thename = thename.trim();
}
name = thename;
quantity = in.nextInt();
price = in.nextDouble();
}
You need to make sure the Name quantity price string is properly formatted. There might not be enough tokens in the string. To check that there are enough tokens for the name:
while (!in.hasNextInt())
{
thename = thename + " ";
if (!in.hasNext())
throw new SomeKindOfError();
thename += in.next();
thename = thename.trim();
}
You don't have to throw an error, but you should have some kind of code to handle this issue properly according to your needs.
The problem is in the logic of your inner while loop:
while (!in.hasNextInt()) {
thename = thename + " " + in.next();
}
In English, this says "while there's not an int available, read the next token". The test does nothing to help check if the next action will succeed.
You aren't checking if there is a next token there to read.
Consider changing your test to one that makes the action safe:
while (in.hasNext()) {
thename = thename + " " + in.next();
thename = thename.trim();
name = thename;
quantity = in.nextInt();
price = in.nextDouble();
}

Replacing a particular word in a scanned in string and concatenating using substring() in Java

I'm brand new to all of this so I am trying to write a simple bit of code that allows the user to type in text (saved as a string) and then have the code search for the position of a word, replace it and join the string back together. I.e.:
'I like foo for lunch'
foo is found at position 7
The new input is: I like Foo for lunch
Here is what I have thus far:
import java.util.Scanner;
public class FooExample
{
public static void main(String[] args)
{
/** Create a scanner to read the input from the keyboard */
Scanner sc = new Scanner (System.in);
System.out.println("Enter a line of text with foo: ");
String input = sc.nextLine();
System.out.println();
System.out.println("The string read is: " + input);
/** Use indexOf() to position of 'foo' */
int position = input.indexOf("foo");
System.out.println("Found \'foo\' at pos: " + position);
/** Replace 'foo' with 'Foo' and print the string */
input = input.substring(0, position) + "Foo";
System.out.println("The new sentence is: " + input);
The problem is occurring at the end -- where I am stumped on how to tack the rest of the sentence on to the concatenation:
input = input.substring(0, position) + "Foo";
I can get the word to be replaced but I am scratching my head over how to get the rest of the string attached on.
input = input.substring(0,position) + "Foo" + input.substring(position+3 , input.length());
or simply you can use replace method.
input = input.replace("foo", "Foo");
Slight update to what Achintya posted, to take into account you don't want to include "foo" again:
input = input.substring(0, position) + "Foo" + input.substring(position + 3 , input.length());
This may be overkill, but if you are looking for words in sentences, you could easily use StringTokenizer
StringTokenizer st = new StringTokenizer(input);
String output="";
String temp = "";
while (st.hasMoreElements()) {
temp = st.nextElement();
if(temp.equals("foo"))
output+=" "+"Foo";
else
output +=" "+temp;
}

Categories