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
Related
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("-------Welcome to the Radius calculator-------");
String input = new String (" ");
while(input.equals("END")==false) {
for (int i = 1; i < 5; i++)
for (int e = 5; e > 0; e--)
{
{
System.out.println("-----------------------------");
System.out.println("Hey you can use this calcultor " + e + " more time(s) till yoh have to purchase our full version only 3.99");
}
System.out.println("Please enter your Radius if not just type in END at any stage during the program");
Double num =sc.nextDouble();
System.out.println("Enter 1 if you would like to get the area");
System.out.println("Enter 2 if you would like to get the circumfrence");
int num1 = sc.nextInt();
if (num1 == 1) {
System.out.println("The area of the circle with the radius " + num + " is :" + (Math.PI) * (num * num));
} else if (num1 == 2) {
System.out.println("The circumfrence of the circle with the radius " + num + " is :" + (2) * (Math.PI) * (num));
} else {
System.out.println("No answer for you boss");
System.out.println("Try again!");
}
System.out.println("You have used this calculator effiently " + i + " time(s)");
System.out.println("-----------------------------");
}
}
}
}
Heres my code it works but when i type in END an ERROR comes up.(https://i.stack.imgur.com/ZZxEW.png)](https://i.stack.imgur.com/ZZxEW.png)
If theres any othere tips to make my code for effecient would be much appriciated too.
You forgot to ask for the end input during the loops.
The best way to ask for an input of different types is to use BufferedReader Class
BufferedReader reader =new BufferedReader(newInputStreamReader(System.in));
String input = null;
try {
input = reader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
if (input.equals("END")) {
break;
}
After that you can use :
Integer.parseInt(input);
to cast from String to Integer
And don't forget to clean and simplify your code.
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
//...
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();
}
}
}
I am writing a code where a player gets to play hangman with a random word chosen from a text file. I keep getting this null pointer exception error, and I am not sure why. Sometimes when I run the program, I have no problems. But sometimes when I run, the program immediately crashes given me the null pointer exception error. Can anyone help me figure out why? Here is my code:
--Edit--
Error occurs in displayGallows method, when trying to set the variable puzzle.
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Hangman {
private Scanner in = new Scanner(System.in);
private boardPiece[] board = {new boardPiece(0),new boardPiece(0),new boardPiece(3),
new boardPiece(1),new boardPiece(2),new boardPiece(0)};
private String puzzle;
private String puzzleWord;
private int puzzleIndex;
private Random generator = new Random(System.currentTimeMillis());
private boolean win;
private boolean over;
private String correct = "";
//private String guesses = "";
private char guesses[] = new char[26];
private int guessed;
private int misses;
private String puzzles[] = new String[5];
// = {"hello world","java is cool","athena is smelly","zach is awesome","athena is cool"};
public static void main(String [] args){
String letter;
String again = "y";
Hangman game = new Hangman();
try{
BufferedReader in =
new BufferedReader(new FileReader("puzzles.txt"));
int count = 0;
while (in.ready()) { //while there is another line in the input file
game.puzzles[count] = in.readLine(); //get line of data
count++; //Increment CWID counter
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}
/*for(int x=0;x<game.puzzles.length;x++)
System.out.println("PUZZLE " + x + ": " + game.puzzles[x]);*/
System.out.println("Welcome to HangMan!");
System.out.println("To play, guess a letter to try to guess the word.");
System.out.println("Every time you choose an incorrect letter another");
System.out.println("body part appears on the gallows. If you guess the");
System.out.println("word before you're hung, you win");
System.out.println("If you get hung, you lose");
System.out.println("Time to guess...");
while(again.charAt(0) == 'y'){
game.displayGallows();
while(!game.over){
game.printBoard();
//System.out.println("Guessed: " + game.guesses);
game.printLettersGuessed();
System.out.println("The word so far: " + game.puzzle);
System.out.println("Choose a letter: ");
letter = game.in.next();
//game.guesses = game.guesses + " " + letter.charAt(0);
game.guesses[game.guessed] = letter.charAt(0);
game.guessed++;
game.sort();
if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
game.correct = game.correct + letter.charAt(0);
game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
game.win = true;
game.over = true;
}
}
else
game.PrintWrongGuesses();
}
game.printBoard();
System.out.println("Solution: " + game.puzzleWord);
if(game.win)
System.out.println("Congratulations! You've solved the puzzle!");
else
System.out.println("You failed, failer!");
System.out.println();
System.out.println("Congratulations, you win!");
System.out.println("Do you want to play again? (y/n)");
again = game.in.next();
}
System.out.println("Goodbye!");
}
public void displayGallows(){
win = false;
over = false;
board[0].piece = " ______ ";
board[1].piece = " | | ";
board[2].piece = " | ";
board[3].piece = " | ";
board[4].piece = " | ";
board[5].piece = " _______| ";
puzzleIndex = generator.nextInt(puzzles.length);
puzzleWord = puzzles[puzzleIndex];
puzzle = puzzleWord.replaceAll("[A-Za-z]","-");
correct = "";
//guesses = "";
for(int x=0;x<26;x++)
guesses[x] = '~';
guessed = 0;
misses = 0;
}
public void printBoard(){
for(int x =0;x<6;x++)
System.out.println(board[x].piece);
}
public void PrintWrongGuesses(){
misses++;
System.out.println();
if(misses == 1){
board[2].piece = " 0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 2){
board[2].piece = " \\0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 3){
board[2].piece = " \\0/ | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 4){
board[3].piece = " | | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 5){
board[4].piece = " / | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 6){
board[4].piece = " / \\ | ";
System.out.println("Number of misses: " + misses);
over = true;
}
}
public void printLettersGuessed(){
System.out.print("Letters guessed already: ");
for(int x=0;x<26;x++){
if(guesses[x] != '~')
System.out.print(guesses[x] + " ");
}
System.out.println();
}
public void sort(){
boolean doMore = true;
while (doMore) {
doMore = false; // assume this is last pass over array
for (int i=0; i<guesses.length-1; i++) {
if (guesses[i] > guesses[i+1]) {
char temp = guesses[i];
guesses[i] = guesses[i+1];
guesses[i+1] = temp;
doMore = true; // after an exchange, must look again
}
}
}
}
class boardPiece{
public String piece;
public int total;
public int used;
boardPiece(int x){
used = 0;
total = x;
}
}
}
Thank you
Do your puzzles.txt have more than 5 lines? because you declared a private String puzzles[] = new String[5]; the problems seems to happen when puzzleWord = puzzles[puzzleIndex]; is trying to put a null into puzzleWord.
say your puzzle have:
aaaa
bbbb
cccc
when you declare ur puzzles[]= new String[5];
your puzzles memory goes like:
null
null
null
null
null
After that you populate the puzzles array:
aaaa
bbbb
cccc
null
null
when the randomed index is 3 or 4, NPE occurs.
can you check on which line null pointer exception occurs. Mostly it will occur when object is not initialized and your trying to do operation. So make sure object is initialized before using it.
Okay, here's the EDIT. After debugging it for a while I found that puzzles array is not being set properly when you read "puzzles.txt" file. Something funky is going on here in this piece of code. Make sure the file is read correctly and puzzles array gets what is intends to.
Hopefully, it's a good starting point for you.
try{
BufferedReader in =
new BufferedReader(new FileReader("puzzles.txt"));
int count = 0;
while (in.ready()) { //while there is another line in the input file
game.puzzles[count] = in.readLine(); //get line of data
count++; //Increment CWID counter
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}
Why don't you try to debug it and see the values on puzzles and puzzleWord inside the method. That's the best way possible to see what's really going in.
Please check the path of your file puzzles.txt. It seems the file path is not correct. You must be getting an exception printed "Error during reading/writing". Handle it properly, if you are not able to read the file then don't proceed ahead.
Move the puzzles.txt file to correct path or provide a exact file path.
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;
}
}