Skip to content

Instantly share code, notes, and snippets.

@desrtfx
Created March 8, 2014 17:45
Show Gist options
  • Save desrtfx/9435739 to your computer and use it in GitHub Desktop.
Save desrtfx/9435739 to your computer and use it in GitHub Desktop.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Popcorn {
public Popcorn() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws IOException {
File file = getValidFile();
// read and process the file
processFile(file);
}
// read and process the file
// generate and print the bargraph
public static void processFile(File aFile) {
Scanner scan = null;
try {
scan = new Scanner(aFile).useDelimiter("\\s*\\n");
String aLine;
while(scan.hasNextLine())
{
aLine = scan.nextLine();
int commaIndex = aLine.indexOf(',');
String farmName = aLine.substring(0, commaIndex);
String lastTwo = aLine.substring(commaIndex + 1);
lastTwo = lastTwo.trim();
String[] lastTwoArray = lastTwo.split(" ");
double acres = Double.parseDouble(lastTwoArray[0]);
int jars = Integer.parseInt(lastTwoArray[1]);
// Directly print the bargraph
printBarGraph(farmName, acres, jars);
// Alternative way:
// System.out.print(generateBarGraph(farmName, acres, jars));
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
if (scan != null) {
scan.close();
}
}
// Get and validate input
// and check if file exists
// and reprompt user if not
// If a valid filename is given, return a file object
public static File getValidFile() {
Scanner in = new Scanner(System.in);
String fileName;
File file;
// Get and validate input
// and check if file exists
// and reprompt user if not
do {
System.out.println("Error: Please enter a valid file name. ");
fileName = in.next();
file = new File(fileName);
} while (!file.isFile());
in.close();
return file;
}
// This method prints the bar graph directly
public static void printBarGraph(String name, double acres, int jars) {
System.out.print(name + "\t"); // Print the farm name followed by a tab
int stars = (int)((jars/acres)/25);
for (int i = 0; i < stars; i++) {
System.out.println("*");
}
System.out.println();
}
// This method produces a line for the bargraph
// returns a formatted String for later printing.
public static String generateBarGraph(String name, double acres, int jars) {
String tmp = name + "\t"; // Print the farm name followed by a tab
int stars = (int)((jars/acres)/25);
for (int i = 0; i < stars; i++) {
tmp = tmp + "*";
}
tmp = tmp + "\n";
return tmp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment