Why cant I input info after if statement? No errors show - java

How can I get the program to ask for input using the scanner after the if statement?
import java.util.Scanner;
public class App1 {
public static void main(String[] Args) {
Scanner keyboard = new Scanner(System.in);
String gender;
String fName;
String lName;
int age;
String female = "F";
String male = "M";
String a = "";
String gettingMarried = "y";
String notGettingMarried = "n";
System.out.println("What is your gender (M or F)");
gender = keyboard.nextLine();
System.out.println("What is your first name?");
fName = keyboard.nextLine();
System.out.println("What is your last name?");
lName = keyboard.nextLine();
System.out.println("Age:");
age = keyboard.nextInt();
System.out.println();
if (gender.equals(female) && age >= 20) {
System.out.println("Are you married " + fName + " (y or n?)");
a = keyboard.nextLine();
} else if (gender.equals(male) && age >= 20) {
System.out.println("Are you married" + fName + "(y or n?)");
a = keyboard.nextLine();
}
}
}

It is because you use a nextInt() that only takes the int value and not the full line. When you try again to read with keyboard.nextLine() what you are catching it's the rest of the sentence of the line in which you put the int.
Change the System.out.println(); before your if statement to keyboard.nextLine();
Edit: If you want a more extended explanation about why you have to put keyboard.nextLine(); after your keyboard.nextInt() you can consult my answer in another question with the same problem: Why isn't the scanner input working?
I expect it will be helpful for you!

Related

I am trying to find a space in the string entered by the user but when I use indexof(" ") it returns -1 for the value, how do I fix this?

