NoSuchElement Exception Error - java

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();
}

Related

Java - Extracting Substrings Programmatically

I am trying to create a code that accepts a user's full name and returns first and last names and initials. Since a user's name length varies, I did not want to use hard coding, so I extract names and initials programmatically.
However when I run it and enter a name, I get the following error message:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
I looked into my code carefully and cannot see where exactly I miscalculated on the index range. I tried to find similar questions here, but though I did see similar problems, they have to do with C++ or Perl, not Java.
package nameSubstring;
import java.util.Scanner;
public class NameSubstring {
public static void main(String[] args) {
/*
* This is a program that accepts a user’s full name as a string (e.g. Margaret Thatcher) and displays to the user his/her first name, last name and initials in the following format:
Your first name is Margaret and your last name is Thatcher and your initials are MT.
*/
System.out.println("This program will take your full name and display your first name, last name, and initials.");
Scanner scanner = new Scanner(System.in);
String firstName, lastName, firstNameInitial, lastNameInitial;
System.out.println("Please enter your full name, e.g. Jane Smith:");
String fullName = scanner.next();
int nameSpace = fullName.indexOf(' ');
firstName = fullName.substring(0, nameSpace);
lastName = fullName.substring(nameSpace)+1;
firstNameInitial = firstName.substring(0, 1);
lastNameInitial = lastName.substring(0, 1);
System.out.println("Your first name is " + firstName + ", " + "your last name is " + lastName + ", " + "and your initials are " + firstNameInitial + lastNameInitial + ".");
}
}
Instead of next() use nextLine():
String fullName = scanner.nextLine();
and correct the error with the +1 which must be inside the parenthesis:
lastName = fullName.substring(nameSpace+1);

Java how to pass and return string, method?

import java.util.Scanner;
import javax.swing.JOptionPane;
public class StarWars {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String firstName = "";
String lastName = "";
String maidenName = "";
String town = "";
System.out.print("What is your first name? ");
firstName = reader.nextLine();
System.out.print("What is your last name? ");
lastName = reader.nextLine();
System.out.print("What is your mothers maiden name? ");
maidenName = reader.nextLine();
System.out.print("What town were you born? ");
town = reader.nextLine();
String Sfirstname = firstName.substring(0,2);
String Slastname = lastName.substring(0,3);
String SmaidenName = maidenName.substring(0,2);
String Stown = town.substring(0,3);
String Star = Sfirstname + Slastname;
String War = SmaidenName + Stown;
String StarWar = Star + War;
System.out.print("Your Star Wars name is: " + StarWar);
}
public static String StarWar (String Star, String War) {
String name;
name = Star + " " + War;
return War;
}
}
So this is my code about my project. While I'm doing my project I have some problem about the returning method and passing method.
I set up the main method perfectly to print out thing that what I want to see.
The problem is I also have to use passing method and returning method. My teacher want me to do two things with passing/returning method.
Pass all this data to your method, and the method should generate and return the users Star Wars name.
Get the return value of the method, and display it to the screen.
I have no idea what should I do with this problems (took 5 hrs to do everything I learn but wrong..).
Can someone give a hint or teach me what actually my teacher want me to do and How I can do this?
I really need help from you guys.
Additional, if I run a program it should be like this.
first name? user input: Alice last name? user input:Smith mothers maiden name? user input: Mata town were you born? user input: Sacramento
Your Star Wars name is: SmiAl MaSac
There are a few things we can improve here, lets start with the method - the method name looks like a constructor and doesn't perform the logic itself, lets describe what it does and move the logic into the method - we don't need all of those temporary variables (we can use a StringBuilder) like
public static String buildStarWarsName(String firstName, String lastName,
String maidenName, String town)
{
return new StringBuilder(lastName.substring(0, 3)) //
.append(firstName.substring(0, 2)) //
.append(" ") // <-- for the space between first and last
.append(maidenName.substring(0, 2)) //
.append(town.substring(0, 3)) //
.toString();
}
Then you can initialize your variables when you read them and finally call the method
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("What is your first name? ");
String firstName = reader.nextLine();
System.out.print("What is your last name? ");
String lastName = reader.nextLine();
System.out.print("What is your mothers maiden name? ");
String maidenName = reader.nextLine();
System.out.print("What town were you born? ");
String town = reader.nextLine();
System.out.print("Your Star Wars name is: " + //
buildStarWarsName(firstName, lastName, maidenName, town));
}
You should return what you evaluated instead :
return name;
and then call this defined method while you want to read the value.
The changes highlighted in the comments as well:
String StarWar = Star + War; // this would not be required, as handled by your method 'starWarName'
System.out.print("Your Star Wars name is: " + starWarName()); // calling the method defined
}
public static String starWarName (String Star, String War) { //renamed method to break the similarity with other variables
String name;
name = Star + " " + War;
return name; //returning the complete star war name
}
Your method is returning the 'war' parameter. Based on what your trying to do it looks like it should be returning 'name'. That's what the method built.

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.

Make an email list, by entering only recipient names

I want to make a simple code, that prompts you to enter names, separated by comma or just a space, and when you click enter, to take every one word you entered, and put a #gmail.com at the end of it, how can I do it?
That's what I have for now
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
String names;
System.out.println("Enter names: ");
names = input.next();
System.out.println(names + mail);
This should be everything you asked for, if you put a list of names separated by commas it will loop through them, otherwise it will just print a single name.
Scanner input = new Scanner(System.in);
String mail = "#gmail.com";
System.out.println("Enter names: ");
String names = input.next();
if(names.contains(",")) {
for(String name : names.split(",")) {
System.out.println(name + mail);
}
} else {
System.out.println(names + mail);
}
Hope that helps.
Not knowing what language this is, here's the pseudo-code:
names = input.next();
namesArray = names.split(" ") -- replace with your preferred delimiter
foreach name in namesArray
print name + mail

Java: 2 runtime errors I can't figure out

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.

Categories