How to get the row index of a csv file in java - java

My program is to validate if the input code number is empty or not. The condition is if there is a code number entered(thru csv file) proceed and if code number is empty an error message show. "The code number is empty in line :__".
My problem is how can I suppose to print the index of a line on which the code number was empty.
Here's my sample data(csv):
CRITERIA CODE NAME AGE ADDRESS
ADD 0001 JOHN 21 USA
ADD MICH 16 EUR
ADD ALI 11 PHL
Error Message should be :
"The code number is empty in line 2."
"The code number is empty in line 3."
Here's my current program :
private static String[] sNextLine2;
public static Map<String,Employee> getChanges
( String sFileName, Map<String, Employee> mEmployeeList )
throws IOException {
//Read_File
setReader2(new CSVReader(new FileReader(sFileName)));
while ((sNextLine2 = reader2.readNext()) != null) {
switch(sNextLine2[0]) {
case "ADD":
if(sNextLine2[1].isEmpty()) {
System.out.println("The code number is empty in line" + lineNumber); //how to get that line number
} else if (mEmployeeList.containsKey(sNextLine2[1]))
{
System.out.println("Data already exist");
}
else
{
mEmployeeList.put(sNextLine2[1],new Employee(sNextLine2[1],
sNextLine2[2], sNextLine2[3], sNextLine2[4], sNextLine2[5],
sNextLine2[6], sNextLine2[7], sNextLine2[8]));
}
break;
}
I hope someone will help me on this. Thank you!

you can add a counter, which is incremented every .readNext() and let it print if there is an error
int counter=0;
while ((sNextLine2 = reader2.readNext()) != null) {
counter++;
switch(sNextLine2[0]) {
case "ADD":
if(sNextLine2[1].isEmpty()) {
System.out.println("The code number is empty in line" + counter); //how to get that line number
} else if (mEmployeeList.containsKey(sNextLine2[1]))
{
System.out.println("Data already exist");
}
else
{
mEmployeeList.put(sNextLine2[1],new Employee(sNextLine2[1],
sNextLine2[2], sNextLine2[3], sNextLine2[4], sNextLine2[5],
sNextLine2[6], sNextLine2[7], sNextLine2[8]));
}
break;
}

Related

String data still remains? (Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string)

I am trying out to code a simple arithmetic game in Java but I faced an error like: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string. This happens when I clicked on number buttons and cleared them to enter a new number but it seems that the string still contains the previous number I clicked. (For example, I clicked 5 and deleted it so I could enter 9 instead and now the string seems to register it as 59 instead of just 9.) I used .setText('') to clear the text area.
This is my code for when the buttons are pressed:
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("one"))
{
answerText.append("1");
userAnswer = userAnswer + "1";
}
// same code for two, three, four... to nine.
if(e.getActionCommand().equals("enter"))
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
}
The answer variable and delete button is :
answerText = new JTextArea();
answerText.setEditable(false);
clearbtn = new JButton("Clear");
clearbtn.setActionCommand("clear");
clearAnswer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
answerText.setText("");
}
});
How do I make sure that my answerText is completely clear?
Your error message:
java.lang.NumberFormatException: For input string
This means that you are trying to parse a string into a number, but the string contains something that cannot be parsed into a number. Java prints the content of the string after the text For input string. In this case there's nothing after that text, because the string that you are trying to parse is the empty string - that you set in the text box by calling answerText.setText("");
Solution: Check if the string you are trying to parse is empty before you try to parse it into a number. For example:
if (e.getActionCommand().equals("enter"))
{
if (!"".equals(userAnswer)) // Check if userAnswer is not empty
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a number before pressing Enter.");
}
}
The variable userAnswer doesn't get cleared when answerText is cleared. This might cause issues.
The exception you are having is probably being cause because int userValue = new Integer(userAnswer); is called at a point where userAnswer is empty (because it can't make a number out of nothing).

java8 - Optional- How to use it correctly?

The cityStr is a String, and it would be a null or "". I want to turn it to a int and if it's greater than 0, then I will print "the city is exist".
if (StringUtils.isNotBlank(cityStr)) {
if (Integer.parseInt(cityStr) > 0) {
System.out.println("the city is exist");
}
}
I want to used the below code to replace the above code, but I got a exception. How can I use it correctly? Thanks so much for your answer.
if (Optional.ofNullable(cityStr)
.map(Integer::parseInt)
.filter(city -> city > 0)
.isPresent()) {
System.out.println("the city is exist");
}
And the below is the exception information:
Exception in thread "main" 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)
at java.util.Optional.map(Optional.java:215)
You are trying to parse a number from an empty String. That throws the exception. It has nothing to do with Optional.
Maybe you thought that an empty string would be 'nullish' - like an empty String being falsy in javascript.
To get rid of the exception, assign null or a number to cityStr.
You could write it as :
String cityStr = null;
if (Optional.ofNullable(cityStr)
.map(Integer::parseInt)
.filter(city -> city > 0)
.isPresent()) {
System.out.println("the city is exist");
}
If you are expecting non numeric string you've to handle that yourself in the map method.
As suggested by #fastcodejava I made minor changes to the program, please take a look below:
public static void main(String[] args) throws NoSuchAlgorithmException {
String cityStr = "1";
Optional<String> cityOptional = Optional.ofNullable(cityStr)
.map(MainClass::parseInt)
.filter(integer -> integer > 0)
.map(integer -> "city exists");
String cityString = cityOptional.orElse("city does not exists");
System.out.println(cityString);
}
public static int parseInt(String str) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
// Eating e for unknown reason
return -1;
}
}
Where MainClass is the class for main method MainClass.java

