BirthDay Wizard Program - java

Given a person’s age, build a Birthday Wizard that can compute the year of birth, considering that you ask the person's age today. Write statements that can be used in a Java program to perform this computation for the Birthday Wizard.
Here what I needed up but it doesn't work. could someone point what I am doing wrong :
import java.util.Scanner;
public class Birthday
{
public static void main(String[]args)
{
int birthday;
int age;
int YearOfBirth;
Scanner keyboard = new Scanner( System.in);
System.out.println(" What is your +Age ?");
age = keyboard.nextInt();
YearOfBirth= 2011 - age;
System.out.println("I was born :+ YearsOfBirth.");
}
}

System.out.println("I was born :+ YearsOfBirth.");
You never close your quote before showing yearsOfBirth
System.out.println("I was born : "+ YearsOfBirth+".");
Try that and let me know.
Also I just noticed you variable names are wrong: in the print statement its YearsOfBirth when you declare it it's YearOfbirth.

System.out.println("I was born :+ YearsOfBirth.");
Should be
System.out.println("I was born :" + YearOfBirth + ".");
Don't know if the age = keyboard.nextInt(); will work though.

System.out.println("I was born :+ YearsOfBirth."); ......this is wrong
use this :
System.out.println("I was born :+" YearsOfBirth);

System.out.println("I was born :+ YearsOfBirth.");
This results in the String literal "I was born :+ YearsOfBirth." being printed out. It's not quite what you want. Perhaps this, is what you meant:
System.out.println("I was born :"+ YearsOfBirth);
This time, the variable YearsOfBirth is converted to a String and concatenated with "I was born :" to provide the desired result.
In Java, when ever you apply the concatenation operator (+) on two objects, and one of them happens to be a String, then the other will be converted to a String object (the value might not make sense), and a new String object will be returned. Also, literals in double-quotes are often Strings.

import java.util.Scanner;
public class Birthday
{
public static void main(String[]args)
{
int birthday;
int age;
int yearOfBirth;
System.out.println(" What is your Age ?");
Scanner keyboard = new Scanner( System.in);
String input = keyboard.nextLine();
age = Integer.parseInt(input);
yearOfBirth = 2011 - age;
System.out.println("I was born :" + yearOfBirth);
}
}
This should work.

Related

Java Programming Error When Run in CMD

