So I have a class project for school and I have to make a bank account program, everything runs smoothly until I hit the while loop, and then it gets stuck in an infinite loop, not executing anything, please help, the code is the following
import java.util.Scanner;
public class Blueprint_ET
{
//initialize all variables in the object
private double balance;
private double interestRate;
private double years;
private String name;
private int age;
private int validAmount;
private double initialBalance;
//construct the objects with the following variables
public Blueprint_ET(double balance, String name, int age){
years=0;
interestRate=.02;
this.balance=balance;
this.name = name;
this.age= age;
initialBalance = balance;
}
//deposit method
public void deposit(double depositAmt){
balance+=depositAmt;
}
//withdraw method
public void withdraw(double withdrawAmt){
balance-=withdrawAmt;
}
//method used to set the account years and add the interest accordingly
public void setYearsAndAddInterest(double years){
this.years=years;
double interestEarned = (interestRate * years) * balance;
balance += interestEarned;
}
//method used to get the name so that it can be printed out later on
public String getName(){
return name;
}
//method used to get the initial balance so that it can be printed out
public double getStarting(){
return initialBalance;
}
//method used to get the years so that it can be printed out
public double getYears(){
return years;
}
//method used to get the final balance once the account it closed
public double getFinal(){
return balance;
}
//method used to get the age of the person
public int getAge(){
return age;
}
public static void main(String[] args){
//create "kboard" scanner
Scanner kboard = new Scanner(System.in);
//ask the user to enter the persons first name
System.out.print("Enter the account owners first name here: ");
String firstName = kboard.nextLine();
//ask the user to enter the persons last name
System.out.print("Enter the account owners last name here: ");
String lastName = kboard.nextLine();
//puts together the first and last name into one variable
String fullName = firstName + " " + lastName;
//asks the user for the starting balance of the account
System.out.print("Enter the starting balance of the account here: ");
double balance = kboard.nextDouble();
//asks the user for the age of the person
System.out.print("Enter the age of the person here: ");
int age = kboard.nextInt();
//initialize variables that will be used in the while loop
String option;
int exitNum=0;
double years=0;
double deposit=0;
double withdraw=0;
//Create account object
Blueprint_ET account1 = new Blueprint_ET(balance, fullName, age);
//start while loop
while (exitNum < 20 ){
//prompts the user to enter what option they want to do with according codes
System.out.print("To widthdraw, type wd, to deposit, type d, to change the number of years that the account has been open and add the according interest, type y, to close the account, type c.");
option = kboard.nextLine();
//if statement for entering the amount of money withdrawn if the option selected is the code for wd
if (option == "wd") {
System.out.print("Enter the amount you want to withdraw from the account: ");
withdraw = kboard.nextDouble();
account1.withdraw(withdraw);
}
//if statement for entering the years the account has been open and sets the years and adds the interest rate into the balance
else if (option == "y") {
System.out.print("Enter the years the person has had the account open: ");
years = kboard.nextDouble();
account1.setYearsAndAddInterest(years);
}
//if statement for entering the amount of money to deposit, adds it to balance
else if (option == "d") {
System.out.print("Enter the amount you want to deposit: ");
deposit = kboard.nextDouble();
account1.deposit(deposit);
}
//sets the exitNum to 21 so that it can exit the while loop
else if (option == "e") {
exitNum = 21;
}
}
//prints out all data once the account has been closed
System.out.println(account1.getName()+"'s is "+account1.getAge()+" had an account that had an intial balance of "+account1.getStarting()+". This account was open for "+account1.getYears()+" years. Also, when the account was closed, they had a balance of "+account1.getFinal());
}
}
Consider this code of yours:
//sets the exitNum to 21 so that it can exit the while loop
else if (option == "e") {
exitNum = 21;
}
Note that there are 2 ways to compare:
Using equals to == operator.
Using str.equals(str2) method.
Using equals to == operator.
== tests for reference equality. Let's suppose you have a String
str1 = "Hello World". Now this str1 String object takes up some
space in memory. Now let's suppose you create another exact same
String str2 = "Hello World". Now it's not always known whether these
two different Hello World String objects would return true or
false when compared with str1 == str2. They may return true if
both of these objects are referring to the same Object in memory.
However, this may also return false if they refer to different memory locations.
Bottomline is that == operator tests for the reference. It doesn't
matter to this operator as to what's there inside the objects.
Using str.equals(str2) method.
This str.equals(str2) would actually check what's there inside the
String Objects. It doesn't matter to this method whether both the
objects refer to the same or different memory locations. It only
considers the inside material of the String Objects.
Hence you should always use .equals() method when comparing String Objects. And so your method becomes:
//sets the exitNum to 21 so that it can exit the while loop
else if (option.equals("e")) {
exitNum = 21;
}
You must use a.equals("abc") to compare one string to another. And you have to know the difference between equals() and ==. I have run your code, this is the problem,I think.
You have used the == comparator, which perform a reference check on the two strings. Since the reference check will never be true, it will end up in an infinite loop, skipping all the if else statements
Since you are comparing the contents in the strings, use equals() instead.
You can look up this answer for a detailed explanation.
You should always compare two strings with equals() method. It actually compares the expression which is stored by a String object. For reference types operator == compares the addresses of two objects in memory
Related
Code a complete Java program to the following:
if it is a red light violation, then the fine is 1.75 % of the driver annual salary
if it is a speeding violation, then the fine is 1.2 %of the annual salary plus .5% of the salary for every 1 mile/hour over the speed limit.
What you need to do?
prompt user/officer to enter the full name of the driver
prompt officer to enter his/her full name.
prompt user/officer to enter annual salary of the driver.
prompt the officer to enter the type of violation (1 for red light or 2 for speeding)
if speeding then prompt user to enter how many miles/hour over speed limit.
evaluate with a set of if...else how much fine should be assessed, then print a full report including:
name of officer
name of driver
annual salary
violation type (you need to spell it out not just 1 or 2. (Red Light or Speeding)
amount of fine assessed (print a $ sign and round to two decimals)
Also, you must consider the following:
your program must not accept any code other than 1 or 2 for violation type.
your input must be handled by different methods and not in main()
evaluating the fine must be handled in a method of its own.
report must be handled by a different method.
the whole program must repeat for a new driver.
Extra credits: develop your own solution when a driver is subject to both violation…caught speeding and passing when red
Here is my code:
package FinFines_
import java.util.Scanner;
/*
* Description: This program assesses fines for traffic violations.
*/
public class FinFines_
{
static Scanner get = new Scanner(System.in);
//declarations:
static double mph = 0;
static double salary = 0;
static double fines = 0;
static int violation = 0;
static int answer = 1; //1 to continue or 0 to quit
static String officer = " ";
static String driver = " ";
public static void main(String[] args)
{
//input:
while (answer != 0) //while will allow the program to repeat for a new driver
{
input(officer, driver, salary, violation); //call input method
//calculations:
fines = calculateFines(violation, fines, salary, mph); //call calculateFines method
//Output:
disp(officer, driver, salary, violation,fines); //call disp method
//ask user if they would like to continue
System.out.println("Would you like to write a new ticket? Press 1 for yes or 0 for no: ");
answer = get.nextInt();
}//end while
System.out.println("Goodbye!");
}//end main
//=================================================================
public static void input(String officer, String driver, double salary, int violation) //Input Method
{
System.out.println("Officer, please enter your first and last name: ");
officer = get.nextLine();
System.out.println("Please the driver's first and last name: ");
driver = get.nextLine();
System.out.println("Please enter the driver's salary: ");
salary = get.nextDouble();
System.out.println("Press 1 if the driver ran a red light. Press 2 if the driver was speeding. Press 3 if the driver is subject to both violations. ");
violation = get.nextInt();
System.out.println("How many miles per hour was the driver going over the speed limit?: ");
mph = get.nextDouble();
}//end input
//=================================================================
public static double calculateFines(int violation, double fines, double salary, double mph) //calculates the amount of fines for either violation
{
{
if (violation == 1)
return (salary * 1.75);
else if (violation == 2)
return (salary * 1.2) + (mph * .5 * salary);
else if (violation == 3)
return (salary * 1.75) + ((salary * 1.2) + (mph * .5 * salary));
return 0;
}
}//end calculateFines
//=================================================================
public static void disp(String officer, String driver, double salary, int violation, double fines) //Display Method
{
System.out.println ("Your name is Officer " + officer + "\nThe name of the driver you pulled over is: " + driver);
System.out.println ( String.format( "The driver's annual salary is $%.2f", + salary) );
{
if (violation == 1)
System.out.println("\nThe type of traffic violation the driver received: Red Light");
else if (violation == 2)
System.out.println("\nThe type of traffic violation the driver received: Speeding");
else if (violation == 3)
System.out.println("\nThe type of traffic violation the driver received: Red Light & Speeding");
}
System.out.println ( String.format( "The amount of fines that will be assessed is $%.2f", + fines) );
}//end disp
}//end class FinFines_
Here is my issue:
When I input values for my program, the program acts as if I didn't input any names or numbers. All it says is
"Your name is Officer
The name of the driver you pulled over is:
The driver's annual salary is $0.00
The amount of fines that will be assessed is $0.00"
What can I do to make sure the program holds my inputted values?
When I press 1, to continue, it skips the first line when it asks for the officer's name. It doesn't allow me to input a name for the variable.
What can I do to make sure my program doesn't skip this line?
Is there an issue with my "return 0;" statement? If I don't include that statement then my program can't run, but I worry that me including it is making my program give 0 to all values.
I noticed that in the calculateFines() method, you have multiplied your values by 1.75. This will give 175% of the original. To find 1.75%, you need to multiply by 0.0175. This is also applicable for all other values.
Hope this helps
Though not a good practice to make everything static. Yet to just make your code work change all your methods as following -
public static void input(String officer, String driver, double salary, int violation) //Input Method {
to
public static void input() {
public static double calculateFines(int violation, double fines, double salary, double mph) //calculates the amount of fines for either violation {
to
public static double calculateFines() {
public static void disp(String officer, String driver, double salary, int violation, double fines) //Display Method {
to
public static void disp() {
This would ensure all your static fields are updated as you call these methods using the same parameters within thei definition and now your main() would include
while (answer != 0) {
input();
fines = calculateFines(); //call calculateFines method
disp();
System.out.println("Would you like to write a new ticket? Press 1 for yes or 0 for no: ");
answer = get.nextInt();
}
Note - I've cut short the text and removed comments, please do keep them in your code.
You need to read about the behavior of nextLine(), nextInt(), and nextDouble() regarding new line characters. If any of these leaves a newline character in the input buffer, then the following one will see that character and not consume any further input. This is what you are seeing.
To fix the issue, you need to read the newline character from the Scanner and ignore it. You should look at the Javadocs for Scanner to find an appropriate method to do this.
This is the same issue as #1.
Most likely there is no problem with this return as long as the if statements account for all possible values of violation. In fact, this is a very good solution because it will immediately let you see when violation has an invalid value. You should also learn about enums which allow you to define a finite number of choices for a variable.
I'm in a Java class and I'm having extreme difficulty getting started on the assignment. I do not want the answer but I really would appreciate any and all help on getting going and a basic outline of what to do.
A supermarket wants to reward its best customer of each day, showing the customer’s name on a screen in the supermarket. For that purpose, the customer’s purchase amount is stored in an ArrayList<Double> and the customer’s name is stored in a corresponding ArrayList<String>.
Implement a method
public static String nameOfBestCustomer(
ArrayList<Double> sales,
ArrayList<String> customers)
that returns the name of the customer with the largest sale.
Write a program that prompts the cashier to enter all prices and names, adds them to two array lists, calls the method that you implemented, and displays the result. Use a price of 0 as a sentinel.
You can use a Scanner to get the values that the cashier enters (an int for the purchase amount and a String for the customer's name, use conditions and throw exceptions to guarantee the values' types). Those values are put in two ArrayList (Lists of Integer and String).
Once the supermarket closes, you can use a loop on the list of purchases amounts to find the max purchase amount and its position in the list and use this position to find the best customer in the other list.
This is what you can do :
package com.assignments;
import java.util.ArrayList;
import java.util.Scanner;
public class MaxSalesCustomer {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> customerNameArray = new ArrayList<String>();
ArrayList<Integer> customerSalesValue = new ArrayList<Integer>();
String continueAdding = "Y";
Scanner sc=new Scanner(System.in);
while(continueAdding.equals("Y")){
System.out.println("Please Enter the customer Name:");
String name = sc.next();
customerNameArray.add(name);
System.out.println("Please Enter the sales value:");
Integer sales = sc.nextInt();
customerSalesValue.add(sales);
System.out.println("Do you want to continue 'Y/N' ?" );
continueAdding = sc.next();
}
String maxSalesCustomerName = getMaxSalesCustomerName(customerNameArray,customerSalesValue);
System.out.println(maxSalesCustomerName);
}
public static String getMaxSalesCustomerName(ArrayList<String> customerNameArray,ArrayList<Integer> customerSalesValue){
Integer maxValue = 0;
String maxSalesCustomerName = new String();
for (int i = 0; i < customerSalesValue.size(); i++){
if (maxValue < customerSalesValue.get(i)){
maxValue = customerSalesValue.get(i);
maxSalesCustomerName = customerNameArray.get(i);
}
}
return maxSalesCustomerName;
}
}
In my CIS 220 Java Application 2 class, we have just went over the use of objects and classes with constructors and such. The whole goal of this assignment is to utilize a class and its methods to get the user employee data. I feel I've more or less finished the whole thing, but there is one last part. The data must be validated, as explained in this screenshot link http://puu.sh/7vzeI.jpg
I would assume employee ID needs to be 9 characters long as a string. The pay rate and hours worked must be doubles. Sadly I have no idea what sort of code I need in order to validate it in the class. I figured it was a while loop but it didn't seem to work.
Here is the main java method:
public class Project3 {
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
Employee worker1 = new Employee();
worker1.getEmployeeName();
worker1.getEmployeeNum();
worker1.getPayRate();
worker1.getEmployeeHours();
System.out.println("Employee Name: " + worker1.printEmployeeName());
System.out.println("Employee ID: " + worker1.printEmployeeNum());
System.out.println("Pay Rate: $" + worker1.printPayRate());
System.out.println("Hours Worked: " + worker1.printHoursWorked());
worker1.getNetPay();
}
}
These are the methods in a class titled "Employee" which are used by main:
public String getEmployeeName()
{
System.out.println("Please enter the employee's name: ");
employeeName = console.nextLine();
return employeeName;
}
// Method that prompts the user to enter their hours worked, then returns it as the reference
public double getEmployeeHours()
{
System.out.println("Enter the number of hours worked(a numeric value between 0.0 and 100.0): ");
hoursWorked = console.nextDouble();
return hoursWorked;
}
// Method that prompts the user to enter their employee ID, then returns it as the reference
public String getEmployeeNum ()
{
System.out.println("Please enter the employee's ID: ");
employeeNum = console.nextLine();
return employeeNum;
}
// Method that prompts the user to enter their pay rate, then returns it as the reference
public double getPayRate()
{
System.out.println("Please enter the employee's pay rate (a numeric value): ");
payRate = console.nextDouble();
return payRate;
}
Please forgive me if the format of this question is hideous, as I am still quite new to stack overflow.
I think you may not be clear on the concept of return methods. There is no point in making a return method if you are not going to use the returned value at any point. For example
public String getEmployeeName()
{
System.out.println("Please enter the employee's name: ");
employeeName = console.nextLine();
return employeeName;
}
// in the other class
worker1.getEmployeeName();
You never assign the String "worker1.getEmployeeName()" to anything so making this a return statement is useless. What I would do is that I would remove the getter methods aka "worker1.printEmployeeName()" and do this instead:
String name = worker1.printEmployeeName();
System.out.println("Employee Name: " + name);
Then in the method "printEmployeeName()" I would add my checks to see if the input was valid or not. like so:
(I don't think the name could have an invalid input except for maybe if it was null, so I will use the number instead.)
Okay so to validate the information I would do this:
public String getEmployeeNum ()
{
while(true)
{
System.out.println("Please enter the employee's ID: ");
try{
employeeNum = console.nextInt(); //this should be getting an integer not the line
}catch(Exception e){
employeeNum = 0;
}
if(String.valueOf(employeeNum).length() == 9)
return String.valueOf(employeeNum); // this will break you out of your loop and return the value
else{
System.out.println("Invalid input...");
continue;
}
}
}
Now I'll try an explain the code above
Because we are using "console.nextInt();" in order to check if what the user enters is not a string, a double or anything else that is not a integer I used a try catch statement. If you are unfamiliar with how the try catch works, it basically checks if there is an error with the code in the " try{ } " part and if there is do what is in the "catch(Exception e) { } " block. I could go in to more detail on it but that explains it enough for now. So if there is a problem with the input or we find an "error" with it we set the employeeNum to "0" (You'll see why in the next part).
Then we move on to the if statement "if(String.valueOf(employeeNum).length() == 9)" basically this will turn our input into a String so we can check the length (Remember if there is an error with the input the employeeNum will be "0" with the length of "1")
If the input is valid (9 numbers long) we then return it "return employeeNum;"
If it is not valid (Not long enough or too long) we tell the user that there was an error, and we restart the process.
I hope this helps some or at least gives you an idea on what to do next!
If you want to read and learn some more:
Try Catch : http://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
Edit: (A Hint)
When you check if the values are doubles for the pay rate and hours use something like this:
try {
hoursWorked = console.nextDouble();
}catch(Exception e){
hoursWorked = -1.0;
}
if(hoursWorked > 0.0)
return hoursWorked;
// the end should be the same as the other example :)
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
so far I have created two classes, which I will show below
I have tested both classes and they both seem to work.
I now need to create a menu which will use the two classes I have created and allow users to enter the information and to find information on their account for the following:
Add the customers details
Make a deposit to the business account
Record a meter reading to the business account
Display current balance of the business account
Display full account details
Change the discount value for the business account
Change the cost per unit for all business accounts
How to use the menu system
While I have tried my best to find out how to do it using resources online I am currently lost. Up to this point every time I have tried to create a menu system I just could not get it to work. I would greatly appreciate if someone could help me with the basics on how to go about doing it.
Thanks :)
public class GasAccount
{
private int intAccRefNo;
private String strName;
private String strAddress;
public double dblBalance;
private double dblUnits;
public static double dblUnitsCosts = 0.02;
public GasAccount (int intNewAccRefNo , String strNewName , String strNewAddress)
{
}
public GasAccount (int intNewAccRefNo , String strNewName , String strNewAddress , double dblNewUnits)
{
intAccRefNo = intNewAccRefNo;
strName = strNewName;
strAddress = strNewAddress;
dblUnits = dblNewUnits;
dblBalance = dblUnits * dblUnitsCosts;
}
public int getAccRefNo()
{
return intAccRefNo;
}
public String getName()
{
return strName;
}
public String getAddress()
{
return strAddress;
}
public void deposit(double dblDepositAmount)
{
dblBalance = dblBalance - dblDepositAmount;
}
public double getBalance()
{
return dblBalance;
}
public double getUnitCost()
{
return dblUnitsCosts;
}
public void recordUnits (double dblUnitsUsed)
{
dblBalance = dblBalance + dblUnitsUsed * dblUnitsCosts;
dblUnits = dblUnitsUsed + dblUnits;
}
public double getUnits()
{
return dblUnits;
}
public void updateUnitsCosts(double dblNewUnitsCosts)
{
this.dblUnitsCosts = dblNewUnitsCosts;
}
}
And another which extends it -
public class BusinessAccount extends GasAccount
{
private double dblDiscount;
public BusinessAccount (int intNewAccRefNo, String strNewName, String strNewAddress, double dblNewUnits, double dblNewDiscount)
{
super (intNewAccRefNo , strNewName , strNewAddress, dblNewUnits);
dblDiscount = dblNewDiscount;
}
public void setNewDiscount(double dblNewDiscount)
{
dblDiscount = dblNewDiscount;
}
public double getDiscount()
{
return dblDiscount;
}
#Override
public void recordUnits (double dblUnitsUsed)
{
double dblNewBalance;
dblBalance = dblBalance + dblUnitsUsed * dblUnitsCosts;
dblNewBalance = dblUnitsUsed * dblUnitsCosts * dblDiscount / 100;
dblBalance = dblBalance - dblNewBalance;
}
Here is what my attempted menu looks like up to the fifth option. I am doing something horribly wrong with calling in the methods from the other classes as BuisnessAccount.getMethod always shows up as an error. I am also pretty sure declaring the variables again is completely wrong as then they have no link to my other classes.
If someone could help me solve this it would be greatly appreciated
import java.util.Scanner;
public class Menu
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int Choice;
{
System.out.println("------------------------------");
System.out.println ( "1. Add the customers details" ) ;
System.out.println ( "2. Make a deposit to the business account" );
System.out.println ( "3. Record a meter reading to the business account" ) ;
System.out.println ( "4. Display current balance of the business account" ) ;
System.out.println ( "5. Display full account details" ) ;
System.out.println ( "6. Change the discount value for the business account" ) ;
System.out.println ( "7. Change the cost per unit for all business accounts ");
System.out.println ( "8. How to use the menu system ");
System.out.println ( "Any other number will exit the program");
System.out.println("------------------------------");
System.out.println ( "\n\nEnter a number from 1 to 8" );
Choice = input.nextInt();
switch (Choice)
{
case 1 :
int intNewAccRefNo;
String strNewName;
String strNewAddress;
Double dblNewUnits;
Double dblNewDiscount;
System.out.println("Please enter the account number?");
intNewAccRefNo = input.nextInt();
System.out.println("Please enter the account name?");
input.nextLine();
strNewName = input.nextLine();
System.out.println("Please enter the account address?");
strNewAddress = input.nextLine();
System.out.println("Please enter the number of initial number of units used?");
dblNewUnits = input.nextDouble();
System.out.println("Please enter the discount?");
dblNewDiscount = input.nextDouble();
case 2:
double dblDeposit;
System.out.println("Please enter the amount you want to deposit?");
dblDeposit = input.nextDouble();
System.out.println ( "The current balance: " + BusinessAccount.getBalance() ) ;
case 3:
double dblUnits;
System.out.println("Enter the number of Units Used");
dblUnits = input.nextDouble();
BusinessAccount.recordUnits(dblUnits);
case 4:
System.out.println("\n Current Balance: £"+ BusinessAccount.getBalance());
case 5:
System.out.println("Account Reference Number: " + BusinessAccount.getAccRefNo());
System.out.println("Address: " + BusinessAccount.getAddress());
System.out.println("Name: " + BusinessAccount.getName());
System.out.println("Balance: " + BusinessAccount.getBalance());
System.out.println("Discount: " + BusinessAccount.getDiscount());
System.out.println("Units: " + BusinessAccount.getUnits());
case 1 :
String strAddress;
System.out.println("Please enter the account address?");
strAddress = input.nextLine();
System.out.println("Address:" + firstAccount.getAddress());
There is no connection between what the user inputs and the method which i am calling, not sure how to fix.
By using BusinessAccount.someMethod(), you're attempting to call said method in a static context, but your methods are not static. To call upon your methods, you either need to make them static or need to create an object which can then call upon them, ie:
BusinessAccount ba= new BusinessAccount (4, "name", "address", 3.4, 43.4);
ba.someMethodFromClass();
In your case, you do NOT want them to be static. Read up more on static methods/variables (see below).
Some documentation that may be helpful:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/JMenu.html
To answer your second question, you need to have a method (in your object's class, not main) which can assign values to your variables. ie:
public void setAddress (String address)
{
strAddress=address;
}
Then, you'd pass the address that you read in from main into your function. By doing that, you're initializing/assigning the value from the user to the value stored in your class, ie:
System.out.println("Please enter the account address?");
String temp = input.nextLine();
ba.setAddress(temp);
System.out.println("Address:" + ba.getAddress());
or better yet,
System.out.println("Please enter the account address?");
ba.setAddress(input.nextLine());
System.out.println("Address:" + ba.getAddress());
Going off of what SteveP said, it would be a good idea to store the instances of the other classes as instance variables in the Menu class.
Also, if you're using a GUI interface, this JMenu class API may come in handy:
http://docs.oracle.com/javase/7/docs/api/javax/swing/JMenu.html
Also look for JMenuBar, JMenuItem
I'm just learning java so this is probaly a really dumb question but i can't find a simple enough answer. I'm trying to make a make the program so if the user types "male" to run the System.out.print("You are a guy");
Here's my code:
import java.util.Scanner;
public class clac {
public static void main(String[] args){
double gender;
Scanner input = new Scanner(System.in);
System.out.print("Are you male or female? ");
gender = input.nextDouble();
if (gender == "male"){
System.out.println("You are a guy");
}else{
System.out.print("You are a gal.");
}
}
}
What you are doing wrong: You need to read a String. A String is a piece of text. A double is a decimal number. You are reading a double.
How to solve it:
String gender = input.next(); // read a String, instead of double
if (gender.equals("male")) // if (gender == "male") use .equals for strings
{
System.out.println("U mad bro!?");
} else
{
System.out.println("Hey Doll!");
}
You shouldn't be using nextDouble(), that refers to a decimal.
Try
String gender = input.nextString();
if ("male".equals(gender)){
System.out.println("Wazzup dude?");
}else{
System.out.print("Hey Doll!");
}
I believe you want to use the .next() method for scanner. Try something like this:
import java.util.Scanner;
public class clac {
public static void main(String[] args){
//Define gender variable as a string since that's what we're expecting as an input
string gender;
//Instantiate a Scanner object
Scanner input = new Scanner(System.in);
//Ask the user a question
System.out.print("Are you male or female? ");
//Read in the response into the gender variable
gender = input.next();
//Check to see if the user's answer matches "male"
//We put "male" first in case the user returns a null value
//This will help avoid a fatal error
if ("male".equals(gender)){
System.out.println("You are a guy");
}
else {
System.out.print("You are a gal.");
}
}
}
I hope this helps.
you should use the equals method to compare the two strings,the string is a object,this is a reference,the equals() method will compare the content of two strings,but the == will compare the address of two strings
so,you should write like this:
gender = input.next();
if (gender.equals("male")){
System.out.println("You are a guy");
}else{
System.out.print("You are a gal.");
}