Avatar of jwhmack
jwhmack
 asked on

Ignores my first if statement in while but processes it next time through

Hi, in this program I need to have it setup so that if an incorrect student number is put in then it will give the message ""Your search failed to return any results" and then it will prompt again for the student number.  The second time I enter a number that doesn't return a result I get the message.  Another odd thing I just tried is that if I enter text instead of number I trigger the exception for number format and get the message "Please enter a proper Student Number" but if if I enter a number that doesn't return a result and get just a blank and then a prompt to enter another student number, I try to enter text and then I receive the message "Your search failed to return any results" and then if I enter text I want it to throw the exception.  Can anyone tell me what I am doing wrong here?  Thanks.

import java.io.*;
import java.util.*;

public class TestProgram
{
	public static void main(String args[])
	     {
	String[][] students;

	        try
	        {
			  BufferedReader in = new BufferedReader(new FileReader("students.txt"));
			  int x=0, y=0, row = 0;
			  row = Integer.parseInt(in.readLine());
			  String line;
			  students = new String[row][6];

			  while ((line = in.readLine()) != null)
			  {
			    String[] values = line.split("[\\s]+");
	            y=0;

	            for (String str : values)
		        {
	              students[x][y]=str;
	              y++;
		        }
	              x++;
			  }

	          in.close();

	         String stuNo;
	         Scanner s2 = new Scanner(System.in);
	         System.out.println("Enter Student Number for search (Enter 0 to quit): ");
	         stuNo = s2.next();



			 while ( Integer.parseInt(stuNo) != 0)
			 {
			  String result = "";
	          int rw = students.length;

	           for (int i=0; i<students.length; i++) {
	              for (int j=0; j<4; j++) {
	                 if (stuNo.equals(students[i][j])) {
	                      rw = i;
	                      //break;
	                 }
	             }
	          }
	           if (rw == students.length) {
	             result += "Your search failed to return any results";
	             System.out.println("\n" + "Enter Student Number for search (Enter 0 to quit): ");
	         	 stuNo = s2.next();
	          }
	          else {
	             for (int j=0; j<6; j++) {
	                 result += students[rw][j] + "    ";
	             }
	          }
	           System.out.println("\n" + result+" ");
	           System.out.println("\n" + "Enter Student Number for search (Enter 0 to quit): ");
	           stuNo = s2.next();
		      }
		     }

			  catch(NumberFormatException nfEx)
			  {
			  	System.out.println("Please enter a proper Student Number.");
			  }

	        catch( IOException ioException )
	        {
	          System.out.println("Problem reading students.txt");
	        }
	     }

}

Open in new window

Java

Avatar of undefined
Last Comment
for_yan

8/22/2022 - Mon
sammySeltzer

Hi,

I am not a java expert and certainly don't have your students.txt file but you can try checking for empty lines like this:

  while ((line = in.readLine()) != null)
  {
// Skip over empty lines.
   if (line.trim().length() == 0) {
 continue;
    }
...
...
ASKER CERTIFIED SOLUTION
for_yan

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
for_yan

This is the input for the above code:

5
111111  NAME  NAME  TITLE  00.0  0.00
111111  NAME  NAME  TITLE  00.0  0.00
111111  NAME  NAME  TITLE  00.0  0.00
111111  NAME  NAME  TITLE  00.0  0.00
111111  NAME  NAME  TITLE  00.0  0.00

Open in new window

jwhmack

ASKER
Here is a small example students.txt attached (you can ignore the 6 because it doesn't get fed into the array.

6
111222333  FIRST  LAST  Freshman  16.0  3.15
666554444  FIRST  LAST  Sophomore  16.0  3.25
777889999  FIRST  LAST  Junior  16.0  2.5
333221111  FIRST  LAST  Senior  8.0  3.75
444556666  FIRST LAST  Senior  16.0  3.125
999887777  FIRST LAST  Junior  16.0  3.8
students.txt
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
jwhmack

ASKER
for_yan, that does fix that problem, thank you but I don't get an exception if I enter I enter text instead of a number on the second search attempt.  For example, I enter 112 and I get
"rw:-1
Your search failed to return any results"
so I enter a second search criteria of:  test
and I get the message:
"Your search failed to return any results"
but I expect to see the exception message "Please enter a proper Student Number."
for_yan

I don't have time to rewriten the whole thing now biut you should have it this way

      boolean found = false;
                while(!found){
	         String stuNo;
	         Scanner s2 = new Scanner(System.in);
	         System.out.println("Enter Student Number for search (Enter 0 to quit): ");
	         stuNo = s2.next();
//now with try/catch check that it is a number and break if it is not

//then check if it is 0 and break if it is

// then do the searcgh

                    
                    
           
                    

// after the sercvha  ay

if not found write all error messages and say continue - it will go to the beginning of the loop
if it founsd

found = true;



and then end the while loop
}

Open in new window

jwhmack

ASKER
No, that's fine...it's the order...that's really all I needed to know and what I was thinking.  I appreaciate it.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
for_yan

try something like that.
Separately deal with non-numeric imput I didnt implement that part

import java.io.*;
import java.util.*;

public class TestProgram
{
	public static void main(String args[])
	     {
	String[][] students;

	        try
	        {
			  BufferedReader in = new BufferedReader(new FileReader("students.txt"));
			  int x=0, y=0, row = 0;
			  row = Integer.parseInt(in.readLine());
			  String line;
			  students = new String[row][6];

			  while ((line = in.readLine()) != null)
			  {
			    String[] values = line.split("[\\s]+");
	            y=0;

	            for (String str : values)
		        {
	              students[x][y]=str;
	              y++;
		        }
	              x++;
			  }

	          in.close();

                boolean found = false;
                while(!found){
	         String stuNo;
	         Scanner s2 = new Scanner(System.in);
	         System.out.println("Enter Student Number for search (Enter 0 to quit): ");
	         stuNo = s2.next();


            if( Integer.parseInt(stuNo) == 0)break;



			// while ( Integer.parseInt(stuNo) != 0)
			// {
			  String result = "";
	          int rw = -1;

	           for (int i=0; i<students.length; i++) {
	              for (int j=0; j<4; j++) {
	                 if (stuNo.equals(students[i][j])) {
	                      rw = i;
	                     break; //break;
	                 }
                      if(rw > 0)break;
	             }
                    if(rw > 0)break;
	          }

                 System.out.println("here: " + rw);
	           if (rw == -1) {
	             System.out.println( "Your search failed to return any results");
                   continue;
	           // System.out.println("\n" + "Enter Student Number for search (Enter 0 to quit): ");
	         //	stuNo = s2.next();
                  //  System.out.println("here1");
	          }
	          else {
	             for (int j=0; j<6; j++) {
	                 result += students[rw][j] + "    ";
	             }
	          }




                 System.out.println("result: " + result);
	           System.out.println("\n" + result+" ");
                    found = true;
	        //   System.out.println("\n" + "Enter Student Number for search (Enter 0 to quit): ");
	         //  stuNo = s2.next();
		      }
		     }

			  catch(NumberFormatException nfEx)
			  {
			  	System.out.println("Please enter a proper Student Number.");
			  }

	        catch( IOException ioException )
	        {
	          System.out.println("Problem reading students.txt");
	        }
	     }

}

Open in new window

for_yan

Yes, the order is indeed important, otherwise it bacme difficult to put a right logic ion there - whehn you need to have two time eneter answer, etc