JAVA while loop

Not able to fix

Page 1 of 1

12 Replies - 5325 Views - Last Post: 01 June 2008 - 10:37 AM Rate Topic: -----

#1 jakkels  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 21-May 08

JAVA while loop

Posted 30 May 2008 - 04:22 AM

I'm not able to check whether a number entered is between 1 and 120... it's not working - think the solution is something along the lines of the bit I have commented out but I've tried and not sure where everything goes....

Can someone make a suggestion please.
Let me know if the rest of the code is needed...

   public void DisplayFile()
   {
	  //line from input file
	  String InputLine = null;
	  String InputAge = null;
	  Integer IntAge = 0;
	  String InputName = null;
	  String InputAge2 = null;
	  Integer IntAge2 = 0;	  

	  BufferedReader UserInterface = null;
	  UserInterface = new BufferedReader( new InputStreamReader( System.in));
	  
	  try
	  {
		 //repeat the loop as long as there is a line of text from the input file
		 while ((InputLine = InputFile.readLine() )!=null ) 
		 {
		 
			//while (Flag 'set to true')
			//{
			//if (Age is less 0 than and more than 120
			//{
			//flag = false
			//}
			//}
			
			System.out.println( InputLine);
			System.out.print( "Input Age:" );
			
					
			   InputAge = UserInterface.readLine();
			   
			   IntAge = Integer.parseInt( InputAge );
			   
			   //Check that the age entered is between 0 and 120
			   if (( IntAge <= 120 ) && ( IntAge > 0 ))
			   {
				  OutputFile.write( InputLine );
				  OutputFile.newLine();		
				  
				  OutputFile.write( IntAge.toString() );
				  OutputFile.newLine();
			   }
			   
			   //Adding a new name using '0'
			   else if ( IntAge == 0 )
				   
			   {
				  System.out.println( "Enter a new name" );
				  InputName = UserInterface.readLine();
				  
				  //Giving the new name an age
				  do 
				  {			
				  System.out.println( "Enter an age" );
				  InputAge2 = UserInterface.readLine();
				  
				  //check that the age entered is 
				  } while (( IntAge2 <= 0 ) || ( IntAge2 > 120 ));
				  
				  OutputFile.write( InputName );
				  OutputFile.newLine();
				  
				  OutputFile.write( InputAge2.toString() );
				  OutputFile.newLine();
			   }
			   //Deleting a name using '-1'
			   else if ( IntAge < 0 )
			   {
			   System.out.println( InputLine + " deleted" );
			   }
			   
			   //}
		 }

Attached File  Doc1.doc (76K)
Number of downloads: 96

This post has been edited by jakkels: 30 May 2008 - 04:31 AM


Is This A Good Question/Topic? 0
  • +

Replies To: JAVA while loop

#2 cutegrrl  Icon User is offline

  • D.I.C Head

Reputation: 10
  • View blog
  • Posts: 77
  • Joined: 12-May 08

Re: JAVA while loop

Posted 30 May 2008 - 05:25 AM

You forgot to parse the String returned by the readLine() method as an Integer type.

Quote

//Giving the new name an age
do
{
System.out.println( "Enter an age" );
InputAge2 = UserInterface.readLine();
// Forgot this: IntAge2 = Integer.parseInt(InputAge2);
//check that the age entered is
} while (( IntAge2 <= 0 ) || ( IntAge2 > 120 ));


	BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
		int age = 0;

		do {			
			System.out.print("Enter an age: ");
			try{
				age = Integer.parseInt(kb.readLine().trim());
				if(age <= 0 || age > 120){
					System.out.println("\nAge must be greater than 0 and less than 120.\n");
				}
			}catch(IOException e){
				e.printStackTrace();
			}catch(NumberFormatException e){
				System.out.println("\nInvalid input. Please enter a valid number.\n");
			}
		}while(age <= 0 || age > 120);


This post has been edited by cutegrrl: 30 May 2008 - 06:40 AM

Was This Post Helpful? 0
  • +
  • -

#3 jakkels  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 21-May 08

Re: JAVA while loop

Posted 30 May 2008 - 11:00 AM

Though this was helpful - thanks very much... It sounds like a step in the right direction but now the code does not accept any number input and jumps out of the loop with my NumberFormatException e



View Postcutegrrl, on 30 May, 2008 - 05:25 AM, said:

You forgot to parse the String returned by the readLine() method as an Integer type.

Quote

//Giving the new name an age
do
{
System.out.println( "Enter an age" );
InputAge2 = UserInterface.readLine();
// Forgot this: IntAge2 = Integer.parseInt(InputAge2);
//check that the age entered is
} while (( IntAge2 <= 0 ) || ( IntAge2 > 120 ));


	BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
		int age = 0;

		do {			
			System.out.print("Enter an age: ");
			try{
				age = Integer.parseInt(kb.readLine().trim());
				if(age <= 0 || age > 120){
					System.out.println("\nAge must be greater than 0 and less than 120.\n");
				}
			}catch(IOException e){
				e.printStackTrace();
			}catch(NumberFormatException e){
				System.out.println("\nInvalid input. Please enter a valid number.\n");
			}
		}while(age <= 0 || age > 120);


Was This Post Helpful? 0
  • +
  • -

#4 herefishyfishy  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 7
  • View blog
  • Posts: 60
  • Joined: 01-May 08

Re: JAVA while loop

Posted 30 May 2008 - 06:33 PM

I think you need to uncomment the //Forgot this line.
Was This Post Helpful? 0
  • +
  • -

#5 cutegrrl  Icon User is offline

  • D.I.C Head

Reputation: 10
  • View blog
  • Posts: 77
  • Joined: 12-May 08

Re: JAVA while loop

Posted 30 May 2008 - 07:55 PM

The NumberFormatException should only be thrown if you input something that cannot be parsed as a number. For instance when you prompt the user for an age and you enter letters. If you do that it should catch the exception, and prompt the user again until a valid age is entered (defined as > 0 and and less than <= 120). Can you post your modified code?

This post has been edited by cutegrrl: 30 May 2008 - 08:00 PM

Was This Post Helpful? 0
  • +
  • -

#6 jakkels  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 21-May 08

Re: JAVA while loop

Posted 31 May 2008 - 03:31 AM

I will include all the code this time....scroll down to the DisplayFile method.
Thanks again for your help.


//CURRENT version 1.1 30 May 2008
//classes from the standard API that are used in the program
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.*;

//primary program class
public class UpdateFile
{
   //class variable for data input file
   BufferedReader InputFile = null;							
   BufferedWriter OutputFile = null;

   //required function to bootsrap the program
   public static final void main(String[] args)				
   {

	  //the program is an instance of this class	  
	  UpdateFile program = null;
		
	  //display program name	  
	  System.out.println();
	  System.out.println("JAVA Programming Project");
	  System.out.println();
	  System.out.println("File UPDATE Program"); 
	  System.out.println();
		
	  //create a new instance of this class
	  program = new UpdateFile();
		 
	  //1. try to open the input file
	  if ( program.OpenFile() )
	  {
	  //2. try to display the file contents
		 program.DisplayFile();
	  }
	  
	  //Display program closing message
	  System.out.println();
	  System.out.println("End of File Reading Program");
   }
   //opening in the input file
   public boolean OpenFile()
   {
	  //the command line user interface
	  BufferedReader UserInterface = null;
   
	  //input file name
	  String FileName = null;
	  String OutputfileName = null;
   
	  //use the standard input to create the command line user interface object
	  UserInterface = new BufferedReader( new InputStreamReader( System.in));
	  //UserInterface = new BufferedWriter( new InputStreamReader( System.in));
	try
	  {
		 while (true) 
		 {
			System.out.println("Please enter a file name: " );
	  
			//user types input file name
			FileName = UserInterface.readLine();
			//error checks
			if ( CheckFile(FileName) )
			
			{  
			   InputFile = new BufferedReader( new FileReader( FileName ) );
		 
			   System.out.println("Please enter the new filename: " );
		 
			   OutputfileName = UserInterface.readLine();
			   
			   if ( CheckFile(OutputfileName) )
				  {
					 //writing to the output file
					 OutputFile = new BufferedWriter( new FileWriter( OutputfileName) );
					 if (OutputFile != null)
						{
						   return true;
						}
				  }
			   {
			   //indicates success at opening an input file
			   return true;
			   }
			}
		 }
	  }
	  catch ( FileNotFoundException error )
	  {
	   //an error has occured while opening input file 
	   System.out.println("File does not exist, please try again.");
	  }
	  catch ( IOException error )
	  {
	  //an error has occured while reading file name input	  
	  }
	  //error has occured
	  return false;
   }
   
   //try to display the input content
   public void DisplayFile()
   {
	  //line from input file
	  String InputLine = null;
	  String InputAge = null;
	  Integer IntAge = 0;
	  String InputName = null;
	  String InputAge2 = null;
	  Integer IntAge2 = 0;	  

	  BufferedReader UserInterface = null;
	  UserInterface = new BufferedReader( new InputStreamReader( System.in));
	  
	  try
	  {
		 //repeat the loop as long as there is a line of text from the input file
		 while ((InputLine = InputFile.readLine() )!=null ) 
		 {
		 
			//while (Flag is true)
			//{
			//if (Age is less 0 than and more than 120
			//{
			//flag = false
			//}
			//}
			
			System.out.println( InputLine);
			System.out.print( "Input Age:" );
			
					
			   InputAge = UserInterface.readLine();
			   
			   IntAge = Integer.parseInt( InputAge );
			   IntAge2 = Integer.parseInt( InputAge2 );
			   
			   //Check that the age entered is between 0 and 120
			   if (( IntAge <= 120 ) && ( IntAge > 0 ))
			   {
				  OutputFile.write( InputLine );
				  OutputFile.newLine();		
				  
				  OutputFile.write( IntAge.toString() );
				  OutputFile.newLine();
			   }
			   
			   //Adding a new name using '0'
			   else if ( IntAge == 0 )
				   
			   {
				  System.out.println( "Enter a new name" );
				  InputName = UserInterface.readLine();
				  
				  //Giving the new name an age
				  do 
				  {			
				  System.out.println( "Enter an age" );
				  InputAge2 = UserInterface.readLine();
				  
				  
				  //check that the age entered is 
				  } while (( IntAge2 <= 0 ) || ( IntAge2 > 120 ));
				  
				  OutputFile.write( InputName );
				  OutputFile.newLine();
				  
				  OutputFile.write( InputAge2.toString() );
				  OutputFile.newLine();
			   }
			   //Deleting a name using '-1'
			   else if ( IntAge < 0 )
			   {
			   System.out.println( InputLine + " deleted" );
			   }
			   
			   //}
		 }
		 InputFile.close();
		 OutputFile.close();
		 System.out.println();
		 System.out.println("End of data file");
			
	  }		  
				
		 catch ( IOException error )
		 {
		 //an error has occured while reading line from input file
		 }
		 
		 catch ( NumberFormatException e )
		 {
		  System.out.println( "Please make sure you have entered a valid age" );
		 }
   }
   
   public static boolean CheckFile(String FileName)
   {
   if ((FileName.length() == 0) || (FileName.contains("*")))
	  {
	  System.out.println ("Please try again...");
	  return false;
	  }
   if (!FileName.contains(".txt"))
	  {
	  //check for file extension
	  System.out.println ("Please add (.txt) extension");
	  return false;
	  }
	  return true;
   }
}








View Postcutegrrl, on 30 May, 2008 - 07:55 PM, said:

The NumberFormatException should only be thrown if you input something that cannot be parsed as a number. For instance when you prompt the user for an age and you enter letters. If you do that it should catch the exception, and prompt the user again until a valid age is entered (defined as > 0 and and less than <= 120). Can you post your modified code?

Was This Post Helpful? 0
  • +
  • -

#7 cutegrrl  Icon User is offline

  • D.I.C Head

Reputation: 10
  • View blog
  • Posts: 77
  • Joined: 12-May 08

Re: JAVA while loop

Posted 31 May 2008 - 04:22 AM

You never set the value for IntAge2 to what the user reads in. Check the commented code below.
   //Adding a new name using '0'
			   else if ( IntAge == 0 )
				   
			   {
				  System.out.println( "Enter a new name" );
				  InputName = UserInterface.readLine();
				  
				  //Giving the new name an age
				  do 
				  {			
				  System.out.println( "Enter an age" );
				  InputAge2 = UserInterface.readLine();
				  
                                  // ADD THE LINE BELOW TO YOUR PROGRAM
                                  IntAge2 = Integer.parseInt(InputAge2);
				  
				  //check that the age entered is 
				  } while (( IntAge2 <= 0 ) || ( IntAge2 > 120 ));




I'm not sure if this is your intention, but you never handle the case where the IntAge is out of range. In the first set of conditional statements, you only check for input 1-120, 0 (above), and -1.

This post has been edited by cutegrrl: 31 May 2008 - 04:29 AM

Was This Post Helpful? 0
  • +
  • -

#8 jakkels  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 21-May 08

Re: JAVA while loop

Posted 31 May 2008 - 08:06 AM

This is great... it worked.

I still have plenty of work to do on this, and I'm slowly realising what goes where...

Thanks a great deal cutegrrl, you made my day.

View Postcutegrrl, on 31 May, 2008 - 04:22 AM, said:

You never set the value for IntAge2 to what the user reads in. Check the commented code below.
   //Adding a new name using '0'
			   else if ( IntAge == 0 )
				   
			   {
				  System.out.println( "Enter a new name" );
				  InputName = UserInterface.readLine();
				  
				  //Giving the new name an age
				  do 
				  {			
				  System.out.println( "Enter an age" );
				  InputAge2 = UserInterface.readLine();
				  
                                  // ADD THE LINE BELOW TO YOUR PROGRAM
                                  IntAge2 = Integer.parseInt(InputAge2);
				  
				  //check that the age entered is 
				  } while (( IntAge2 <= 0 ) || ( IntAge2 > 120 ));




I'm not sure if this is your intention, but you never handle the case where the IntAge is out of range. In the first set of conditional statements, you only check for input 1-120, 0 (above), and -1.

Was This Post Helpful? 0
  • +
  • -

#9 jakkels  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 21-May 08

Re: JAVA while loop

Posted 31 May 2008 - 08:14 AM

This was my original question.... I was trying to get the code that is commented out to work.

Is it on the right track?


View Postcutegrrl, on 31 May, 2008 - 04:22 AM, said:

You never set the value for IntAge2 to what the user reads in. Check the commented code below.
   //Adding a new name using '0'
			   else if ( IntAge == 0 )
				   
			   {
				  System.out.println( "Enter a new name" );
				  InputName = UserInterface.readLine();
				  
				  //Giving the new name an age
				  do 
				  {			
				  System.out.println( "Enter an age" );
				  InputAge2 = UserInterface.readLine();
				  
                                  // ADD THE LINE BELOW TO YOUR PROGRAM
                                  IntAge2 = Integer.parseInt(InputAge2);
				  
				  //check that the age entered is 
				  } while (( IntAge2 <= 0 ) || ( IntAge2 > 120 ));




I'm not sure if this is your intention, but you never handle the case where the IntAge is out of range. In the first set of conditional statements, you only check for input 1-120, 0 (above), and -1.

This post has been edited by jakkels: 31 May 2008 - 08:19 AM

Was This Post Helpful? 0
  • +
  • -

#10 jakkels  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 21-May 08

Re: JAVA while loop

Posted 01 June 2008 - 04:29 AM

Hi there,

Has anyone got a suggestion for me?

See second lot of code posted (Yesterday, 03:31 AM), and the original question.

Thanks,
Jackie

This post has been edited by jakkels: 01 June 2008 - 04:31 AM

Was This Post Helpful? 0
  • +
  • -

#11 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: JAVA while loop

Posted 01 June 2008 - 05:58 AM

			//while (Flag is true)
			//{
			//if (Age is less 0 than and more than 120
			//{
			//flag = false
			//}
			//}



This is an endless or useless loop

Assuming that Flag is defined as a boolean

while(Flag) {
   if(Age < 0 && Age > 120)
	  Flag = false;
}



If Flag is true you will enter the loop
if(Age >= 0 && Age <= 120) Flag will stay true forever
if not flag will be false
so easier to write

Flag = false;



What are you trying to do ?
Was This Post Helpful? 0
  • +
  • -

#12 jakkels  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 21-May 08

Re: JAVA while loop

Posted 01 June 2008 - 08:23 AM

I would like this bit of the code to check that the 'age' entered is between 1 and 120. If not I would like it to jump to the NumberFormatException e

Currently it is accepting numbers above 120 too.

...

	  try
	  {
		 //repeat the loop as long as there is a line of text from the input file
		 while ((InputLine = InputFile.readLine() )!=null )
		 {
			
			System.out.println( InputLine);
			System.out.print( "Input Age:" );
			
					
			   InputAge = UserInterface.readLine();
			  
			   IntAge = Integer.parseInt( InputAge );
			   IntAge2 = Integer.parseInt( InputAge2 );
			  
			   //Check that the age entered is between 0 and 120
			   if (( IntAge <= 120 ) && ( IntAge > 0 ))
			   {
				  OutputFile.write( InputLine );
				  OutputFile.newLine();		
				  
				  OutputFile.write( IntAge.toString() );
				  OutputFile.newLine();
			   }
			  
			   //Adding a new name using '0'
			   else if ( IntAge == 0 )
				  
			   {
				  System.out.println( "Enter a new name" );
				  InputName = UserInterface.readLine();
				  
				  //Giving the new name an age
				  do
				  {			
				  System.out.println( "Enter an age" );
				  InputAge2 = UserInterface.readLine();
				  
				  
				  //check that the age entered is
				  } while (( IntAge2 <= 0 ) || ( IntAge2 > 120 ));
				  
				  OutputFile.write( InputName );
				  OutputFile.newLine();
				  
				  OutputFile.write( InputAge2.toString() );
				  OutputFile.newLine();
			   }
			   //Deleting a name using '-1'
			   else if ( IntAge < 0 )
			   {
			   System.out.println( InputLine + " deleted" );
			   }
			  
		 }
		 InputFile.close();
		 OutputFile.close();
		 System.out.println();
		 System.out.println("End of data file");
			
	  }		  
				
		 catch ( IOException error )
		 {
		 //an error has occured while reading line from input file
		 }
		
		 catch ( NumberFormatException e )
		 {
		  System.out.println( "Please make sure you have entered a valid age" );
		 }
   }



Any help will be great.
Was This Post Helpful? 0
  • +
  • -

#13 cutegrrl  Icon User is offline

  • D.I.C Head

Reputation: 10
  • View blog
  • Posts: 77
  • Joined: 12-May 08

Re: JAVA while loop

Posted 01 June 2008 - 10:37 AM

The purpose of the try and catch statements is to handle exceptions. In other words, in the event that your program crashes, it will allow your program to recover.

For instance, when you prompt the user for an integer, the program attempts to parse the String returned by the readLine() method into an int value. If the String of characters has a decimal point or letters or some other invalid int format, then a NumberFormatException is thrown. If that happens, the flow of control transfers to the catch ( NumberFormatException e ) {...} block of code and proceeds.

So with that said, to perform that check you desire (to see whether the age entered falls within a range) you simply utilize conditional statements. See the code below.

import java.io.*;

public class UpdateFile {

	// Create a single shared BufferedReader for keyboard input
	static BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));

	static BufferedReader inputFile;                            
	static BufferedWriter outputFile;

	// Program execution starts here
	public static final void main(String[] args) throws IOException{    

		System.out.println();
		System.out.println("JAVA Programming Project");
		System.out.println();
		System.out.println("File UPDATE Program");
		System.out.println();

		// Open file
		if(openFile()){
			// Display file contents
			displayFile();
		}

		// Display program closing message
		System.out.println("\nEnd of File Reading Program");
	}

	/* Prompts user for input & output file. Returns true if successful, false otherwise. */
	public static boolean openFile(){

		try{
			// Loop until files are valid
			while(true){

				// Prompt user for file to be read
				System.out.print("Please enter a file name: " );
				String filename = kb.readLine().trim(); // read input and remove leading/trailing whitespace
				System.out.println();

				// Determine if filename is valid
				if(checkFilename(filename)){  

					try{
						inputFile = new BufferedReader(new FileReader(filename));
					}catch(FileNotFoundException e){
						System.out.println(filename + " could not be opened for reading. Check that it exists.");
						continue; // keeps continuity in loop without executing the statement written after the continue statement
					}

					// If file is valid and exists get new filename
					while(true){

						// Prompt user for new name of file
						System.out.print("Please enter the new filename: " );
						filename = kb.readLine().trim();

						// Determine of filename is valid
						if(checkFilename(filename)){
							try{
								outputFile = new BufferedWriter(new FileWriter(filename));
								return true; // everything is valid - return success
							}catch(IOException e){
								System.out.println("File " + filename + " cannot be created/opened.");
							}
						}
					}
				}
			}
		}catch(IOException e){
			System.out.println("\nI/O error encountered. Please enter valid input.");
		}

		return false; 
	}

	public static void displayFile() throws IOException{

		String currentLine;
		int age = 0;

		try{
			// Repeat the loop as long as there is a line of text from the input file
			while( (currentLine = inputFile.readLine()) != null){

				System.out.println(currentLine);

				// Prompt user for age until valid age is entered
				while(true){
					try{
						System.out.print("Input Age: ");
						age = Integer.parseInt(kb.readLine().trim());
						if(age < -1 || age > 120){
							System.out.println("Invalid age entered. Age must be between 1 and 120 (inclusive).");
							System.out.println("Age '0' to add a new name or '1' to delete.");
						}else{
							break; // valid age - break loop
						}
					}catch(NumberFormatException e){
						// An error occurred while trying to parse input String as integer
						System.out.println("Please make sure you have entered a valid age.");
					}
				}

				// Check that the age entered is between 1 and 120 (inclusive)
				if(age > 0 && age <= 120){
					// Write to file
					outputFile.write(currentLine);
					outputFile.newLine();        
					outputFile.write(age+"");
					outputFile.newLine();
				}
				// Adding new name using '0'
				else if(age == 0){

					// Prompt user for new name
					System.out.print("Enter a new name: ");
					String name = kb.readLine().trim();

					// Giving the new name an age
					do{    
						try{
							System.out.print("Enter an age: ");
							age = Integer.parseInt(kb.readLine().trim());
							if(age <= 0 || age > 120){
								System.out.println("Invalid age entered. Age must be between 1 and 120 (inclusive).");
							}
						}catch(NumberFormatException e){
							// An error occurred while trying to parse input String as integer
							System.out.println("Please make sure you have entered a valid age.");
						}
					}while(age <= 0 || age > 120 );

					// Write to file
					outputFile.write(name);
					outputFile.newLine();
					outputFile.write(age+"");
					outputFile.newLine();
				}
				// Deleting a name using '-1'
				else if(age == -1){
					System.out.println(currentLine + " deleted");
				}
			}

		}catch(IOException e){
			System.out.println("An error has occurred while reading line from input file.");
		}finally{
			inputFile.close();
			outputFile.flush();
			outputFile.close();
			System.out.println("\nEnd of data file");
		}

	}

	/* Determines if valid filename is entered. */
	public static boolean checkFilename(String filename){
		if (filename.length() == 0 || filename.contains("*")) {
			System.out.println("Please try again...");
			return false;
		}
		if (!filename.contains(".txt")) {
			System.out.println("Please add (.txt) extension");
			return false;
		}
		return true;
	}

} // end of class UpdateFile

This post has been edited by cutegrrl: 01 June 2008 - 10:40 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1