today i have an issue with this code i wrote. The problem comes when i try and run it with command prompt, it doesnt display the last line of code i wrote "Congratulations, the birth month is April"
If anyone understands why it would be helpful!
CODE:
import java.io.*;
import java.util.Scanner;
public class Lab3_5{
// Global variable to hold sales is defined
static double age, weight, birthMonth;
public static void main(String[] args){
// Method calls
getAge();
getWeight();
getMonth();
}
// This module takes in the required user input
public static void getAge(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your guess for age: ");
double age = keyboard.nextDouble();
if (age >= 25){
System.out.println("Congratulations, the age is 25 or less.");
}
}
// This module takes in the required user input
public static void getWeight(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your guess for weight: ");
double weight = keyboard.nextDouble();
if (weight <= 128){
System.out.println("Congratulations, the weight is 128 or less.");
}
}
// This module takes in the required user input
public static void getMonth(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your guess for birth month: ");
String birthMonth = keyboard.next();
if (birthMonth == "April"){
System.out.println("Congratulations, the birth month is April.");
}
}
}
It has no relation with the command prompt.
The problem is that :
if (birthMonth == "April"){
should be :
if ("April".equals(birthMonth)){
Strings have to be compared with equals().
birthMonth == "April" is true only if these are the same object.
This is not always the case wheras equals() compares the content of the Strings.
The command prompt is not the issue here.
You can't use "==" with strings, you need to use equals() or equalsignorecase()
public static void getMonth(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your guess for birth month: ");
String birthMonth = keyboard.next();
if (birthMonth.equalsIgnoreCase("April")){
System.out.println("Congratulations, the birth month is April.");
}
}
}
This is because String are objects. (note that String is uppercase what is good practice for classes!)
So you are looking at two different String classes and you are asking if they are the same, which they are not off course. So by using equals() or equalsIgnoreCase, you tell the class to compare itself with the other based on what kind of chars it holds.
In java String is a class and hence birthMonth is an object and so you cannot do
if (birthMonth == "April")
Since == tests for reference equality (whether they are the same object).
you have to string function .equals() or equalsIgnoreCase() (ignores cases) which tests for value equality (whether they are logically "equal").
Like So
if (birthMonth.equalsIgnoreCase("April"))

Java Constructor Syntax Issue

I need a little help understanding constructors. It isnt full code I just need help understanding one part. My code is as follows:
School.java
public class School {
private String name;
private int busNumber;
enter code here
public School (String name) {
this.name = name;
}
public String getSchoolName() {
return name;
}
public int getBusNumber() {
return bus Number;
}
Main.Java
System.out.println("Enter school number 1: ");
school1 = keyboard.nextLine();
School s1 = new School(school1);
System.out.println("Enter school number 2: ");
school2 = keyboard.nextLine();
School s2 = new School(school2);
System.out.println("School 1 is " + s1.getName());
System.out.println("School 2 is " + s2.getName());
System.out.println("Enter the bus number 1: ");
bus1 = keyboard.nextLine();
//Now what I want to do is send the bus numbers to getBusNumber.
//How do I send bus1 so I can use s1.getBusNumber(); to call the number later! I feel like this should be so easy but I can't grasp it or find how to do it anywhere. I also do not want to use a set function. Any syntax help would be awesome!!
Thanks!
So if you need to not use a setter, you probably need to put it in the constructor.
So your constructor would be
public School (String name, int busNumber) {
this.name = name;
this.busNumber = busNumber
}
and your code would look like this
System.out.println("Enter school number 1: ");
school1 = keyboard.nextLine();
System.out.println("Enter school number 2: ");
school2 = keyboard.nextLine();
System.out.println("School 1 is " + school1);
System.out.println("School 2 is " + school2);
System.out.println("Enter the bus number 1: ");
bus1 = keyboard.nextLine();
int intBus1 = Integer.parseInt(bus1)
School s1 = new School(school1, intBus1);
Then later in your code you can call get s1.getBusNumber() if needed
With the code you posted here is not possible since the busNumber is declared private...
You need (is a good practice) to define a setter for the member bus in the class School, you can to use public members but is not a good oop design since you need to change the access of the busNumber to public...
public void setBusNumber(int number) {
this.busNumber = number;
}
and call it from the main java
System.out.println("Enter the bus number 1: ");
bus1 = keyboard.nextLine();
s1.setBusNumber(bus1);
Be aware you need to validate that what you read is a number because next line is returning strings...

java input must take from customer and it must be in sequential way

Write a java program to ask the user for his/her name, age, and salary (double). Follow the input/output format.
Following conversation should be displayed as output on screen, where you will enter the values of name,age and salary.
Suppose your inputs are:
John
22
500
Expected Output:
Hello. What is your name?
Hi John! How old are you?
So you're 22 eh? That's not old at all!
How much do you make John?
500.0! I hope that's per hour and not per year! LOL!
i try to solve like this
import java.util.Scanner;
class Enquiry
{
public static void main(String args[])
{
Scanner scanner=new Scanner(System.in);
do{
System.out.println("Hello. What is your name?");
string name1 = scanner.nextString();
}
while(name1 != null)
{
System.out.println("Hi" +name1 "! How old are you?");
int age = scanner.nextInt();
}
while(age != null)
{
System.out.println("So you're" +age "eh? That's not old at all!"); System.out.println("How much do you make John?");
double salary = scanner.nextDouble();
}
while(salary != null)
{
System.out.println(+salary"! I hope that's per hour and not per year! LOL!");
}
}
}
can any one help me how to solve this and what are mistakes done by me
thanks and really appreciate your help
There are lot of mistakes, like
1.) There is no need for do - while loops.
2.) String is concatenated with + operator, missing in system.out.println() statements.
3.) string name1, S should be in uppercase, String is a java keyword, referring to a datatype.
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Hello. What is your name?");
String name1 = scanner.nextLine();
System.out.println("Hi" + name1 + "! How old are you?");
int age = scanner.nextInt();
System.out.println("So you're" + age + "eh? That's not old at all!");
System.out.println("How much do you make John?");
double salary = scanner.nextDouble();
System.out.println(+salary + "! I hope that's per hour and not per year! LOL!");
}
Output
Hello. What is your name?
John
HiJohn! How old are you?
22
So you're22eh? That's not old at all!
How much do you make John?
500
500.0! I hope that's per hour and not per year! LOL!

Store many values in a variable, if possible

Wondering if anyone can help me, I'm trying to create a program that adds up the total amount of all the prices entered for each book, for as long as the do/while loop keeps looping, but all I have so far is that every time the loop restarts it deletes the previous assigned variable value! Can anybody steer me in the right direction? I'm just beginning with java so my knowledge pool is pretty low.
String surname, firstname, email, cfn, btitle, finished;
double pno, nochild, cage, noboks, costbook=0, totalcost, averagecost, price;
k = new Scanner(System.in);
System.out.print("Welcome - What is your Family surname?");
surname = k.next();
System.out.print("What is your own first name?");
firstname=k.next();
System.out.print("What is your email address?");
email=k.next();
System.out.print("What is your phone number?");
pno=k.nextInt();
System.out.print("How many children do you have?");
nochild=k.nextInt();
System.out.print("You are Alan " + surname);
System.out.println();
int childcounter=1;
do{
System.out.print("What is your childs first name "+childcounter+" of " +nochild+"?");
cfn=k.next();
System.out.print("What is "+cfn+"'s age?");
cage=k.nextInt();
System.out.println();
do {
System.out.print("What is the title of the book "+cfn+" would like?");
btitle=k.next();
System.out.print("Price of '"+btitle+"' ?");
price=k.nextDouble();
System.out.println();
System.out.print("Do you want to finish? y/n ");
finished=k.next();
}
while (finished.equalsIgnoreCase("n"));
if (finished.equalsIgnoreCase("y"))
{
}
childcounter++;
}
while (childcounter <= nochild);
System.out.print("Heres the book price €"+price);
}
use like this
String[][] data = new String[numberOfLoops][numberOfVariable];
so you can use
data[nthIteration][variable] = scanner.next();
To have variables persist through a loop, you need to define them before the loop begins. If a variable is defined inside of a loop, it will be deleted once the loop is finished.
int test;
for (int i=0; i < 10; i++)
{
test = test * i;
}
//test's value will persist
Tutorial: Java >> Variable Scope
If you want to store multiple values into a variable, you should look at Arrays
Tutorial: Java >> Arrays
Probably you need to define a class that contains those variables/fields:
public class MyInfo {
String surname, firstname, email, cfn, btitle, finished;
double pno, nochild, cage, noboks, costbook=0, totalcost, averagecost, price;
}
then create new instance of the class on each iteration of the while loop and store each new object in a list/ArrayList