Eclipse Syntax error on token "}", delete this token and Syntax error, insert "}" to complete ClassBody

I am trying to make a practice program for a bookstore clerk that allows the clerk to add, remove, edit, and search for books in its database. I have all but made the entire program however I am getting stuck on 2 errors. It is a total of 234 lines of code in all so I will try to shorten it to the relevant parts to make it easier on those willing to help me. I am using Eclipse with JDE and JDK 10. The Eclipse project was initiated using the JavaSE-10 execution environment as far as I am aware. Below are the 2 methods causing the errors.
public class Bookstore {
public static void main(String[] args) {
try(
//Creating table connection and statement
Connection conn = DriverManager.getConnection("***********",
"****", "*********"); //Please note that I blocked out the actual connection information here
Statement stmt = conn.createStatement();
){
Scanner input = new Scanner(System.in);
int selection = 0;
//Menu for action selection and user input
while(selection != 5) {
System.out.println("Please enter the number corresponding to the action you would like to take:\n"
+ "1. Enter book\n"
+ "2. Update book\n"
+ "3. Delete book\n"
+ "4. Search books\n"
+ "5. Exit");
selection = input.nextInt();
//Selection sorting
if(selection == 1) {
//Collecting book information
System.out.println("Please enter the Title of the book you would like to put into the system: ");
String title = input.next();
System.out.println("Please enter the Author of said book: ");
String author = input.next();
System.out.println("Please enter the number of said book currently in stock: ");
int qty = input.nextInt();
//Sending info to the addBook method
addBook(title, author, qty, stmt);
} else if(selection == 2) {
//Collecting book information
System.out.println("Please enter the id of the book you would like to update: ");
int id = input.nextInt();
//Sending info to the updateBook method
updateBook(id, stmt);
} else if(selection == 3) {
//Collecting book information
System.out.print("Please enter the id of the book you would like to delete from the system: ");
int id = input.nextInt();
//Sending info to deleteBook method
deleteBook(id, stmt);
} else if(selection == 4) {
searchStore(stmt);
} else if(selection == 5) {
System.out.println("Goodbye");
input.close();
} else { //Invalid entry handler
System.out.println("Sorry, that isn't a valid selection.");
}
}
} catch(SQLException ex) {
ex.printStackTrace();
}
}
} //This is the line giving me the error "Syntax error on token "}", delete this token"
Now I have already done some research regarding the error at the bottom of this block of code. As far as I can tell I am not missing any brackets and there are no variables or anything being created outside of a class that would cause this error. The only other solution I have been able to find is that "Eclipse is just being weird".
My second error comes from this block of code:
public static void resultSetPrinter(ResultSet rset) {
while(rset.next()) {
String title = rset.getString("Title");
String author = rset.getString("Author");
int qty = rset.getInt("qty");
System.out.println("Title: " + title + "\nAuthor: " + author + "\nNumber in stock: " + qty + "\n\n");
}
if(rset == null) {
System.out.println("No records for the entry could be found.");
}
} //This is the line giving me the "Syntax error, insert "}" to complete ClassBody" error
I have also done some research regarding the error at the bottom of this block and when I do remove the bracket as requested the error just jumps up to the method before this one. I haven't included the other 4 methods in the class to try and reduce the headache of running through all this code since they aren't giving me errors. Any help would be greatly appreciated at this point, I am completely stumped.
Thanks mainly to Elliott Frisch I have found my answer. Essentially I needed to put all my methods into my main class by the name of Bookstore. I moved the } to the end of my program and added try catch statements for each method. For example I changed the last code block I put in my question to:
public static void resultSetPrinter(ResultSet rset) {
try {
if(rset.next()) {
while(rset.next()) {
String title = rset.getString("Title");
String author = rset.getString("Author");
int qty = rset.getInt("Qty");
System.out.println("Title: " + title + "\nAuthor: " + author + "\nNumber in stock: " + qty + "\n");
}
} else {
System.out.println("No records for the entry could be found.\n");
}
} catch(SQLException ex) {
ex.printStackTrace();
}
}
You'll also note that I added an if else statement to check if the ResultSet rset was empty, if it wasn't I proceeded as normal and if it was I printed a simple message to let the user know nothing was found.
Thank you both Elliott Frisch and Marco13 for the asssistance.

