public class Rectangle
{
private int width;
private int height;
public Rectangle(int w, int h)
{
width=w;
height=h;
}
public String shapeInfo()
{
return "The height of this shape is: "+height+"\nThe width of this shape is "+width;
}
public String drawRectangle()
{
String toPrint="";
for (int i=0;i<height;i++)
{
toPrint+="\n";
for (int j=0;j<width;j++)
{
toPrint+="* ";
}
}
return toPrint;
}
}
public class Main
{
public static void Main()
{
Rectangle rectangle1=new Rectangle(10,10);
System.out.println("\nReference for this shape: "+rectangle1);
System.out.println(rectangle1.shapeInfo());
System.out.println(rectangle1.drawRectangle());
}
}
Create a class that will simulate the workings of a bank account. A bank account needs to have an owner, starting balance, as well as the ability to inquire about the current balance, to deposit, and to withdraw money.
A new account needs to be created with the owner's name filled out as well as a specific starting balance (think of your constructor here).
Try out creating several accounts and try to deposit, withdraw, and inquire about the balance.
Here is my suggested solution:
public class BankAccount
{
private String owner;
private double balance;
public BankAccount(String ownerName, double StartBalance)
{
balance= StartBalance;
owner=ownerName;
System.out.println("Congratulations on your new account, "+owner+"!");
System.out.println("Your initial balance is: "+balance+".");
}
public String deposit(double amount)
{
balance+=amount;
return "You have successfully deposited "+amount+" euros.";
}
public String withdraw(double amount)
{
balance-=amount;
return "You have successfully withdrawn "+amount+" euros.";
}
public double balance()
{
return balance;
}
}
b;
public class Main
{
public static void Main()
{
BankAccount acc1=new BankAccount("Matej Kubes",500);
System.out.println(acc1.deposit(300));
System.out.println("The new balance is +"+acc1.balance());
System.out.println(acc1.withdraw(200));
System.out.println("The new balance is +"+acc1.balance());
}
}
Now, you will add user authorization to your Bank Account project. How this will work is that any of the BankAccount class methods will check to see if the user is authorized to deposit, withdraw, or check the balance.
There are multiple ways of implementing this. Do your pen-and-pencil planning first before you start coding. Will you need a new class or will you implement this added functionality within the BankAccount class and/or the Main class? What are the instance variables and methods you will need? Will these methods have parameters or not? Will they return anything or not? Try your best - we will discuss the different possible implementations on Monday.
Here is my solution (not the only correct one):
public class BankAccount
{
// instance variables
private String owner;
private double balance;
private boolean activeSession;
private String password;
public BankAccount(String ownerName, double StartBalance, String pass)
{
// initialise instance variables
balance= StartBalance;
owner=ownerName;
System.out.println("Congratulations on your new account, "+owner+"!");
System.out.println("Your initial balance is: "+balance+".");
activeSession=false;
password=pass;
}
public String deposit(double amount)
{
if (activeSession)
{balance+=amount;
return "You have successfully deposited "+amount+" euros.";
}
else
return("Incorrect credentials.");
}
public String withdraw(double amount)
{
if (activeSession)
{balance-=amount;
return "You have successfully withdrawn "+amount+" euros.";
}
else
return("Incorrect credentials.");
}
public double balance()
{ if (activeSession)
return balance;
else
return -0; //This is just so that the method returns something. We will learn to do this more elegantly later.
}
/**
* Creating an authorized session
*
* @param username
* @param pass
* @return String
*/
public String createSession(String username, String pass)
{
if (username.equals(owner) && pass.equals(password))
{
activeSession=true;
return "You are successfully logged in.";
}
else
{
activeSession=false;
return "Wrong credentials. Access denied.";
}
}
public boolean sessionActive()
{
if (activeSession)
return true;
else
return false;
}
}
public class Main
{
public static void Main()
{
BankAccount acc1=new BankAccount("Matej Kubes",500,"pass123");
System.out.println(acc1.createSession("Matej Kubes","pass123"));
if (acc1.sessionActive())
{
System.out.println(acc1.deposit(300));
System.out.println("The new balance is +"+acc1.balance());
System.out.println(acc1.withdraw(200));
System.out.println("The new balance is +"+acc1.balance());
}
else
System.out.println("Your session is not active.");
}
}
Try to implement the different classes from the role play we played in class on Tuesday. Please, check your school email for the role play cards. Try to implement all of them and then create a main class to test their functionality. For actions you don't know how to implement, just return a message that says, e.g. "clap" or "rectangle", etc.
Think of your instance variables, method parameters (if any), and whether the different methods will be void or will return a value.
public class Acrobat
{
private int count;
public Acrobat()
{
count= 0;
}
public void clap(int times)
{
for (int i=0;i<times;i++)
{
count++;
System.out.println("Clap!");
}
}
public void kneeBend(int times)
{
for (int i=0;i<times;i++)
{
count++;
System.out.println("bending...");
System.out.println("Standing up...");
}
}
public int count()
{
return count;
}
}
public class Main
{
public static void Main()
{
Acrobat acrobat1=new Acrobat();
acrobat1.clap(6);
acrobat1.kneeBend(3);
System.out.println("The total number of exercises is: "+acrobat1.count());
}
}
Constructor overloading occurs when you include two or more constructors with the same name in a class. They must differ either in the number or the data types of its arguments. The compiler will then choose the corresponding constructor to execute according to the parameter provided.
Method overloading, analogue with constructor overloading, occurs when you include two or more methods of the same name in the class body. These methods, however, must differ in the number and/or the data types of the arguments. The compiler will then choose the correct method depending on the arguments provided when calling the method.
Follow up tasks:
Here is my solution, with another method called "getAcrobatName" added for more functionality, the modified/added lines are in bold italics:
public class Acrobat
{
private int count;
private String acrobatName;
public Acrobat(String name)
{
count= 0;
acrobatName=name;
}
public Acrobat()
{
count= 0;
acrobatName="no name";
}
public void clap(int times)
{
for (int i=0;i<times;i++)
{
count++;
System.out.println(this.returnAcrobatName()+" Clap!");
}
}
public void clap()
{
count++;
System.out.println(this.returnAcrobatName()+" Clap!");
}
public void kneeBend(int times)
{
for (int i=0;i<times;i++)
{
count++;
System.out.println(this.returnAcrobatName()+" bending...");
System.out.println(this.returnAcrobatName()+" Standing up...");
}
}
public int count()
{
return count;
}
public String returnAcrobatName()
{
return acrobatName;
}
}
public class Main
{
public static void Main()
{
Acrobat acrobat1=new Acrobat("John");
Acrobat acrobat2=new Acrobat();
acrobat1.clap(6);
acrobat1.kneeBend(3);
acrobat2.clap();
acrobat2.kneeBend(2);
System.out.println("The total number of exercises for "+acrobat1.returnAcrobatName()+" is: "+ acrobat1.count());
System.out.println("The total number of exercises for "+acrobat2.returnAcrobatName()+" is: "+ acrobat2.count());
}
}
Remember some main points about strings in Java:
+
to join strings ==
operator to test strings for equalityThe String object methods included in the AP Java subset are as follows:
string1.equals(string2)
testing two strings for equalitytoString()
returns a string version of any object; this method gets invoked every time you try to print an object. By default, it returns the name and the pointer reference of the object. In order to make it more meaningful for the user, you can override the default method by defining your own version of the toString() method inside your class. An example for this, as seen in the Acrobat class, follows: public String toString()
{
return "The acrobat's name is "+this.returnAcrobatName()+" and it has done "+this.count()+ " exercises thus far.";
}
In this snippet, I used the this
keyword, which refers to the object itself that is calling the method. It is also en example of overriding a method which means to provide a class-specific version of a generic method that will be used instead of the default version.
string1.length()
returns the length of a string (as an integer)string1.substring(int startIndex)
- returns a new string that is a substring of this stringstring1.substring(int startIndex, int endIndex)
- returns a new string that is a substring of this stringstring1.indexOf(String str)
return the index number of the first occurence of string "str" within this string. If the string does not contain the "str" string, it will return -1.string1.compareTo(String otherString)
returns a value <0 if string1
is less than otherString
in dictionary order. It will return 0 if the two strings are identical and it will return a value>0 if string1
follows otherString
in the dictionary."hello"
would be displayed as "olleh"
.. , ; ! ?
(try using two for-loops, having all your punctuation symbols saved in a string of text).toHTML(p,The quick brown fox jumped over the lazy dogs)
would result in returning <p>The quick brown fox jumped over the lazy dogs</p>
Don't forget to use your escape characters as necessary.Problem 2:
import java.util.Scanner;
public class Main
{
public static void main()
{
String name="";
String reversedName="";
Scanner keyboard=new Scanner(System.in);
System.out.println("Type in your name.");
name=keyboard.next();
int length=name.length(); // Here I find the length of the string, so that I can set the loop
for (int i=length-1;i>=0;i--)// counting down,e.g. if a word is 5 letters long: "4,3,2,1,0"
{
reversedName=reversedName+name.substring(i, i+1); // adding letter-by-letter to the new str
}
System.out.println(reversedName);
}
}
Problem 3:
import java.util.Scanner;
public class Main
{
public static void Main()
{
int passwordStrength=0;
String password="";
String punctuation=".,;!?";
Scanner keyboard=new Scanner(System.in);
System.out.println("Input the password");
password=keyboard.next();
if (password.length()<8)
System.out.println("Your password is not long enough.");
else
{
for (int i=0;i<punctuation.length();i++) // traversing through the string containing punctuation
{
if (password.indexOf(punctuation.substring(i,i+1))!=-1) //testing to see if this specific punctuation symbol is found in the password
passwordStrength++; // counter for the number of punctuation symbols found
}
System.out.println("Your password is long enough.");
System.out.println("You have "+passwordStrength+" punctuation symbol(s) in your password.");
if (passwordStrength>0)
System.out.println("You password is strong enough.");
else
System.out.println("You password is NOT strong enough.");
}
}
}
Problem 4:
import java.util.Scanner;
public class Main
{
public static void Main()
{
int passwordStrength=0;
String firstName="";
String lastName="";
String password="";
Scanner keyboard=new Scanner(System.in);
System.out.println("Input the First name");
firstName=keyboard.next();
System.out.println("Input the Last name");
lastName=keyboard.next();
System.out.println("Input the password");
password=keyboard.next();
if (firstName.indexOf(password)==-1 && lastName.indexOf(password)==-1 )
System.out.println("You password is strong enough.");
else
System.out.println("You password is NOT strong enough.");
}
}
Problem 5:
public class tagCreator
{
public tagCreator()
{//the constructor is empty as the only need for creating a tagCreator object is so that we can call its toHTML() method
}
public String toHTML(String HTMLtag, String textInBetween)
{
return "<"+HTMLtag+">"+textInBetween+"</"+HTMLtag+">";
}
}
public class Main
{
public static void main()
{
//Here I create a tagCreator object, so that I can call its toHTML() method on the following line.
tagCreator tc1=new tagCreator();
System.out.println(tc1.toHTML("p","A quick brown fox jumped over the lazy dogs."));
}
}
Problem 6:
import java.util.Scanner;
public class Main
{
public static void main()
{
String word="";
Scanner keyboard=new Scanner(System.in);
System.out.println("Type in the word to check.");
word=keyboard.next();
String wordReversed="";
for (int i=word.length()-1; i>=0;i--)
{
// this is where I reverse the word, letter by letter:
wordReversed+=word.substring(i,i+1); }
// if the original word is the same as the reversed, it's a palindrome:
if (wordReversed.equals(word))
System.out.println(word+" is a palindrome");
else
System.out.println(word+" is NOT a palindrome");
}
}
An alternative solution to Problem 6:
import java.util.Scanner;
public class Main
{
public static void main()
{
String word="";
Scanner keyboard=new Scanner(System.in);
System.out.println("Type in the word to check.");
word=keyboard.next();
int length=word.length();
boolean isPalindrome=true;
for (int i=0; i<length; i++)
{
// the line below is just displaying the individual characters being compared (first:last, second:second-to-last, etc.):
System.out.println(word.substring(i,i+1)+" "+word.substring(length-i-1,length-i));
if (!word.substring(i,i+1).equals(word.substring(length-i-1,length-i)))
isPalindrome=false;
}
if (isPalindrome)
System.out.println(word+" is a palindrome");
else
System.out.println(word+" is NOT a palindrome");
}
}
You can refer to an object that called its method from inside this method by using the "this
" keyword. Is is called implicit parameter.
Task: Look at the Acrobat class implementation above and see where and how the this keyword was used. Could we, instead of using this
use the object name explicitly? (explicit parameter). Would the program work without the "this
" keyword.
publicVoid printAcrobat()
{
System.out.println(this);
}
This method prints the class type and the memory reference of the object that called the printAcrobat () method.
Wrapper classes wrap a primitive value in an object.
Integer
- a wrapper class for the int primitive typeDouble
- a wrapper class for the double primitive typeInteger(int value)
example: Integer (7)
creates an Integer class object that has an int primitive type wrapped in it. The value of the int primitive type is 7.
By "wrapping" the primitive object, it provides object functionality - instance variables and methods.
compareTo(another Integer object)
returns 0 if the two Integer objects equal, a negative integer if it is less than the other Integer, a positive value if it's greater than another Integer.intValue()
returns the int value of an Integer objectequals(object)
returns true if the Integer object equals another objectImporting the class - it should not be necessary, as it it part of the java.lang library:
import java.lang.Math;
abs(int/double x)
- returns the absolute value of int/double xpow(double base,double exponent)
- returns base
to the power of exponent
.sqrt(double x)
- returns the square root of xrandom()
- returns a random number between 0 and 1.base^exponent
", so "2^3
" would translate as two to the power of three. You will need to use String methods as well as one Math method for this. Creating a keyboard for user input will be necessary as well. Think about whether you will need to create two classes or just the Main class.Dice roller:
public class Dice
{
public Dice()
{
}
public int roll()
{
int face=(int) Math.ceil(Math.random()*6);
return face;
}
}
import java.util.Scanner;
public class Main
{
public static void Main()
{
Scanner keyboard=new Scanner(System.in);
Dice dice=new Dice();
System.out.println("What is your guess? a number between 1 and 6");
int guess=keyboard.nextInt();
int rolledNumber=dice.roll();
if (guess==rolledNumber)
System.out.println("You got it.");
else
System.out.println("Not quite. The number that was rolled was "+rolledNumber);
}
}
Problem 2: n-th power:
public class power
{
public double power(int parsedBase, int parsedExponent)
{
int base=parsedBase;
int exponent=parsedExponent;
return Math.pow(base,exponent);
}
}
import java.util.Scanner;
public class Main
{
public static void Main()
{
Scanner keyboard=new Scanner(System.in);
power power1=new power();
System.out.println("Type BASE^EXPONENT");
String command=keyboard.next();
int base =Integer.parseInt(command.substring(0,command.indexOf("^")));
int exponent =Integer.parseInt(command.substring(command.indexOf("^")+1));
double answer=power1.power(base,exponent);
System.out.println(command+" is "+answer);
}
}