Solved

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

Posted on 2012-03-14
9
222 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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

708 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

16 Experts available now in Live!

Get 1:1 Help Now