Skip to content

Commit

Permalink
added exercises
Browse files Browse the repository at this point in the history
  • Loading branch information
justinmusgrove committed Apr 27, 2014
1 parent a03d3c7 commit 305946e
Show file tree
Hide file tree
Showing 7 changed files with 407 additions and 0 deletions.
66 changes: 66 additions & 0 deletions src/main/java/com/levelup/java/exercises/beginner/BarChart.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.levelup.java.exercises.beginner;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
* This java example will demonstrate solution for bar chart exercise.
*
* @author Justin Musgrove
* @see <a href='http://www.leveluplunch.com/java/exercises/bar-chart/'>Bar
* chart</a>
*/
public class BarChart {

static int CHAR_PER_SALE = 100;

public static void main(String[] args) {

double sales;
List<Double> storeSales = new ArrayList<>();

// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);

do {
// ask user for input
System.out.print("Enter today's sales for store 1: ");
sales = keyboard.nextDouble();

// add input to collection
storeSales.add(new Double(sales));

} while (sales != -1);

// close scanner
keyboard.close();

// Display the bar chart heading.
System.out.println("\nSALES BAR CHART");

// Display chart bars
for (Double sale : storeSales) {
System.out.println("Store:" + getBar(sale));
}
}

/**
* Method should return the number of chars to make up the bar in the chart.
*
* @param sales
* @return
*/
static String getBar(double sales) {

int numberOfChars = (int) (sales / CHAR_PER_SALE);

StringBuffer buffer = new StringBuffer();
for (int i = 0; i < numberOfChars; i++) {
buffer.append("*");
}

return buffer.toString();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.levelup.java.exercises.beginner;

import java.text.DecimalFormat;
import java.util.Scanner;

/**
* This java example will demonstrate a solution to the budget analysis problem.
*
* @author Justin Musgrove
* @see <a href='http://www.leveluplunch.com/java/exercises/budget-analysis/'>Budget analysis</a>
*/
public class BudgetAnalysis {

public static void main(String[] args) {

// Create a DecimalFormat object to format output.
DecimalFormat dollar = new DecimalFormat("#,##0.00");

// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);

// Get the budget amount.
System.out.print("Enter your budget for the month: ");
double monthlyBudget = keyboard.nextDouble();

// Get each expense, keep track of total.
double expense;
double totalExpenses = 0.0;
do {
// Get an expense amount.
System.out.print("Enter an expense, or a negative "
+ "number to quit: ");
expense = keyboard.nextDouble();

totalExpenses += expense;

} while (expense >= 0);

// Display the amount after expenses.
double balance = calculateAmountOverBudget(monthlyBudget, totalExpenses);
if (balance < 0) {
System.out.println("You are OVER budget by $"
+ dollar.format(Math.abs(balance)));
} else if (balance > 0) {
System.out.println("You are UNDER budget by $"
+ dollar.format(balance));
} else {
System.out.println("You spent the budget amount exactly.");
}

keyboard.close();
}

static double calculateAmountOverBudget(double monthlyBudget,
double totalExpenses) {
return monthlyBudget - totalExpenses;
}

}
79 changes: 79 additions & 0 deletions src/main/java/com/levelup/java/exercises/beginner/ESPGame.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package com.levelup.java.exercises.beginner;

import java.util.List;
import java.util.OptionalInt;
import java.util.Random;
import java.util.Scanner;

import com.google.common.collect.Lists;

/**
* This java exercise shows a solution for the ESP question.
*
* @author Justin Musgrove
* @see <a href='http://www.leveluplunch.com/java/exercises/esp-game/'>ESP game</a>
*/
public class ESPGame {

static List<String> choices = Lists.newArrayList("red", "green", "orange", "blue", "yellow");

public static void main(String[] args) {

int correctGuesses = 0;

String input;
Scanner keyboard = new Scanner(System.in);

// join list for display
String colors = String.join(", ", choices);

// Play the game for 10 rounds.
for (int round = 1; round <= 10; round++) {

System.out.print("I'm thinking of a color " + colors + ":");

input = keyboard.next();

while (!isValidChoice(input)) {
System.out.print("Please enter " + colors + ":");
input = keyboard.next();
}

if (computerChoice().equalsIgnoreCase(input)) {
correctGuesses ++;
}
}

//close scanner
keyboard.close();

// show output
System.out.println("Number of correct guesses: " + correctGuesses);
}

/**
* Method should return computer choice
*
* @return color
*/
static String computerChoice() {
Random random = new Random();
OptionalInt computerChoice = random.ints(0, choices.size() - 1).findFirst();

return choices.get(computerChoice.getAsInt());
}

/**
* Check if input is contained within list
*
* @param input
* @return
*/
static boolean isValidChoice(String input) {

java.util.Optional<String> val = choices.stream()
.filter(e -> e.equals(input.toLowerCase())).findAny();

return val.isPresent();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.levelup.java.exercises.beginner;

import java.util.Scanner;

/**
* This java exercises will solve for the square display problem.
*
* @author Justin Musgrove
* @see <a href='http://www.leveluplunch.com/java/exercises/square-display-asterisk/'>Square display</a>
*
*/
public class SquareDisplay {

public static void main(String[] args) {

// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);

// Get a number from the user.
System.out.print("Enter a number between 1-15: ");
int number = keyboard.nextInt();

//validate users input
validateNumber(keyboard, number);

//produce matrix
outputMatrix("X", number);

//close scanner
keyboard.close();

}

/**
* Method should validate a input number and continue to ask if the number
* is now within range
*
* @param keyboard
* @param number
*/
static void validateNumber(Scanner keyboard, int number) {

// Validate the input.
while (number < 1 || number > 15) {
// Get a number from the user.
System.out.println("Sorry, that's an invalid number.");
System.out.print("Enter an integer in the range of 1-15: ");
number = keyboard.nextInt();
}
}

/**
* Method should output a row/column of char specified
*
* @param charToOutput
* @param number
*/
static void outputMatrix(String charToOutput, int number) {

// display square made of char
for (int row = 0; row < number; row++) {

// display row
for (int column = 0; column < number; column++) {
System.out.print(charToOutput);
}

// Advance to the next line.
System.out.println();
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.levelup.java.exercises.beginner;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

/**
* This java example will demonstrate a solution for the upper case file
* converter exercise.
*
* @author Justin Musgrove
* @see <a href=
* 'http://www.leveluplunch.com/java/exercises/uppercase-file-converter/'>Uppercase
* File Converter</a>
*/
public class UppercaseFileConverter {

public static void main(String[] args) throws IOException,
URISyntaxException {

// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);

// Ask user for file name
System.out.print("Enter the input file name: ");
String fileToRead = keyboard.nextLine();

// Ask user for output file name
System.out.print("Enter the output file name: ");
String outputFileName = keyboard.nextLine();

// Find the path of file in class path
String fileLocation = getFileLocation(fileToRead);

// read all lines into file
Path inputPath = Paths.get(fileLocation);
List<String> fileLines = java.nio.file.Files.readAllLines(inputPath);

// iterate each line in file calling toUpperCase
// using java 8 streams
List<String> linesToUpperCase = fileLines.stream()
.map(s -> s.toUpperCase()).collect(Collectors.toList());

// write to file
Path outputPath = Paths.get(outputFileName);
java.nio.file.Files.write(outputPath, linesToUpperCase,
StandardOpenOption.CREATE, StandardOpenOption.WRITE);

keyboard.close();
}

/**
* Method will just return the location of the file in the class path
*
* @param fileName
* @return
*/
static String getFileLocation(String fileName) {
return UppercaseFileConverter.class.getResource(fileName).getPath();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.levelup.java.exercises.beginner;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
* Unit test for {@link BarChart}
*
* @author Justin Musgrove
* @see <a href='http://www.leveluplunch.com/java/exercises/bar-chart/'>Bar chart</a>
*
*/

public class BarChartTest {

@Test
public void chart_length() {

String chars = BarChart.getBar(1000);

assertTrue(chars.length() == 10);
}

}
Loading

0 comments on commit 305946e

Please sign in to comment.