You are given a text file (customer.txt) in which name, lastname and age of customers are stored:
Ali Aslan 25
Ayse Demir 35
Ahmet Gemici 17 .
.
.
You should process this file and find number of customers for each of the following ranges:
0 - 19
20 - 59
60 -
This is my code:
import java.io.*;
import java.util.*;
public class ass11 {
public static void main(String[] args) {
Scanner inputStream = null;
try {
inputStream = new Scanner(new FileInputStream("customer.txt"));
}
catch (FileNotFoundException e) {
System.out.println("file customer.txt not found");
System.exit(0);
}
int next, x = 0, y = 0, z = 0, sum = 0;
while(inputStream.hasNextInt()) {
next = inputStream.nextInt();
sum = sum + next;
if (next >= 60)
x++;
else if (next >= 19 && next <= 59)
y++;
else
z++;
}
inputStream.close();
System.out.println(x + " customer bigger than 60");
System.out.println(y + " customer between 19 and 59");
System.out.println(z + " customers smaller then 19");
}
}
It reads only numbers. When I write a name and surname to the text file, it doesn't work and I don't use the split() method...
I would recommend testing with the original file:
Ali Aslan 25
Ayse Demir 35
Ahmet Gemici 17
Each line is a name plus age, so you would get a code like:
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("path/to/file" ), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
String[] contents = line.split(" ");
// Assume contents is 3 long: name, surname, age
System.out.printf("%s %s is %d", contents[0], contents[1], Integer.parseInt(contents[2]));
}
Yes, this does make use of the split method, which makes it easier in my opinion. You could also use the Scanner by calling it in a loop with next(), next() and nextInt()
Try this code. It works.
import java.io.BufferedReader;
import java.io.FileReader;
public class MyProject {
public static void main(String [] args){
String path = "C:/temp/stack/scores.txt";
processTextFile(path);
}
public static void processTextFile(String filePath) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filePath));
String line = br.readLine();
String [] tokens = null;
int score = 0;
int x = 0;
int y = 0;
int z = 0;
while (line != null) {
tokens = line.split(" ");
score = Integer.parseInt(tokens[tokens.length -1]);
if(score >= 0 && score < 20){
x++;
}
if(score >= 20 && score < 60){
y++;
}
if(score > 60){
z++;
}
line = br.readLine();
}
if (br != null) {
br.close();
}
System.out.println("0-20 = " + x + ", 20-60 = " + y + ", 60+ = " + z);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Related
my program is a recreation of the game mastermind. I am trying to protect against an error when you enter three or less characters instead of the required four, but my try/catch just... isn't doing anything. Please help
/*
* AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
* AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
*/
package nowornever;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
import java.util.Scanner;
/**
*
* #author KK
*/
public class NowOrNever {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String code[] = new String[4];
String guessNum[] = new String[4];
String hint[] = new String[4];
String line;
String guess = null;
try {//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------PREVIOUS MATCH CLEAR
PrintWriter pw = new PrintWriter(new FileWriter("LastMatch.txt"));
pw.print("");
pw.close();
} catch (IOException ioe) {
System.err.println("Problem opening / writing to file");
}
int menu = Integer.parseInt(JOptionPane.showInputDialog("Would you like to read the rules? \n Enter 1 for yes or 2 for No."));
if (menu == 1) { //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------RULES
JOptionPane.showMessageDialog(null, "The object of this game is to break a number code in six turns or less.\nHow to play:\n\n1. Enter four numbers you think could be the code, from 1 to 9.\n\n2. The machine will respond by indicating whether any of your numbers are a correct guess.\n- Correct number wrong location will be indicated with a dot '•'.\n- Correct number and correct location will be indicated with a reverse dot '◘'.\n- if both number and location are wrong, there will be a blank space' '.\n\n3. Use your logic and luck to crach the code and win the game within six tries or less!\n\nIf you play again, you can find a record of your most recent match saved in 'LastMatch.txt' in the root folder of this project.");
JOptionPane.showMessageDialog(null, " The game is starting in the output section");
} else {
JOptionPane.showMessageDialog(null, " The game is starting in the output section");
}
try { //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------MENU PREPPER
PrintWriter pw = new PrintWriter(new FileWriter("LastMatch.txt", true));
pw.println("┌─────┬─────┐");
pw.close();
} catch (IOException ioe) {
System.err.println("Problem opening / writing to file");
}
for (int count = 0; count < 4; count++) { //-----------------------------------------------------------------------------------------------------------------------------------------------------AI LOOP
double randomValue = (double) (Math.random());
if (randomValue >= 0.0 && randomValue <= 0.1111111) {
code[count] = 1 + "";
} else if (randomValue >= 0.1111111 && randomValue <= 0.2222222222) {
code[count] = 2 + "";
} else if (randomValue >= 0.2222222 && randomValue <= 0.3333333) {
code[count] = 3 + "";
} else if (randomValue >= 0.33333333 && randomValue <= 0.44444444) {
code[count] = 4 + "";
} else if (randomValue >= 0.44444444 && randomValue <= 0.555555555) {
code[count] = 5 + "";
} else if (randomValue >= 0.55555 && randomValue <= 0.66666666) {
code[count] = 6 + "";
} else if (randomValue >= 0.6666666666 && randomValue <= 0.777777777) {
code[count] = 7 + "";
} else if (randomValue >= 0.777777777 && randomValue <= 0.88888888) {
code[count] = 8 + "";
} else if (randomValue >= 0.88888888 && randomValue <= 1) {
code[count] = 9 + "";
} else {
System.out.println("Issue with generating code; please try again.");
//System.exit(0);
}
}
for (int count = 0; count < 6; count++) { //-------------------------------------------------------------------------------------------------------------------------------------------BEGINNING OF PROCESSING LOOP
try {//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------INPUT TRY/CATCH
System.out.println("Please enter your guess of four numbers from 1-9. Please do not include spaces in your submission.");
guess = input.nextLine();
} catch(StringIndexOutOfBoundsException siobe){
System.out.println("Please enter four numbers");
}
if (guess.contains(" ")) { //-----------------------------------------------------------------------------------------------------------------------------------------------------------SPACE CHECKER
JOptionPane.showMessageDialog(null, "Try again, and Please do not enter spaces in between the characters.");
System.exit(0);
}
for (int countInternal = 0; countInternal < 4; countInternal++) { //-----------------------------------------------------------------------------------------------------------------TAKING GUESS APART
guessNum[countInternal] = guess.substring(countInternal, countInternal + 1);
}
if (guessNum[0].equals(code[0])) {//--------------------------------------------------------------------------------------------------------------------------------------------------CORRECT CHECKER 1
hint[0] = "◘";
} else if (guessNum[0].equals(code[1])) {
hint[0] = "•";
} else if (guessNum[0].equals(code[2])) {
hint[0] = "•";
} else if (guessNum[0].equals(code[3])) {
hint[0] = "•";
} else {
hint[0] = " ";
}
if (guessNum[1].equals(code[1])) {//--------------------------------------------------------------------------------------------------------------------------------------------------CORRECT CHECKER 2
hint[1] = "◘";
} else if (guessNum[1].equals(code[2])) {
hint[1] = "•";
} else if (guessNum[1].equals(code[3])) {
hint[1] = "•";
} else if (guessNum[1].equals(code[0])) {
hint[1] = "•";
} else {
hint[1] = " ";
}
if (guessNum[2].equals(code[2])) {//--------------------------------------------------------------------------------------------------------------------------------------------------CORRECT CHECKER 3
hint[2] = "◘";
} else if (guessNum[2].equals(code[3])) {
hint[2] = "•";
} else if (guessNum[2].equals(code[0])) {
hint[2] = "•";
} else if (guessNum[2].equals(code[1])) {
hint[2] = "•";
} else {
hint[2] = " ";
}
if (guessNum[3].equals(code[3])) {//--------------------------------------------------------------------------------------------------------------------------------------------------CORRECT CHECKER 4
hint[3] = "◘";
} else if (guessNum[3].equals(code[0])) {
hint[3] = "•";
} else if (guessNum[3].equals(code[1])) {
hint[3] = "•";
} else if (guessNum[3].equals(code[2])) {
hint[3] = "•";
} else {
hint[3] = " ";
}
try {//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------PLAYER INPUT LINE PRINT
PrintWriter pw = new PrintWriter(new FileWriter("LastMatch.txt", true));
pw.println("│" + guessNum[0] + guessNum[1] + guessNum[2] + guessNum[3] + "│" + hint[0] + hint[1] + hint[2] + hint[3] + "│");
pw.close();
} catch (IOException ioe) {
System.err.println("Problem opening / writing to file");
}
try {//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------PLAYER INPUT LINE READ
BufferedReader br = new BufferedReader(new FileReader("LastMatch.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException ioe) {
System.err.println("Error reading from file");
}
if (guessNum[0].equals(code[0]) && guessNum[1].equals(code[1]) && guessNum[2].equals(code[2]) && guessNum[3].equals(code[3])) {//------------------------------------------------------WIN CONDITION
count = 6;
System.out.println("You Win!");
}
} //-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------END OF ENTERING AND PRCESSING LOOP
System.out.println("Game Over!");
try {
PrintWriter pw = new PrintWriter(new FileWriter("LastMatch.txt", true));
pw.println("└─────┴─────┘");
pw.close();
} catch (IOException ioe) {
System.err.println("Problem opening / writing to file");
}
System.out.println("Final Game Board:");
try {
BufferedReader br = new BufferedReader(new FileReader("LastMatch.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException ioe) {
System.err.println("Error reading from file");
}
try {//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------PLAYER INPUT LINE PRINT
PrintWriter pw = new PrintWriter(new FileWriter("LastMatch.txt", true));
pw.println("The code was:" + code[0] + code[1] + code[2] + code[3]);
pw.close();
} catch (IOException ioe) {
System.err.println("Problem opening / writing to file");
}
}
}
StringIndexOutOfBoundsException occurs when you try to access the character index which doesn't exists. e.g. String length is 3 and you are trying to access str.charAt(4) etc.
In your program, (which I believe isn't having the most optimum solution but respecting your logic), should handle it at below lines and not while taking input from user.
try {
guessNum[countInternal] = guess.substring(countInternal, countInternal + 1);
} catch(StringIndexOutOfBoundsException siobe){
System.out.println("Error");
}
Better solution would be, while taking the input, check length of a string
while(true) {
System.out.println("Please enter your guess of four numbers from 1-9. Please do not include spaces in your submission.");
guess = input.nextLine();
if(guess.length()==4) {
break;
}else{
System.out.println("Please enter four numbers");
}
}
The line that is currently wrapped inside your try block is guess = input.nextLine(); which will never throw a StringIndexOutOfBoundsException, rather the error is caused by using substring with an out of bounds index here guess.substring(countInternal, countInternal + 1);.
To make the exception work correctly you need to wrap the entire code block including the substring code inside the try bracers like the following, however, we also need to use a while loop to get the inputs if the exception is caught:
//We need to wrap any code that can have multiple attempts inside a while loop
//Variable to control the while loop
boolean waiting = true;
//Loop to get 4 inputs
while (waiting)
{
System.out.println("Please enter your guess of four numbers from 1-9. Please do not include spaces in your submission.");
guess = input.nextLine();
//Remove any spaces in the guess
guess = guess.replaceAll(" ", "");
try {
//Process the input INSIDE the try block
for (int countInternal = 0; countInternal < 4; countInternal++) {
guessNum[countInternal] = guess.substring(countInternal, countInternal + 1);
}
//Success, if the code reached here then no errors were thrown, and we can change the flag so that the loop stops after this cycle
waiting = false;
}
catch(StringIndexOutOfBoundsException siobe){
System.out.println("Please enter four numbers");
//Move to the next loop cycle and skip all code below
continue;
}
}
//Put code here to be done after storing the 4 inputs in guessNum
//...
However, the above is not a good solution, we should never rely on a try/catch block to run our code, rather we should work with absolute values. For example, we can use an if statement inside a while loop to check the length of the input. As before we need to wrap any code that can have multiple attempts inside a while loop:
//Variable to control the while loop
boolean waiting = true;
//Loop to get 4 inputs
while (waiting)
{
System.out.println("Please enter your guess of four numbers from 1-9. Please do not include spaces in your submission.");
guess = input.nextLine();
//Remove any spaces in the guess
guess = guess.replaceAll(" ", "");
if(guess.length() < 4)
{
System.out.println("Please enter four numbers");
//Do this: Move to the next loop cycle and skip all code below
continue;
}
//Or do this: Put any following code in an else block so that it is not exected unless the length is over 4
else {
//Success, change the flag so that the loop stops after this cycle
waiting = false;
//Process the input
for (int countInternal = 0; countInternal < 4; countInternal++) {
guessNum[countInternal] = guess.substring(countInternal, countInternal + 1);
}
}
}
//Put code here to be done after storing the 4 inputs in guessNum
//...
I am little confused about how I can format my output cleanly like the output given below:
My code:
import java.io.*;
import java.util.Scanner;
public class CountChar {
public static void main(String[] args) {
File file = new File("test1.txt");
BufferedReader reader = null;
int numCount = 0;
int otherCount = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please specify the # of intervals: ");
int N = sc.nextInt();
while (true) {
if (N == 2 || N == 4 || N == 5 || N == 10) {
break;
} else {
System.out.println("Your input is not supported, please choose another value: ");
N = sc.nextInt();
}
}
int interval_at = 100 / N;
int[] histogram = new int[N];
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
int num = 0;
try {
num = Integer.parseInt(text);
if (num > 0 && num <= 100) {
numCount++;
int inRange = (num - 1) / interval_at;
histogram[inRange] = histogram[inRange] + 1;
} else {
otherCount++;
}
} catch (NumberFormatException e) {
otherCount++;
continue;
}
}
// creating a file in which the output is stored
File myObj = new File("result1.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
// Writting in a file
FileWriter myWriter = new FileWriter("result1.txt");
myWriter.write("Please specify the # of intervals: ");
myWriter.write("\n" + N);
myWriter.write("\nNumber of integers in the interval [1,100]: " + numCount);
myWriter.write("\nOthers: " + otherCount);
for (int i = 0; i < N; i++) {
myWriter.write("\n" + ((i * interval_at) + 1) + " - " + ((i + 1) * interval_at) + " | ");
for (int j = 0; j < histogram[i]; j++) {
myWriter.write("*");
}
}
myWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
My code output:
1 - 25 | ****************
26 - 50 | *******************
51 - 75 | ***********************
76 - 100 | **********************
I need to format my output as given in the picture above.
I am new to java and I was given 3 files but I do not know how to compile them to get them to work together.
Here are the files:
GetBurnRate.java
import java.io.*;
public class GetBurnRate{
public static void main(String[] args){
//Send welcome message
System.out.println("#Welcome to Lunar Lander");
try{
//Begin reading from System input
BufferedReader inputReader =
new BufferedReader(new InputStreamReader(System.in));
//Set initial burn rate to 0
int burnRate = 0;
do{
//Prompt user
System.out.println("#Enter burn rate or <0 to quit:");
//Read user response
try{
String burnRateString = inputReader.readLine();
burnRate = Integer.parseInt(burnRateString);
//Send user-supplied burn rate to next filter
System.out.println("%" + burnRate);
} catch(NumberFormatException nfe){
System.out.println("#Invalid burn rate.");
}
}
while(burnRate >= 0);
inputReader.close();
} catch(IOException ioe){
ioe.printStackTrace();
}
}
}
CalcNewValues.java
import java.io.*;
public class CalcNewValues{
public static void main(String[] args){
//Initialize values
final int GRAVITY = 2;
int altitude = 1000;
int fuel = 500;
int velocity = 70;
int time = 0;
try{
BufferedReader inputReader = new
BufferedReader(new InputStreamReader(System.in));
//Print initial values
System.out.println("%a" + altitude);
System.out.println("%f" + fuel);
System.out.println("%v" + velocity);
System.out.println("%t" + time);
String inputLine = null;
do{
inputLine = inputReader.readLine();
if((inputLine != null) &&
(inputLine.length() > 0)){
if(inputLine.startsWith("#")){
//This is a status line of text, and
//should be passed down the pipeline
System.out.println(inputLine);
}
else if(inputLine.startsWith("%")){
//This is an input burn rate
try{
int burnRate =
Integer.parseInt(inputLine.substring(1));
if(altitude <= 0){
System.out.println("#The game is over.");
}
else if(burnRate > fuel){
System.out.println("#Sorry, you don't" +
"have that much fuel.");
}
else{
//Calculate new application state
time = time + 1;
altitude = altitude - velocity;
velocity = ((velocity + GRAVITY) * 10 -
burnRate * 2) / 10;
fuel = fuel - burnRate;
if(altitude <= 0){
altitude = 0;
if(velocity <= 5){
System.out.println("#You have" +
"landed safely.");
}
else{
System.out.println("#You have" +
"crashed.");
}
}
}
//Print new values
System.out.println("%a" + altitude);
System.out.println("%f" + fuel);
System.out.println("%v" + velocity);
System.out.println("%t" + time);
}
catch(NumberFormatException nfe){
}
}
}
}
while((inputLine != null) && (altitude > 0));
inputReader.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
DisplayValues.java
import java.io.*;
public class DisplayValues{
public static void main(String[] args){
try{
BufferedReader inputReader = new
BufferedReader(new InputStreamReader(System.in));
String inputLine = null;
do{
inputLine = inputReader.readLine();
if((inputLine != null) &&
(inputLine.length() > 0)){
if(inputLine.startsWith("#")){
//This is a status line of text, and
//should be passed down the pipeline with
//the pound-sign stripped off
System.out.println(inputLine.substring(1));
}
else if(inputLine.startsWith("%")){
//This is a value to display
if(inputLine.length() > 1){
try{
char valueType = inputLine.charAt(1);
int value =
Integer.parseInt(inputLine.substring(2));
switch(valueType){
case 'a':
System.out.println("Altitude: " +
value);
break;
case 'f':
System.out.println("Fuel remaining: " +
value);
break;
case 'v':
System.out.println("Current Velocity: "
+ value);
break;
case 't':
System.out.println("Time elapsed: " +
value);
break;
}
}
catch(NumberFormatException nfe){
}
}
}
}
}
while(inputLine != null);
inputReader.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
Then I am supposed to change GetCalcNewValues.java and translate it to C++ and get it to run as so:
|GetBurnRate.java | GetCalcNewValues.cpp | DisplayValues.java
I only need to know how to properly compiler these, I can do the translation.
To compile a java program with main file GetBurnRate.java type the following into a console (You will need a java compiler installed)
javac GetBurnRate.java
To compile a c++ program you will need a c++ compile installed such as gcc or clang.
For gcc type the following into a console
g++ GetCalcNewValues.cpp -o GetCalcNewValues.exe
For clang
clang++ GetCalcNewValues.cpp -o GetCalcNewValues.exe
If you aren't using windows the file extension for the compiled c++ program probably won't be exe.
To run the programs giving the output from the first as the input to the next use
java GetBurnRate | GetCalcNewValues | java DisplayValues
I have the textfile as follow, it has 2 section PLUS and MINUS and 2 question in each section. I would want to write a program to solve them. I attached my code below as I could not get to the MINUS potion. The result I got for Minus is still using Plus operator.
math.txt
[Plus]
Question = 0
num1 = 2
num2 = 3
Question = 1
num1 = 4
num2 = 5
[Minus]
Question = 0
num2 = 6
num1 = 5
Question = 1
num2 = 7
num1 = 2
CODE
:
BufferedReader in = null;
InputStream fis;
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" = ");
if (file_Array[0].equalsIgnoreCase("num1")) {
num1 = file_Array[1];
} else if (file_Array[0].equalsIgnoreCase("num2")) {
num2 = file_Array[1];
int sum = Integer.parseInt(num1) + Integer.parseInt(num2);
System.out.println("Answer :" + sum);
}
else if (file_Array[0].equalsIgnoreCase("[Minus]")) {
if (file_Array[0].equalsIgnoreCase("num2")) {
num2 = file_Array[1];
} else if (file_Array[0].equalsIgnoreCase("num1")) {
num1 = file_Array[1];
int minus = Integer.parseInt(num2) - Integer.parseInt(num1);
System.out.println("Answer :" + minus);
}
}
}
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
}
My solution is as below :
public static void main(String arg[]) {
BufferedReader in = null;
InputStream fis;
String file = "math.txt";
try {
fis = new FileInputStream(file);
in = new BufferedReader(new InputStreamReader(fis));
String line = null;
String section=null;
String num1 = null;
String num2 = null;
while ((line = in.readLine()) != null) {
String[] file_Array = line.split(" = ");
if (file_Array[0].equalsIgnoreCase("[Minus]"))
{
section="Minus";
}
if (file_Array[0].equalsIgnoreCase("[Plus]"))
{
section="Plus";
}
if (file_Array[0].equalsIgnoreCase("num1")) {
num1 = file_Array[1];
} else if (file_Array[0].equalsIgnoreCase("num2")) {
num2 = file_Array[1];
}
//Solution depends on the fact that there will be a blank line
//after operands.
if (file_Array[0].equals("")){
printResult(section,num1,num2);
}
}
//There is no blank line at the end of the file, so call printResult again.
printResult(section,num1,num2);
} catch (IOException ex) {
System.out.println("Input file " + file + " not found");
}
}
private static void printResult(String section,String num1,String num2) {
if (section.equals("Minus")){
int minus = Integer.parseInt(num2) - Integer.parseInt(num1);
System.out.println("Answer :" + minus);
}
if (section.equals("Plus")){
int sum = Integer.parseInt(num1) + Integer.parseInt(num2);
System.out.println("Answer :" + sum);
}
}
I'm having diffuculties with sorting the input i want it to sort by lowest time first. I'm new to java so i dont know so much I've done a guees a number game but I cant manage to sort the highscore by lowest time here is what i've done so far.
import java.io.*;
import java.util.*;
public class teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeest {
private static void start() throws IOException {
int number = (int) (Math.random() * 1001);
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
String scorefile = "p-lista_java";
int försök = 0;
int gissning = 0;
String namn;
String line = null;
String y;
String n;
String val ;
String quit = "quit";
System.out.println("Hello and welcome to this guessing game" +
"\nStart guessing it's a number between 1 and 1000:");
long startTime = System.currentTimeMillis();
while (true){
System.out.print("\nEnter your guess: ");
gissning = input.nextInt();
försök++;
if (gissning == number ){
long endTime = System.currentTimeMillis();
long gameTime = endTime - startTime;
System.out.println("Yes, the number is " + number +
"\nYou got it after " + försök + " guesses " + " times in " + (int)(gameTime/1000) + " seconds.");
System.out.print("Please enter your name: ");
namn = reader.readLine();
try {
BufferedWriter outfile
= new BufferedWriter(new FileWriter(scorefile, true));
outfile.write(namn + " " + försök +"\t" + (int)(gameTime/1000) + "\n");
outfile.close();
} catch (IOException exception) {
}
break;
}
if( gissning < 1 || gissning > 1000 ){
System.out.println("Stupid guess! I wont count that..." );
--försök;
}
else if (gissning > number)
System.out.println(" Your guess is too high");
else
System.out.println("Your guess is too low");
}
try {
BufferedReader infile
= new BufferedReader(new FileReader(scorefile));
while ((line = infile.readLine()) != null) {
System.out.println(line);
}
infile.close();
} catch (IOException exception) {
}
System.out.println("Do you want to continue (Y/N)?");
val=reader.readLine();
if ((val.equals("y"))||(val.equals("Y"))){
teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeest.start();
}
else
System.out.print("Thanks for playing");
System.exit(0);
}
}
Create a value object that holds all your scoring, time and other details. Create a Comparator that compares the components between two of these holders. The sorting can be achieved by creating a Set of Holder with a Comparator.
If you wish to sort by other properties in a different order simply update the Comparator as appropriate.
Holder {
long time;
int score;
String name;
}
Comparator<Holder> {
int compare( Holder holder, Holder other ){
int result = holder.time - other.time;
if( 0 == result ){
result = holder.score - other.score;
}
return result;
}
}