Java How to dispaly no data found when the user input no reach the condition

If the user key in 4 I wish to pop up a message to inform the user that is no data found for user id "4" in the array list.
But when the user key in 4 there is 3 no data found appear.
User usr1 = new User(1,"Ken", 55.5, 26, Arrays.asList("0140392812", "0123456789"));
User usr2 = new User(2, "Mark", 54.7, 33, Arrays.asList("0129876543"));
User usr3 = new User(3, "Ong", 62.3, 34, Arrays.asList("06123456", "0987654322", "01798654321"));
ArrayList<User> ulist = new ArrayList<User>();
ulist.add(usr1);
ulist.add(usr2);
ulist.add(usr3);
String answer ="";
do{
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter user ID");
int userid = scan.nextInt();
for(User uid: ulist){
if(userid == uid.getUID()){
System.out.println(uid.getUID() +", " + uid.getName() +", " + uid.getAge() +" years old, " + uid.getWeight() +"kg");
}else{
System.out.println("no data found");
}
}
System.out.println("Continue(Y/N)");
answer = scan.next();
}while(answer.equalsIgnoreCase("y"));
current result:
no data found
no data found
no data found
Result that i wish:
no data found
Remove else { System.out.println("no data found"); } from the loop and put it outside. The for loop intent is to find, to lookup the correct user.
Once found you may use it: you have to declare a variable of type User before loop, initialized to null and if it's null after lookup, you have to print the message 'not found'.
You get no data found 3 times because you print it in the cycle: for every user in the list, if his id doesn't match specified id, System.out.println("no data found"); You can avoid this modifying your cycle or writing a method that fidns user by id.
User found;
for (User uid : ulist) {
if (userid == uid.getUID()) {
found = uid;
break; // assuming that ids are unique
}
}
if (found != null) {
System.out.println(found.getUID() +", " + found.getName() +", " + found.getAge() +" years old, " + found.getWeight() +"kg");
} else {
System.out.println("no data found");
}
You have problem in your logic.
in your for loop you should have a break statement, in case there is no data found.
else {
System.out.println("no data found");
break;
}

Why won't this method call work?

I'm creating a method to take an input by a user and validate it to make sure it's correct. If it's correct it will call a method and input the user input in to it. But for some reason, the method call is not working. It doesn't produce any errors, it just simply doesn't do it. I placed a print statement at the end of the code to make sure it actually reaches there and it does, but for some reason it's just not calling the method like it's supposed to. The other method works fine if I call it by itself and input a string via the parameters.
The code is:
public void getGetScheduledShowByFilmInput()////new - omar////
{
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
String filmInput;
filmInput = "";
boolean foundFilm;
foundFilm = false;
System.out.println("Here is a list of films that are currently showing:");
for(Film film : films){
System.out.println(film.getFilmName());
}
System.out.println("");
System.out.println("Please type the film name that you wish to view the corresponding shows for and press enter.");
System.out.println("Type 'exit' and press enter to exit this process.");
while(foundFilm == false){
try{
filmInput = reader.readLine();
}
catch (IOException e){
System.out.println("Error");
}
//If user enters "exit" then return.
if(filmInput.equals("exit")){
return;
}
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName() == filmInput){
foundFilm = true;
break;
}
}
if(foundFilm = true){
System.out.println("Film found.");
}
else{
System.out.println("The film name you entered has not been recognised. Please try again.");
}
}
//Call the function and input the film name input by the user.
getScheduledShowsByFilm(filmInput); ////This is the code that seems to be the problem.
System.out.println("reached bottom");
}
and the second method is:
public void getScheduledShowsByFilm(String inputFilmName)
{
ArrayList<Show> scheduledShows;
scheduledShows = new ArrayList<Show>();
for(Film film : films){
if(inputFilmName == film.getFilmName()){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}
for(Show show : scheduledShows){
System.out.println("**********************************");
show.getShowDetails();
System.out.println("**********************************");
}
}
The second method works perfectly when I call it on its own and enter parameters manually though.
It's probably something extremely simple that I'm not understanding! haha, thank you for your help :)
foundFilm can never be false because you always assign true to it:
if(foundFilm = true){
System.out.println("Film found.");
}
try changing it to this:
if(foundFilm)
{
System.out.println("Film found.");
}
In getGetScheduledShowByFilmInput() and getScheduledShowsByFilm(String) avoid doing string comparison using the equality operator (==). The == operator tests for object equality, but you want to test whether two strings contain the same sequence of characters. Therefore, use equals instead:
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName().equals(filmInput)){
foundFilm = true;
break;
}
}
and
for(Film film : films){
if(inputFilmName.equals(film.getFilmName())){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}

Categories

Resources