Splitting a string into different array indexes Java?

I am trying to split a string into different array indexes. This string is coming from user input (through java.util.Scanner) and is being loaded into a String variable. How can I split the input from the string into different array indexes?
Also, how can I do the math functions that are implied by DOBbeing an int?
Here is my code:
import java.util.Scanner;
public class main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter date of birth (MM/DD/YYYY):");
String DOB;
DOB = input.next();
int age = 0;
age = 2013 - DOB - 1;
int age2 = 0;
age2 = age + 1;
System.out.println("You are " + age + " or " + age2 + " years old");
}
}
String[] parts = DOB.split("/");
int months = Integer.parseInt(parts[0]);
int days = Integer.parseInt(parts[1]);
int years = Integer.parseInt(parts[2]);
Then just use years instead of DOB in your calculations.
Better yet, use new Calendar() to get today's precise date, and compare against that.
Use DateTimeFormat as shown in Parse Date String to Some Java Object to parse your string into a DateTime object, and then access the members.
DateTimeFormatter format = DateTimeFormat.forPattern("MM/dd/yyyy");
DateTime dateTime = format.parseDateTime(DOB);
This uses Joda Time library.
Alternatively you can use SimpleDateFormat in a similar manner, to parse it into a Date object.
I notice you're using keyboard input to recognize the string. If the user doesn't input what you expect it will crash your program. (If you're just starting Java, this is fine; you can just run it again)
You can make it easier to split by asking them thrice too eg:
int dob[] = new Integer[3]; // integer array made from Integer class-wrapper
System.out.println("Input day");
dob[0] = Integer.parseInt(input.next());
System.out.println("Input month");
dob[1] = Integer.parseInt(input.next());
System.out.println("Input year");
dob[2] = Integer.parseInt(input.next());
You now have three integers in an array, split and ready to manipulate.
If Integer can't parse the text input as a number you'll get a NumberFormatException.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class main {
public static void main(String args[]) {
// Man you should look onto doing your
// homework by yourself, ijs.
// But here it goes, hope i make myself clear.
Scanner input = new Scanner(System.in);
System.out.println("Enter date of birth (MM/DD/YYYY):");
String DOB;
DOB = input.next();
//
int age;
// You need to know when it is today. Its not 2013 forever.
java.util.Calendar cal = java.util.Calendar.getInstance();
// ^ The above gets a new Calendar object containing system time/date;
int cur_year = cal.get(Calendar.YEAR);
int cur_month = cal.get(Calendar.MONTH)+1; // 0-indexed field.
// Cool we need this info. ill skip the day in month stuff,
// you do that by your own, okay?
SimpleDateFormat dfmt = new SimpleDateFormat("MM/dd/yyyy");
int bir_year;
int bir_month;
try {
// If you wanna program, you must know that not all functions
// will exit as it's intended. Errors happen and YOU should deal with it.
// not the user, not the environment. YOU.
Date d = dfmt.parse(DOB); // This throws a parse exception.
Calendar c = Calendar.getInstance();
c.setTime(d);
bir_year = c.get(Calendar.YEAR);
bir_month = c.get(Calendar.MONTH)+1; // 0-indexed field;
age = cur_year - bir_year;
// Well, you cant be a programmer if you dont think on the logics.
if(cur_month < bir_month ) {
age -= 1;
// If the current month is not yet your birth month or above...
// means your birthday didnt happen yet in this year.
// so you still have the age of the last year.
}
// If code reaches this point, no exceptions were thrown.
// and so the code below wont execute.
// And we have the variable age well defined in memory.
} catch(ParseException e) {
// But if the date entered by the user is invalid...
System.out.println("The date you typed is broken bro.");
System.out.println("Type a date in the correct format MM/DD/YYYY and retry.");
return; // Got errors? tell the program to quit the function.
}
// Well now we can say to the user how old he is.
// As if he/she didnt know it ^^'
System.out.println(String.format("You are %d years old", age));
// **Not tested.
}
}

Categories

Resources