problems in if else

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 827 Views - Last Post: 08 August 2011 - 07:13 PM Rate Topic: -----

#16 pbl  Icon User is offline

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

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

Re: problems in if else

Posted 08 August 2011 - 07:13 PM

Use a while loop until the condition, set before it become true

import java.util.Scanner;

public class Student {

	private String name;
	private char gender;
	
	// constructor
	Student(String name) {
		this.name = name;
	}
	
	void setGender(char gender) {
		this.gender = gender;
	}
	
	// to be used in System.out.print[ln]
	public String toString() {
		return "The gender of " + name + " is: " + gender;
	}
	
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		String name = "";
		while(name.length() == 0) {
			System.out.print("Please enter student name: ");
			name = scan.nextLine().trim();
			if(name.length() == 0)
				System.out.println("You entered an empty name !!!");
		}
		
		Student stu = new Student(name);
		boolean validGender = false;
		
		while(!validGender) {
			System.out.print("Enter " + name +"'s gender: ");
			String line = scan.nextLine().trim();
			if(line.length() == 0) {
				System.out.println("You enter an empty line for the gender !!!");
				continue;
			}
			char gender = line.charAt(0);
			gender = Character.toUpperCase(gender);   // make it upcase just to check F and M
			if(gender != 'F' && gender != 'M') {
				System.out.println("Sorry the only valid genders are F and M");
				continue;
			}
			// OK valid set the gender
			stu.setGender(gender);
			validGender = true;  // finish the while loop
		}
		
		System.out.println(stu);
	}
}


Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2