Java Please help! I was wondering how I can get the code to not repeat when the
ID: 3930097 • Letter: J
Question
Java Please help!
I was wondering how I can get the code to not repeat when the user puts something in other than m or f.
System.out.println("Are you Female or Male (F for female and M for male)");
String inputString = keyboard.next();
inputString = inputString.toUpperCase();
char gender = inputString.charAt(0);
//If Gender does not equal M and F it gets error
//Otherwise, if it does, it is set in object
//Increments info_counter
while(gender != 'M' || gender != 'F')
{
System.out.println("Please pick F or M");
System.out.println("Are you Female or Male (F for female and M for male)");
inputString = inputString.toUpperCase();
gender = inputString.charAt(0);
}
user.setUserGender(gender);
Second questions is how could I convert this code into a while so that repeat if the user puts the wrong information in
System.out.println("How fast were you going? (MPH)");
int speed = keyboard.nextInt();
if(speed <= 0 || speed > 30)
{
System.out.println("Remember how fast you were going... not your car");
}
else
{
user.setUserActivitySpeed(speed);
}
Explanation / Answer
public static void main(String[] args) {
//declare the variables
String gender; //the gender of the user
Scanner scanner = new Scanner(System.in); //text input scanner
System.out.println(" Are you male or female? (format: M or F)");
gender = scanner.next();
System.out.println(gender); //an output line for debugging
if (gender == "M") gender = "Male";
else gender = "Female";
System.out.println(" You said you are:");
System.out.println(gender);
import java.util.Scanner;
public class Distance{
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
int time , speed , hour;
double distance;
System.out.println("How fast were you going ?");
speed = keyboard.nextInt();
while(speed<=0)
{
System.out.println("Please enter a valid speed ");
speed = keyboard.nextInt();
}
System.out.println(" How long did you ride / drive ?");
time = keyboard.nextInt();
while(time<=0)
{
System.out.println("Please enter a valid time ");
time = keyboard.nextInt();
}
System.out.println(" Hour Distance");
System.out.println("---------------------------------");
hour = 0;
for( int x = 1; x<=time; x++)
{
hour++;
if(hour>1)
{
distance = time * speed;
System.out.println(time+ " " +distance);
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.