?
Solved

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

Posted on 2012-03-14
9
Medium Priority
?
233 Views
Last Modified: 2012-03-14
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

0
Comment
Question by:jwhmack
  • 5
  • 3
9 Comments
 
LVL 29

Expert Comment

by:sammySeltzer
ID: 37722230
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;
    }
...
...
0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 37722242
This will print more or less correctly:

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;

                 rw = -1;

	           for (int i=0; i<students.length; i++) {
	              for (int j=0; j<4; j++) {
	                 if (stuNo.equals(students[i][j])) {
                         System.out.println(students[i][j]);
	                      rw = i;
                         System.out.println("stuNo");
	                      break;
	                 }
                      if(rw > -1)break;
	             }
                  if(rw > -1)break; 
	          }
                 System.out.println("rw:" + rw);
                 
	           if (rw == -1) {
	             result += "Your search failed to return any results";
                   System.out.println("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


Output:

Enter Student Number for search (Enter 0 to quit): 
111111
111111
stuNo
rw:0

111111    NAME    NAME    TITLE    00.0    0.00     

Enter Student Number for search (Enter 0 to quit): 
2
rw:-1
Your search failed to return any results

Enter Student Number for search (Enter 0 to quit): 

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37722247
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

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:jwhmack
ID: 37722278
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
0
 

Author Comment

by:jwhmack
ID: 37722307
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."
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37722336
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

0
 

Author Comment

by:jwhmack
ID: 37722349
No, that's fine...it's the order...that's really all I needed to know and what I was thinking.  I appreaciate it.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37722355
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

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37722361
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
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month12 days, 21 hours left to enroll

578 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question