UserNamePasswordValidation

UserNamePasswordValidation 1

Create a class the asks the user for their name. Loop and call the validateName method that checks the name against the valid name array. If there is a match move on to the next section. If it does not match loop and ask again for the name until there is a match. The validateName method has one String as an argument and returns a Boolean value of true or false. It checks the incoming argument against the array of valid usernames that you create. It should have at least three names. If a valid name is found then return true, else return false.
Once the validate name is passed then the main method will loop again and ask the user for their password. It will then pass the password to the validatcPassWord method that will check the password against the password array. If they match, continue. If they don’t match loop and ask the user to try again. The validate password array should have three valid passwords at least. The same number as valid login names. The validatePassWord method takes one String as an argument and returns a Boolean value. If the incoming String matches one of the passwords in the password array, then return true, otherwise return false. Once the password is validated, display “Login successful” from the main method.

Copenhagen Transit

Copenhagen Transit 2

Write a program that computes the fare on the Copenhagen Transit system given two inputs from the user:The zone number: 1 or more
The passenger type: adult or childYour prompts to the user must be :Enter zone number :
Enter adult or child :
The fare on Copenhagen Transit is specified as follows:If the zone is 2 or smaller and the ticket type is “adult,” the fare is 23.0.
If the zone is 2 or smaller and the ticket type is “child,” the fare is 11.5.
If the zone is 3 and the ticket type is “adult,” the fare is 34.5.
If the zone is 3 or 4 and the ticket type is “child,” the fare is 23.0.
If the zone is 4 and the ticket type is “adult,” the fare is 46.0.
If the zone is greater than 4, the fare is -1.00 (since your calculator does not handle inputs that high).Your output must be in the format:The fare for adultOrChild to zone number zoneNumber is *****A sample run of the program with inputs 3 and adult must look like:Enter zone number : 3
Enter adult or child : adult
The fare for adult to zone number 3 is $34.50Please note that your class should be named CopenhagenTransit.

Sieve of Eratosthenes

Sieve of Eratosthenes 3

Sieve of Eratosthenes
A prime number is any integer greater than 1 that’s evenly divisible only by itself and 1. The Sieve of Eratosthenes is a method of finding prime numbers. It operates as follows:
a) Create a primitive-type boolean array with all elements initialized to true. Array elements with prime indices will remain true. All other array elements will eventually be set to false.b) Starting with array index 2, determine whether a given element is true. If so, loop through the remainder of the array and set to false every element whose index is a multiple of the index for the element with value true. Then continue the process with the next element with value true. For array index 2, all elements beyond element 2 in the array that have indices which are multiples of 2 (indices 4, 6, 8, 10, etc.) will be set to false; for array index 3, all elements beyond element 3 in the array that have indices which are multiples of 3 (indices 6, 9, 12, 15, etc.) will be set to false; and so on.When this process completes, the array elements that are still true indicate that the index is a prime number. These indices can be displayed. Write an application that uses an array of 1,000 elements to determine and display the prime numbers between 2 and 999. Ignore array elements 0 and 1.

Saving Account Class

Saving Account Class 4

Saving Account Class
Create class SavingsAccount. Use a static variable annualInterestRate to store the annual interest rate for all account holders. Each object of the class contains a private instance variable savingsBalance indicating the amount the saver currently has on deposit. Provide method calculateMonthlyInterest to calculate the monthly interest by multiplying the savingsBalance by annualInterestRate divided by 12—this interest should be added to savingsBalance. Provide a static method modifyInterestRate that sets the annualInterestRate to a new value. Write a program to test class SavingsAccount. Instantiate two savingsAccount objects, saver1 and saver2, with balances of $2000.00 and $3000.00, respectively. Set annualInterestRate to 4%, then calculate the monthly interest for each of 12 months and print the new balances for both savers. Next, set the annualInterestRate to 5%, calculate the next month’s interest and print the new balances for both savers.

Game of Craps

Game of Craps 5

