Solved

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

Posted on 2012-03-14
9
223 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 28

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 500 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
 

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
java  and programming certification ? 4 86
print map entry 34 56
servlet requestdispatcher include and forward differences 1 25
object oriented programming comparison 5 57
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

864 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now