System.out.println("Please enter your first and last names separated by a space: ");
try (Scanner scan = new Scanner(System.in)) {
String s1 = scan.next();
int space = s1.indexOf(" ");
String First_Name = s1.substring(0,space);
String init1 = First_Name.substring(0,1);
String Last_Name = s1.substring(space+1,s1.length());
String init2 = Last_Name.substring(0,1);
int First_N = First_Name.length();
int Last_N = Last_Name.length();
System.out.println("You entered the name "+s1+".");
System.out.println("Your first name "+First_Name+": has "+First_N+" characters.");
System.out.println("Your last name "+Last_Name+": has "+Last_N+" characters.");
System.out.println("Your initials are "+init1+init2+".");
You should use
String s1 = scan.nextLine();
instead of
String s1 = scan.next();

Why cant java find symbol even though string is defined?

import java.util.Scanner;
public class DJNameCreator {
public static void main(String[] args){
//Variables to store inputted names
String firstName;
String lastName;
//Scanner for user inputted names
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter your first name: ");
firstName = keyboard.nextLine();
System.out.println("Nice to meet you, "+firstName+"!");
System.out.println("Please enter your last name: ");
lastName = keyboard.nextLine();
//Use substring and length method to get total length of string
//First name section
int firstLength = firstName.length();
if (firstLength%2 == 0){
String firstHalf = firstName.substring(0, firstLength/2);
}
//Last name section
int lastLength = lastName.length();
if (lastLength%2 == 0){
String lastHalf = lastName.substring((lastLength/2), lastLength);
}
if (lastLength%2 == 1){
String lastHalf = lastName.substring((lastLength/2), (lastLength)-1);
}
//Output the DJ name using println combined with the word "Jayster"
System.out.println(firstHalf + "Jayster" + lastHalf);
}
}
I can't figure out why java cannot find symbol. My code compiles fine until the last println. It's pointing at firstHalf and lastHalf specifically. I have them defined in the if statement, but it won't compile.
Is it because if statements are kind of isolated from the main code?
In the snippet above the firstHalf and secondHalf have scope only in their respective If blocks. Where as you are trying to print it in the method scope of Main.
You can find more info about scopes here.
Check the refactored code below.
import java.util.Scanner;
public class DJNameCreator {
public static void main(String[] args){
String firstName;
String lastName;
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter your first name: ");
firstName = keyboard.nextLine();
System.out.println("Nice to meet you, "+firstName+"!");
System.out.println("Please enter your last name: ");
lastName = keyboard.nextLine();
int firstLength = firstName.length();
// FirstHalf is in the scope of main method.
String firstHalf = "";
if (firstLength%2 == 0){
firstHalf= firstName.substring(0, firstLength/2);
}
int lastLength = lastName.length();
// LastHalf is in the scope of main method.
String lastHalf ="";
if (lastLength%2 == 0){
lastHalf = lastName.substring((lastLength/2), lastLength);
}
if (lastLength%2 == 1){
lastHalf = lastName.substring((lastLength/2), (lastLength)-1);
}
//Output the DJ name using println combined with the word "Jayster"
System.out.println(firstHalf + "Jayster" + lastHalf);
}
}

How to get a scanner to loop until it reads a desired string?

Scanner one = new Scanner(System.in);
System.out.print("Enter Name: ");
name = one.nextLine();
System.out.print("Enter Date of Birth: ");
dateofbirth = one.nextLine();
System.out.print("Enter Address: ");
address = one.nextLine();
System.out.print("Enter Gender: ");
gender = //not sure what to do now
Hi I've tried to figure this out myself but I can't quite get it from looking at other examples, most are either only accepting certain characters or A-Z+a-z
I'm trying to make the program only accept input of male or female ignoring the case and if the input is wrong to repeat the "Enter Gender:" until a correct value is entered.
You can put the piece of code in a while and validate each time. for instance:
String gender;
do
{
System.out.print("Enter Gender ('male' or 'female'): ");
gender = one.nextLine().toLowercase();
} while(!gender.equals("male") && !gender.equals("female"))
do {
System.out.print("Enter Gender (M/F): ");
gender = one.nextLine();
} while (!gender.equalsIgnoreCase("M") && !gender.equalsIgnoreCase("F"));
You can add an if check after gender assignment to display a invalid message
One way to do this is to use infinite loop and a label to break out.
Like this:
//Start
Scanner one = new Scanner(System.in);
here:
while (true){
System.out.print("Enter Gender: ");
String str = one.nextLine();
switch (str.toUpperCase()){
case "MALE":
System.out.println("Cool");
break here;
case "FEMALE":
System.out.println("Nice");
break here;
default:
System.out.println("Genders variants: Male/Female");
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Name: ");
String name = readValue(scanner, null);
System.out.print("Enter Date of Birth: ");
String dateofbirth = readValue(scanner, null);
System.out.print("Enter Address: ");
String address = readValue(scanner, null);
System.out.print("Enter Gender: ");
String gender = readValue(scanner, createGenderMatcher());
}
private static IMatcher createGenderMatcher() {
return new IMatcher() {
#Override
public boolean isMatch(String value) {
return "male".equalsIgnoreCase(value) || "female".equalsIgnoreCase(value);
}
};
}
private static String readValue(Scanner scanner, IMatcher matcher) {
String value = null;
do {
value = scanner.nextLine();
} while (matcher != null && !matcher.isMatch(value));
return value;
}
private interface IMatcher {
public boolean isMatch(String value);
}

Scanning different types of variables in one line

As the title says, I would like to scan the whole line of input just using one input from user. The input should be like "Eric 22 1".
If nextString() shouldn't be used that way, should I just use hasNext?
JAVA CODE :
import java.util.Scanner;
public class tugas1
{
public static void main(String []args)
{
String name;
int age;
boolean sex;
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
name = sc.nextString();
age = sc.nextInt();
sex = sc.nextBoolean();
if(isString(name))
{
if(isInteger(age))
{
if(isBoolean(sex))
{
System.out.println("Correct format. You are :" +name);
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the name in string");
}
}
}
After adding and editing the lines :
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String name = inputAfterSplit[0];
int age = Integer.parseInt(inputAfterSplit[1]);
boolean sex = Boolean.parseBoolean(inputAfterSplit[2]);
I would like to add if(name instanceof String). I haven't touched Java since a long time and I forgot is that the way of using instanceof, or is that wrong?
The point is I want to compare if the input var is in int or string or bool.
if(name instanceof String)
{
if(age instanceof Integer)
{
if(sex instanceof Boolean)
{
System.out.println("All checked out")
}
else
{
System.out.println("Not boolean")
}
else
{
System.out.println("Not int")
}
System.out.println("Not string")
}
Will these lines work?
Please input your name, age, and sex
As you need to insert values in specific sequence.
Use nextLine() and perform split
For Example:"Abc 123 true 12.5 M"
String s[]=line.split(" ");
And you will have
s[0]="Abc"
s[1]="123"
s[2]="true"
s[3]="12.5"
s[4]="M"
Than parse them to required type.
String first=s[0];
int second=Integer.parseInt(s[1].trim());
boolean third=Boolean.parseBoolean(s[2].trim());
double forth=Double.parseDouble(s[3].trim());
char fifth=s[4].charAt(0);
As your code suggest and as David said you can change just this
name = sc.next();//will read next token
age = sc.nextInt();
sex = (sc.next()).charAt(0);//change sex to character for M and F
//or //sex = sc.nextInt();//change it to int
first thing when we use scanner , we dont have a method called nextString()
so instead we must use next() which is to read string.
secondly when you want to read whole line then use nextLine() which will read entire line in the form of text and put it in a string.
now the String which is read as entire line can be split based on split character(assume it is space in our case)
then get the string array and parse each element to required type.
better if we use try/catch while parsing so that we can catch exception for unwanted format for the input and throw it to user.
sample code without try/catch but you use try/catch as per your need
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String firstParam = inputAfterSplit[0];
int secondParam=Integer.parseInt(inputAfterSplit[1]);
boolean thirdParam=Boolean.parseBoolean(inputAfterSplit[2]);
Reworked it all, this is the remake of the code just in case people are having same problem as mine..
int in the delcaration should be changed into Integer
import java.util.Scanner;
import java.lang.*;
public class tugas1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Input number of line :");
int lineNum = sc.nextInt();
String[] name = new String[lineNum];
Integer[] age = new Integer[lineNum];
String[] gender = new String[lineNum];
System.out.println("Please input your name, age, and gender(Male/Female) \n(Separate each line by an enter) :");
for ( int i = 0; i < lineNum; i++)
{
System.out.print("Line " + (i+1) + " : ");
name[i] = sc.next();
age[i] = sc.nextInt();
gender[i] = sc.next();
}
for ( int j = 0; j < lineNum; j++ )
{
if (name[j] instanceof String)
{
if (age[j] instanceof Integer)
{
if (gender[j] instanceof String)
{
System.out.println("Person #" + (j+1) + " is " + name[j] + ", with age of " + age[j] + " years old, and gender " + gender[j]);
}
else
{
System.out.println("Gender is missing");
}
}
else
{
System.out.println("Age and Gender are");
}
}
else
{
System.out.println("Name, Age and Gender are missing");
}
}
}
}

Can't compare char

boolean isGender = gender == "M";
this statement returns an error "incomparable types"
the rest of the code before that is
import java.util.Scanner;
public class BMR
{
public static void main(String[] args)
{
//Scanner
Scanner in = new Scanner(System.in);
//Get info
System.out.println("Enter your name: ");
String name = in.nextLine();
System.out.println("Gender (M or F): ");
String genderString = in.next();
char gender = genderString.charAt(0);
System.out.println("Enter your age: ");
int age = in.nextInt();
System.out.println("Height in inches: ");
int height = in.nextInt();
System.out.println("Weight in pounds: ");
int weight = in.nextInt();
System.out.println();
//calculate BMR
boolean isGender = gender == "M";
no idea why this doesn't work
"M" is not a character, it's String
Based on your code, you should be using gender == 'M'
As a side note, if gender was a String, you should be using gender.equals("M") or if don't care about the case, you could use gender.equalsIgnoreCase("M") instead.
try
boolean isGender = gender == 'M';
http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html

Categories

Resources