Game of Craps
Write an application that runs 1,000,000 games of craps code in discussed in chapter 6 (also given in appendix 1 of this assignment file) and answers the following questions:
a) How many games are won on the first roll, second roll, …, twentieth roll and after the twentieth roll?
b) How many games are lost on the first roll, second roll, …, twentieth roll and after the twentieth roll?
c) What are the chances of winning at craps? [Note: You should discover that craps is one of the fairest casino games. What do you suppose this means?]
d) What is the average length of a game of craps?
e) Do the chances of winning improve with the length of the game?

Appendix 1 – Game of Craps Code
// Fig. 6.9: Craps.java
// Craps class simulates the dice game craps.
import java.util.Random;
public class Craps
{
// create random number generator for use in method rollDice
private Random randomNumbers = new Random();
// enumeration with constants that represent the game status
private enum Status { CONTINUE, WON, LOST };
// constants that represent common rolls of the dice
private final static int SNAKE_EYES = 2;
private final static int TREY = 3;
private final static int SEVEN = 7;
private final static int YO_LEVEN = 11;
private final static int BOX_CARS = 12;
// plays one game of craps
public void play()
{
int myPoint = 0; // point if no win or loss on first roll
Status gameStatus; // can contain CONTINUE, WON or LOST
int sumOfDice = rollDice(); // first roll of the dice
// determine game status and point based on first roll
switch ( sumOfDice )
{
case SEVEN: // win with 7 on first roll
case YO_LEVEN: // win with 11 on first roll
gameStatus = Status.WON;
break;
case SNAKE_EYES: // lose with 2 on first roll
case TREY: // lose with 3 on first roll
case BOX_CARS: // lose with 12 on first roll
gameStatus = Status.LOST;
break;
default: // did not win or lose, so remember point
gameStatus = Status.CONTINUE; // game is not over
myPoint = sumOfDice; // remember the point
System.out.printf( “Point is %d\n”, myPoint );
break; // optional at end of switch
} // end switch
// while game is not complete
while ( gameStatus == Status.CONTINUE ) // not WON or LOST
{
sumOfDice = rollDice(); // roll dice again
// determine game status
if ( sumOfDice == myPoint ) // win by making point
gameStatus = Status.WON;
else
if ( sumOfDice == SEVEN ) // lose by rolling 7 before point
gameStatus = Status.LOST;
} // end while
// display won or lost message
if ( gameStatus == Status.WON )
System.out.println( “Player wins” );
else
System.out.println( “Player loses” );
} // end method play
// roll dice, calculate sum and display results
public int rollDice()
{
// pick random die values
int die1 = 1 + randomNumbers.nextInt( 6 ); // first die roll
int die2 = 1 + randomNumbers.nextInt( 6 ); // second die roll
int sum = die1 + die2; // sum of die values
// display results of this roll
System.out.printf( “Player rolled %d + %d = %d\n”,
die1, die2, sum );
return sum; // return sum of dice
} // end method rollDice
} // end class Craps

Coupon Collector

Coupon Collector 6

Solve the following problem using arrays:
Part A: Coupon collector is a classic statistic problem with many practical applications. The problem is to pick objects from a set of objects repeatedly and determine how many picks are needed for all the objects to be picked at least once. A variation of the problem is to pick cards from a shuffled deck of 52 cards repeatedly and find out how many picks are needed before you see one of each suit. Assume a picked card is placed back in the deck before picking another. Write a program to simulate the number of picks needed to get total of four cards from each different suit and display the four cards picked (it is possible that a card may be picked twice).Here is a sample run of the program:
Queen of Spades
5 of Clubs
Queen of Hearts
4 of Diamonds
Number of picks: 12Sample run explanation: As you see in the above run, 12 picks are made to get the four cards from different suits. The other 8 picks (12-4=8) were from the same previously picked suits, so they are not printed. So we continue picking a card until we see at least one card from each of the for suits.Note: The card pick is with replacement, meaning that when you pick a card from the deck of 52 card, you put it back in the deck. There is chance to see the previously selected card again.

