exercises
- Write a program that writes “My Kitchen Rules” to the screen
- write a program that outputs a sentence from a dank meme
- Write a program that asks for a user name, and tells the user they are a meme
- Write a program that adds 1 plus 1 together and outputs the answer
- write a program that inputs two whole numbers into two variables (lets say x and y), then outputs the sum, product and difference of those two numbers.
- write a program that outputs the role of a dice. Challenge: add a second dice and calculate the total (so this could be used in monopoly)
- Write a program that asks a user the colour of a traffic light. If it is a “green” light, output “go”. If it is a “yellow” light, output “wait”. If it is a “red” light, output “stop”.
help
import java.util.*; public class traffic { public static void main(String[] args) { String trafficLightColour; Scanner myScanner = new Scanner(System.in); System.out.println("Enter the traffic light colour:"); trafficLightColour = myScanner.nextLine(); if(trafficLightColour.equals("red")) { System.out.println("stop"); } if(trafficLightColour.equals("yellow")) { System.out.println("wait"); } if(trafficLightColour.equals("green")) { System.out.println("go"); } } }
- write a program that inputs the current temperature as a whole number (celcius) and tells me whether it is hot or cold (lets assume hot is anything 20 or over, everything else is cold).
- try to get your program to 'pause'..
help
public class freeze{ public static void finishCount() throws InterruptedException { Thread.sleep(1000); System.out.println("four"); Thread.sleep(1000); System.out.println("five"); } public static void main(String[] args) throws InterruptedException { System.out.println("one"); Thread.sleep(1000); System.out.println("two"); Thread.sleep(1000); System.out.println("three"); finishCount(); } }
- write a program that puts your computer into an infinite loop (hint: when 1 == 1)
- write a program that calculates simple interest. Challenge: put the formula to calculate simple interest into a method
- write a program that counts from 0-50, and for each number counted the program tells me if it is an even or odd number
- write a program that uses a method to find the area of a rectangle
- write a program that adds together all the even numbers from 0 to 100
help
public class even { public static void main(String[] args) { int total = 0; int currentNumber = 0; while(currentNumber<=100){ total = total + currentNumber; currentNumber = currentNumber + 2; } System.out.println(total); } }
- Write a program that adds all the odd numbers together from 1 to n
(where n is a number inputted by a user)
help
import java.util.Scanner; public class odd { public static void main(String[] args) { int maxNumber; Scanner myScanner = new Scanner(System.in); maxNumber = Integer.valueOf(myScanner.nextLine()); int total = 0; int currentNumber = 1; while(currentNumber<=maxNumber){ total = total + currentNumber; currentNumber = currentNumber + 2; } System.out.println(total); } }
- Write a program that uses a method to calculate the area of a circle
help
import java.lang.Math; public class areaOfCircle { public static Double workOutArea(int r){ return 3.14*(Math.pow(r,2)); } public static void main(String[] args) { final int radius = 10; Double answer = workOutArea(radius); System.out.println(answer); } }
- Write an algorithm and program that inputs 5 numbers and calculates the average help
this should be done easily without an array!
thus the following version is acceptable, but complete overkill:import java.util.*; public class arrayAverage{ public static void main(String[] args) { double average = 0; int total = 0; System.out.println("how many elements in total?"); Scanner myInput = new Scanner(System.in); int numOfElements = Integer.valueOf(myInput.nextLine()); int[] arrayList = new int[numOfElements]; for(int index = 0; index <= (numOfElements-1); index++){ System.out.println("enter element " + index); arrayList[index] = Integer.valueOf(myInput.nextLine()); total = total + arrayList[index]; } average = total / numOfElements; System.out.println(average); } }
- Write an algorithm that lists prime numbers between 1 and 20
- Code the algorithm that lists prime numbers between 1 and 20 (use mod / %) help
import java.util.*; public class listPrime { public static void main(String[] args) { //currentNum processes all nums from 1 and 20: for (int currentNum = 1; currentNum <= 20; currentNum++) { //countOfDivisors will increment each time we find a divisible number: int countOfDivisors = 0; //countBackNum counts back from the currentNum to 1: for(int countBackNum = currentNum; countBackNum >= 1; countBackNum--) { //if there is no remainder when dividing: if(currentNum % countBackNum==0) { //theoretically prime numbers have 2 divisors, //1 and itself: countOfDivisors++; } } //therefore if currentNum is only divisible by 1 and itself: if(countOfDivisors==2) { System.out.println(currentNum); } }//end currentNum for-loop (1 to 20) }//end Main }//end listPrime
- sort a simple array of five integer elements into ascending order
- write a program that finds the max, min and average of an array of 5 integers
- try and sort an array of n integers into descending order (where n is a whole integer number inputted by the user)
- write a multidimensional String array that stores the location of 3 sunken treasures (use the String value "Sunken Treasure" to designate this) at 3 random co-ordinates on an x and y axis to simulate a map of the ocean (you can limit the axis to values between 0 and 10)
- right a recursive java program to calculate the factorial of a number, e.g. 5! = 5 * 4 * 3 * 2 * 1 = 120
- currency converter: Write a program that converts any number to a currency string, e.g. 4 = “four dollars”
helpimport java.lang.Math; public class currencyConverter { public static void main(String[] args) { //******************************** final double numberAmount = 913.37; //******************************** int dollars = (int)numberAmount; int cents = (int)(Math.round((numberAmount - dollars)*100)); //****break it apart further:***** int hundredsDigit = (dollars % 1000) / 100; int tensDigit = (dollars % 100) / 10; int onesDigit = dollars % 10; //****output values to screen:**** System.out.println( "dollars: " + dollars + " cents: " + cents + " hundredsDigit: " + hundredsDigit + " tensDigit: " + tensDigit + " onesDigit: " + onesDigit ); } }
- simple golf game: Welcome to Emerald Lakes Golf Club! You are 463m away from the hole. Please choose a club: A) Driver: 200m - 250m B) 5-Iron: 140m - 180m C) Sand Wedge: 30m - 100m D) Putter: 1m - 15m [>>A] You have chosen the Driver. You hit the ball 234m You are 229m away from the hole. Please choose a club: etc. randomize shot lengths
- Higher / lower. The computer picks a number between 1 and 10. I (the user) get 3 guesses. On each incorrect guess, the computer tells me if my guess was higher / lower than original number. After 3 guesses the computer tells me what the number was. Alternatively if I guess correctly, the computer tells me how many guesses it took me. I then get an option to play again or exit. Challenges: Give the user the option to set the variables in the game at run time – numOfGuessesAllowed, rangeMaxNum, rangeMinNum. Add new variables to keep track of: gamesPlayed, timesSolved, timesFailed, quickestFind
- Naughts and crosses The game board is represented by three lines of text:
123
456
789
Player “X” goes first:
X23
456
789
Player “O” goes next:
X23
4O6
789
The game continues until all 9 squares are filled. Challenges: Make Player “O” a computer player (so randomise their move). Make it check for “3 in a row” after each go, and display the winner if there is 3 in a row
helpimport java.util.*; public class noughtsAndCrosses{ public static String[][] board = new String[][]{{"1","2","3"},{"4","5","6"},{"7","8","9"}}; public static boolean isSpaceTaken(int pick, String marking){ switch(pick){ case 1: if(board[0][0].equals("1")) {board[0][0] = marking; return true;} break; case 2: if(board[0][1].equals("2")) {board[0][1] = marking; return true;} break; case 3: if(board[0][2].equals("3")) {board[0][2] = marking; return true;} break; case 4: if(board[1][0].equals("4")) {board[1][0] = marking; return true;} break; case 5: if(board[1][1].equals("5")) {board[1][1] = marking; return true;} break; case 6: if(board[1][2].equals("6")) {board[1][2] = marking; return true;} break; case 7: if(board[2][0].equals("7")) {board[2][0] = marking; return true;} break; case 8: if(board[2][1].equals("8")) {board[2][1] = marking; return true;} break; case 9: if(board[2][2].equals("9")) {board[2][2] = marking; return true;} break; } return false; //if there is X or O } public static int inputUserPick(){ Scanner pick = new Scanner(System.in); System.out.println("Pick a number:"); return Integer.valueOf(pick.nextLine()); } public static void outputStateOfBoard(){ for(int column=0; column<=2; column++) { System.out.println(""); //lineBreak for(int row=0; row<=2; row++) { System.out.print(board[column][row]); } } System.out.println(""); //lineBreak } public static boolean determineWinners(String marking){ if(checkIfThereIsThreeInARow() ) { outputStateOfBoard(); System.out.println(marking + " wins."); return true; } else return false; } public static boolean checkIfThereIsThreeInARow(){ for(int line=0; line<=2; line++) { //rows: if(board[line][0].equals(board[line][1]) && board[line][1].equals(board[line][2])) {return true;} //columns: if(board[0][line].equals(board[1][line]) && board[1][line].equals(board[2][line])) {return true;} //both diags: if(board[0][0].equals(board[1][1]) && board[1][1].equals(board[2][2])) {return true;} if(board[2][0].equals(board[1][1]) && board[1][1].equals(board[0][2])) {return true;} } return false; //no winners yet } public static void main(String[] args){ boolean winningThree = false; while(!winningThree){ outputStateOfBoard(); if(isSpaceTaken(inputUserPick(),"X")==false){ System.out.println("You can't take their SPOT!"); } else { if(determineWinners("X")){ winningThree = true; } else { Random seed = new Random(); int cpuGuess = 0; do{ cpuGuess = seed.nextInt(9) + 1; }while(!isSpaceTaken(cpuGuess,"O")); //****THIS WILL INFINITE LOOP CPUGUESS ON A FULL BOARD / DRAWN GAME - FIX??**** if(determineWinners("O")){ winningThree = true; } } } }//end while(!winningThree) }//end main }//end noughtsAndCrosses
- card deck: create an OOP class for a deck of cards with the methods shuffle() and drawOneCard(). also create a constructor that populates the deck.
help - deck classimport java.util.*; public class Deck { public class singleCard{ public String title; //Seven public String suit; //Hearts public int weight; //7 - could be used in-game } public singleCard[] cards = new singleCard[52]; //constructor: public Deck(){ fillDeck(); } private void fillDeck() { int suitCounter = 0; for(int number=0; number<52; number++){ cards[number] = new singleCard(); //***************SUITS************** switch(suitCounter) { case 0: cards[number].suit = "spades"; break; case 1: cards[number].suit = "diamonds"; break; case 2: cards[number].suit = "clubs"; break; case 3: cards[number].suit = "hearts"; suitCounter = -1; break; } suitCounter++; //*******TITLE && WEIGHT************ switch(number) { case 0: case 1: case 2: case 3: cards[number].title = "Two"; cards[number].weight = 2; break; case 4: case 5: case 6: case 7: cards[number].title = "Three"; cards[number].weight = 3; break; case 8: case 9: case 10: case 11: cards[number].title = "Four"; cards[number].weight = 4; break; case 12: case 13: case 14: case 15: cards[number].title = "Five"; cards[number].weight = 5; break; case 16: case 17: case 18: case 19: cards[number].title = "Six"; cards[number].weight = 6; break; case 20: case 21: case 22: case 23: cards[number].title = "Seven"; cards[number].weight = 7; break; case 24: case 25: case 26: case 27: cards[number].title = "Eight"; cards[number].weight = 8; break; case 28: case 29: case 30: case 31: cards[number].title = "Nine"; cards[number].weight = 9; break; case 32: case 33: case 34: case 35: cards[number].title = "Ten"; cards[number].weight = 10; break; case 36: case 37: case 38: case 39: cards[number].title = "Jack"; cards[number].weight = 10; break; case 40: case 41: case 42: case 43: cards[number].title = "Queen"; cards[number].weight = 10; break; case 44: case 45: case 46: case 47: cards[number].title = "King"; cards[number].weight = 10; break; case 48: case 49: case 50: case 51: cards[number].title = "Ace"; cards[number].weight = 11; break; } } } public void shuffle(){ Random seed = new Random(); singleCard[] dupeCards = (singleCard[]) cards.clone(); for(int number=52; number>=1; number--) { int numbersLeft = seed.nextInt(number); cards[number-1] = dupeCards[numbersLeft]; dupeCards[numbersLeft] = dupeCards[number-1]; } } }
//save as cardGame.java public class cardGame { public static void main(String[] args) { Deck myDeck = new Deck(); myDeck.shuffle(); for(int counter=0; counter<52; counter++) { String cardTitle = myDeck.cards[counter].title; String cardSuit = myDeck.cards[counter].suit; int cardWeight = myDeck.cards[counter].weight; System.out.println(cardTitle + " of " + cardSuit); } } }
- add the variable health to the Player class in the Object Oriented Programming examples. set it to 100 when an object of the class is instantiated (which means created). add the methods gainHealth(int amt) and loseHealth(int amt) to the class. write code for these, where amt is the amount of health i gain / lose.
- Finish the game of battleships from the multi-dimensional array examples. challenge: do it with methods (so make it modular, which means keep the main method short). epic mlg challenge: do it using object oriented programming techniques
- Write an algorithm and program that inputs 5 numbers and calculates the average help