Part B: Put part A in a for loop and repeat it 10,000 times and report the average number of total picks we should have to see 4 cards from different suits.

City JAVA

City JAVA 7

A salesman wants to go to five different cities and sell some products. The locations of the cities are listed in the following table.
City # X_location Y_location
City 1 1 1
City 2 1 3
City 3 4 1
City 4 5 3
City 5 3 5The distance between two cities is defined as the Euclidean distance. That is:
Distance = sqrt( (x1 – x2)^2 + (y1 – y2)^2 )
For example, the distance between cities 1 and 2 will be:
Distance = sqrt( (1 – 1)^2 + (1 – 3)^2 ) = sqrt( 4 ) = 2The purpose: The salesman starts his journey from city 1. He then has 4 remaining options for the next city (city 2, city 3, city 4, city 5). If he chooses city 3 as the next destination, then he will have 3 remaining options (city 2, city 4, city 5). He wants to travel all the cities and then come back to the start location (City 1). Not all the paths will be a good choice. We want to help the salesman by finding the shortest path (best order of cities to visit (visit all of them once) starting from city 1).Steps:
Step 1 [7 points]: Create a class City with x and y as the class variables. The constructor with argument will get x and y and will initialize the city. Add a member function getDistanceFrom() to the class that gets a city as the input and finds the distance between the two cities.
city1.getDistanceFrom(city2) will be distance between city 1 and 2.Step 2 [6 points]: Create 5 city objects and initialize their location (x and y) using the above table. Then put all of the five cities in a vector.Step 3 [7 points]: Create a two dimensional array or vector DistanceVec of size 5 * 5 and initialize it such that DistanceVec[i,j] is the distance between city_i and city_j. Print the distanceVec and show the distance among all cities.Step 4 [15 points]: If the salesman starts from the city 1, search all the possible paths and find the optimal path (order of cities to visit) that leads to the minimum total travel distance. Display the found optimal path (order of cities to travel) in your sample run.

sortJAVA

sortJAVA 8

Given the following code
interface WritingTool
{
public double getWordsLeft(int newWords);
}
you are required to create two classes.First, write the code for an abstract class named Pen that implements the WritingTool interface.
Pen should have an integer attribute called wordLimit which represents the number of words that can be written during the life of a Pen. The default value for wordLimit is one million.Next, create a concrete class that is derived from Pen called BallPointPen.
BallPointPen has an integer attribute called futureWords that represents the number of words that can be written by the pen in the future. For a BallPointPen, calling getWordsLeft will result in the futureWords being incremented by newWords, and the returned value will be the difference between the wordLimit and the updated value of futureWords.All attributes should be private in all classes.
Accessors and mutators for all attributes should be provided.
The constructor of each class should initialize it’s attributes.

Search JAVA

Search JAVA 9

Consider an approach to searching for a key in a sorted array in which we randomly choose an index between the two ends of the array, compare the item at that index with the search key and then either • If the item there equals the key, return the index • If the item there is larger than the key, recursively search to the left of index using the same strategy • If the item there is smaller than the key, recursively search to the right of the index using the same strategy
Write a function search(intO a, int key) to implement this searching algorithm.
Write recurrences that describe the average and worst case behaviors of this algorithm and, without formally solving them, explain what you think the answers will be and why.

RockPaperScissors JAVA

RockPaperScissors JAVA 10

Create a java programme called rockPaperScissors.java
● Write a program that allows the user to play rock, paper, scissors.
● The program should randomly generate a number (0, 1 or 2), which
represents scissors, rock and paper, respectively. (Hint: look up
Math.random)
● The program should then prompt the user to enter a number (0, 1 or 2).
● Once the user has entered their number, the program should inform
them whether they win, lose or draw.
● The rules of the game are as follows:
○ Scissors beats paper
○ Rock beats scissors
○ Paper beats rock

×
New Download