I'm having trouble figuring out what's wrong with my java code. I am creating a Trivia Game that reads in the question ID, question, answer, and answer point value from a dat file.
I've tried all sorts of things, but am getting the same NumberFormatException.
Below is an example of how the dat file is setup: 10 questions total
1: 01
2: What is light as a feather, but even the strongest man cannot hold it more
than a few minutes?
3: His breath
4: 3
Game.java
import java.util.*;
import java.io.*;
public class Game {
// Instance Variables
private QuestionBank[] questions;
private int numQuestions;
private int questionNumber;
private int playerScore;
// Constructor
public Game()
{
QuestionBank[] questions = new QuestionBank[10];
numQuestions = 0;
questionNumber = 0;
playerScore = 0;
}
public Game(FileInputStream questionsFile)
{
BufferedReader br = new BufferedReader(new InputStreamReader(questionsFile));
String stringLine = null;
int i = 0;
try
{
while((stringLine = br.readLine()) != null)
{
QuestionBank quest = new QuestionBank();
quest.setQuestionID(Integer.valueOf(br.readLine())); //ERROR OCCURS HERE
quest.setQuestion(br.readLine());
quest.setAnswer(br.readLine());
quest.setPointValue(Integer.valueOf(br.readLine()));
questions[i] = quest;
i++;
stringLine = null;
}
br.close();
}
catch (IOException e)
{
System.out.println("Uh oh. Exception caught.");
}
this.questionNumber = 0;
/*Scanner questionsFileScanner = new Scanner(questionsFile);
questions = new QuestionBank[5];
while(questionsFileScanner.hasNextLine())
{
for(int i = 0; i < 4; ++i)
{
questions[i] = new QuestionBank();
questions[i].setQuestion(questionsFileScanner.nextLine());
}
}*/
}
//Accessors and Mutators
public int getNumQuestions()
{
return numQuestions;
}
public int getQuestionNumber()
{
return questionNumber;
}
public int getPlayerSocre()
{
return playerScore;
}
public boolean checkAnswer(String answer)
{
if(answer.contentEquals(questions[questionNumber].getAnswer()) == true)
{
playerScore += questions[questionNumber].getPointValue();
++questionNumber;
return true;
}
else
{
return false;
}
}
public String getNextQuestion()
{
return questions[questionNumber].getQuestion();
}
public String toString()
{
String outputString = "";
for (int i = 0; i < questionNumber; ++i)
{
outputString = questions[i].toString();
}
return outputString;
}
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "What is light as a feather, but even the strongest man cannot hold it more than a few minutes?"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.valueOf(Integer.java:983)
at project7.Game.<init>(Game.java:41)
at project7.RunGame.main(RunGame.java:41)
In addition to what I mentioned above you can use StringUtils.isNumeric method to see if stringLine only contains numeric values.
You can find that method with Apache Commons Lang dependency.
if you're using maven here's the link to download it to your project https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.5
If you're not using maven you should be able to download the jar from that link (or from https://jar-download.com/artifacts/org.apache.commons/commons-lang3/3.5/source-code) and then include the jar as a library in your project.
Related
I need to make high score list in a txt file. In the first game, the txt file should be empty as it is the first game. After the first game, the score list must be updated each time with the player's name and the player's score. The list should of course be ordered from high to low according to player's score. After 10 games, the last ones should be removed and only 10 should remain in the list.
I am trying to do this but every time my txt file is stays empty. How can I fix this issue?
My HighScore class:
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.Formatter;
import java.nio.file.Paths;
public class HighScore {
public class HighScoreEntry {
private String name;
private int score;
public HighScoreEntry(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
public void writeHighScores(HighScoreEntry[] highScores) {
Formatter f = null;
FileWriter fw = null;
try {
fw = new FileWriter("highscores.txt",true);
f = new Formatter(fw);
for (int i = 0; i < highScores.length; i++) {
f.format("%s:%d%n", highScores[i].getName(), highScores[i].getScore());
}
} catch (IOException e) {
System.out.println("An error occurred while writing the high scores file.");
} finally {
if (f != null) {
f.close();
}
}
}
public HighScoreEntry[] readHighScores() {
HighScoreEntry[] highScores = new HighScoreEntry[10];
// Initialize the high scores array with default values
for (int i = 0; i < highScores.length; i++) {
highScores[i] = new HighScoreEntry("", 0);
}
Scanner reader = null;
try {
reader = new Scanner(Paths.get("highscores.txt"));
int i = 0;
while (reader.hasNextLine() && i < 10) {
String line = reader.nextLine();
String[] parts = line.split(":");
String name = parts[0];
int score = Integer.parseInt(parts[1]);
highScores[i] = new HighScoreEntry(name, score);
i++;
}
} catch (IOException e) {
System.out.println("An error occurred while reading the high scores file.");
} finally {
if (reader != null) {
reader.close();
}
}
return highScores;
}
public void updateHighScores(String name, int score) {
System.out.println("Updating high scores with name " + name + " and score " + score);
// Write the player's score and name to the high scores file
writeHighScores(new HighScoreEntry[] {new HighScoreEntry(name, score)});
// Read the high scores from the file
HighScoreEntry[] highScores = readHighScores();
// Sort the high scores
sortHighScores(highScores);
}
private void sortHighScores(HighScoreEntry[] highScores) {
for (int i = 0; i < highScores.length - 1; i++) {
for (int j = i + 1; j < highScores.length; j++) {
if (highScores[i].getScore() < highScores[j].getScore()) {
HighScoreEntry temp = highScores[i];
highScores[i] = highScores[j];
highScores[j] = temp;
}
}
}
}
}
My calling method in Game class:
HighScore highScore = new HighScore();
highScore.updateHighScores(user, playerPoints);
I just have to use them. I can't use anything other than these.
The Formatter class returns a formatted string, but you're not capturing the return value of your format call, nor are you writing the resulting string to your FileWriter.
It should look something like this:
String result = f.format("%s:%d%n", highScores[i].getName(), highScores[i].getScore());
fw.write(string);
Give or take a newline.
So I have seen alot of similar questions to this one but can't seem to find the answer so sorry if this is a duplicate. So I am creating a java program for black jack that I would like to have a system in place to save the chips the user has. I can get it to work but whenever I try to get it to save it just seems to overwrite what was already previously there.
Example
User enters there name: Bob
The system automatically knows there chips so when they press the button to save game it writes there name and chips like so...
Bob
200 (or however many chips they have)
The problem comes up when a new user enters there name and saves so say sally was saving instead of going
Bob
200
Sally
300
It does
Sally
300
And completly deletes bob
public void newSave(String user){
this.user = user;
user = user;
String Chip = Integer.toString(chips);
try{
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(user);
fileWriter.write("\n");
fileWriter.write(Chip);
fileWriter.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
Here is my code that I have that is where my issue lies.
Here is the whole code of the program method.
import java.util.*;
import java.io.*;
class BlackJackPlayer{
//Keep the data secure by using private
private String hand;
private String user;
private int betNum;
private int sum;
private int numAces;
private int chips = 100;
private String bet;
private static Random gen = new Random();
private String result = "";
public String Win = "Win", Lose = "Lose", Split = "Split";
private final int ACE = 1;
private final int JACK = 11;
private final int QUEEN = 12;
private final int KING = 13;
//Scanner for fileIn
Scanner fileIn;
//File For Saves!
File file = new File("Saves.txt");
//Array For Saves!
private ArrayList<String> User = new ArrayList<>();
private ArrayList<Integer> Chips = new ArrayList<>();
//constructor
public BlackJackPlayer(){
hand = "";
sum = 0;
numAces = 0;
//Create a file if save file does not exist//
try{
if (file.createNewFile()){
System.out.println("Save File Created!");
}
else{
//Say Nothing//
}
}//End Try
catch(Exception e){
System.out.println(e.getMessage());
}
//End File Create//
//Read File //
try{
fileIn = new Scanner(new FileReader(file, true));
while(fileIn.hasNext()){
User.add( fileIn.nextLine().trim() );
Chips.add( fileIn.nextInt() );
}//End While
fileIn.close();
}//End Try
catch(Exception e){
System.out.println(e.getMessage());
}//End Catch
//End Read File//
}//End public
//checkSaveStatus//
//See if save exists already in text than send to proper scenario//
public boolean checkSaveStatus(String user){
for(String u: User){
if (user == u){
return true;
}//end if
}//end for
return false;
}//end checkSaveStatus
//End checkSaveStatus//
//overWriteSave if save already exists//
public void overWriteSave(String user){
}//end overWriteSave
//End overWriteSave//
//newSave scnenario if save dosent exist//
public void newSave(String user){
this.user = user;
user = user;
String Chip = Integer.toString(chips);
try{
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(user);
fileWriter.write("\n");
fileWriter.write(Chip);
fileWriter.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
public boolean checkBet(String bet, int chips){
this.bet = bet;
int betNum = Integer.parseInt(bet);
if(betNum <= chips){
return true;
}
return false;
}
public String setBet(String bet){
this.bet = bet;
betNum = Integer.parseInt(bet);
return "You Bet: " + betNum;
}
public String updateChips(){
chips -= betNum;
return "You have: " + chips + " chips";
}
//Getter for hand variable
public String getHand(){
return hand;
}
public String setHand(){
hand = " ";
return hand;
}
//Getter for sum variable
public int getSum(){
return sum;
}
public void hit(){
//local variable
int currentCard = gen.nextInt(13) + 1;
if(currentCard > ACE && currentCard < JACK){
sum += currentCard;
hand += currentCard + " ";
}
else if(currentCard == ACE){
sum += 11;
numAces++;
hand += "A ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == KING){
sum += 10;
hand += "K ";
}//Ends Else If
//Is Ace 1 or 11
if(sum > 21 && numAces > 0){
numAces--;
sum -= 10;
}
}//ENDS HIT
public void stand(){
sum = sum;
return;
}//ends stand
public String getWin(BlackJackPlayer other) {
if(sum > 21){
result = Win;
}
else if(sum < other.getSum()){
result = Lose;
}
else if(sum == other.getSum()){
result = Split;
}
return result;
}
}//end class
Use following code.
FileWriter fileWriter = new FileWriter(file, true);
Here true signifies that you want to append data to existing file.
For more details : https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File,%20boolean)
I am solving the Acode problem of SPOJ.It is a simple Dp problem here
This is my solution:
//http://www.spoj.com/problems/ACODE/
import java.util.Scanner;
//import java.util.Math;
public class Acode {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String encodedString = sc.next();
while (!encodedString.equals("0")) {
long number = numOfDecodings(encodedString);
System.out.println(number);
encodedString = sc.next();
}
return;
}
public static long numOfDecodings(String encodedString)
{
int lengthOfString = encodedString.length();
long decode[] = new long[lengthOfString];
decode[0] = 1;
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
for (int i=2; i<lengthOfString; i++) {
if (isCurrentTwoDigitsValid(encodedString, i)) {
decode[i] = decode[i-2] + decode[i-1];
} else {
decode[i] = decode[i-1];
}
}
return decode[lengthOfString-1];
}
public static boolean isCurrentTwoDigitsValid(String encodedString, int startIndex)
{
char c1 = encodedString.charAt(startIndex);
char c2 = encodedString.charAt(startIndex-1);
if ( (c2=='1') || (c2=='2' && c1<='6')) {
return true;
} else {
return false;
}
}
}
But I am getting an NZEC error when I try to submit it.I tested it for large values too and it is not breaking.I am not understanding how else to improve it.
When input size is 1 you get an error in
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
because of accessing out of the decode array bounds.
You treat 0 as a valid number, but it's not. For example, the correct answer for input "10" is 1, not 2.
It's my second time asking here and straight to the point. I can't seem to find a solution and I know it's not impossible. I wrote a java program that can generate a set of combination of any length, when I stop the program I don't want to start from the beginning how can I pick up from where I stopped?
Thanks.
Example (for length 3):
If I start from aaa ==> 9zI and I stop the program here, I don't want to start from aaa all over but start from 9zI and continue to 999. I just want to continue from where I left off.
public class Main {
public static void main(String[] args) {
S_Permutation sp = new S_Permutation();
String text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
FileClass.fileExist("new.txt", true);
System.out.println("");
sp.permutation(text, "", 7, "sha256.txt","Kaaaaaa");
}
}
=====================================================================
public class S_Permutation {
private List<String> permutation;
public S_Permutation() {
permutation = new ArrayList<>();
}
public boolean saveThis(String words, char a, int limit) {
int count = 0;
limit++;
for (char character : words.toCharArray()) {
if (count == limit) {
return false;
}
if (character == a) {
count++;
} else {
count = 0;
}
}
return count < limit;
}
private int counter = 0;
private boolean seen = false;
public void permutation(String str, String prefix, int lengthOfPermutationString, String filename, String startPoint) {
if (prefix.equalsIgnoreCase(startPoint))
{
seen = true;
}
if (counter == 0) {
if (startPoint.length() != lengthOfPermutationString) {
for (int i = startPoint.length(); i < lengthOfPermutationString; i++) {
startPoint += str.charAt(0);
}
}
counter = -45;
}
if (prefix.length() == lengthOfPermutationString) {
boolean savethis = true;
for (int i = 0; i < prefix.length(); i++) {
savethis = this.saveThis(prefix, prefix.charAt(i), 13);
if (!savethis) {
break;
}
}
if (savethis && seen) {
System.out.println(prefix);
//permutation.add(prefix);
}
} else {
for (int i = 0; i < str.length(); i++) {
if (permutation.size() == 1000) {
FileClass.WriteFile("new.txt", permutation);
permutation.clear();
}
permutation(str, prefix + str.charAt(i), lengthOfPermutationString, filename, startPoint);
}
FileClass.WriteFile("new.txt", permutation);
permutation.clear();
}
}
}
=========================================================================
public class FileClass {
public static boolean WriteFile(String filename, List<String> doc) {
try {
if (!filename.contains(".txt")) {
filename += ".txt";
}
RandomAccessFile raf = new RandomAccessFile(filename, "rw");
String writer = "";
writer = doc.stream().map((string) -> string + "\n").reduce(writer, String::concat);
raf.seek(raf.length());
raf.writeBytes(writer);
raf.close();
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Error");
new Scanner(System.in).nextLine();
return false;
}
return true;
}
static RandomAccessFile raf;
public static boolean fileExist(String filename, boolean delete){
File file = new File(filename);
if (file.exists() && delete)
{
return file.delete();
}
return file.exists();
}
public static void WriteFile(String filename, String text) {
try {
if (!filename.contains(".txt")) {
filename += ".txt";
}
raf = new RandomAccessFile(filename, "rw");
long length = raf.length();
raf.setLength(length + 1);
raf.seek(raf.length());
raf.writeBytes(text + "\n");
} catch (Exception e) {
}
}
private static void write(List<String> records, Writer writer) throws IOException {
for (String record : records) {
writer.write(record);
}
writer.flush();
writer.close();
}
public static void stringWriter(List<String> records, String filename) {
try {
File file = new File(filename);
FileWriter writer = new FileWriter(file, true);
write(records, writer);
} catch (Exception ex) {
System.out.println(ex.getMessage());
new Scanner(System.in).nextLine();
}
}
public static boolean CloseFile() {
try {
raf.close();
return true;
} catch (Exception e) {
return false;
}
}
}
In order to add a "Resume" mechanism, you need to make your program idempotent. One way to do it, is instead of saving the permutations - save to file the parameters that are sent to permutation on each iteration:
now each time that the program starts, it will check what were the last parameters that permutation was called with (the last line in the file), and start from there (when the program starts on the first time, nothing will be written in the file - so it will start from the beginning).
After that the recursion finished, we can call another method that will go over the lines of the file, and read only the permutations (ignoring the other parameters) and write them into a cleaner "final_result.txt" file.
Needless to say that this implementation is more costly (all the additional reads and write from disc) but that's the tradeoff for having it support "resume" operation.
To save/restore process in the middle of its work, you need something we can call a "state" and implement generating combinations in iterative way.
In my implementation the "state" is pos object (I assume set and k will not change on "resume").
My implementation of the problem would be following:
public class RepeatComb {
private int[] pos;
private String set;
public RepeatComb(String set, int k) {
this.set = set;
pos = new int[k];
}
public int[] getState() {return Arrays.copyOf(pos, pos.length);}
public void resume(int[] a) {pos = Arrays.copyOf(a,a.length);}
public boolean next() {
int i = pos.length-1;
for (int maxpos = set.length()-1; pos[i] >= maxpos; ) {
if (i==0) return false;
--i;
}
++pos[i];
while (++i < pos.length) pos[i]=0;
return true;
}
public String getCur() {
StringBuilder s = new StringBuilder(pos.length);
for (int i=0; i < pos.length; ++i)
s.append(set.charAt(pos[i]));
return s.toString();
}
public static void main(String[] args) {
int[] state;
String text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
RepeatComb comb = new RepeatComb(text, 3);
int stop = 10; //break after 10
do {
if (stop-- == 0) break;
System.out.println(comb.getCur());
} while (comb.next());
//save state
state = comb.getState();
System.out.println("---------");
//resume (with the same args: text,3)
stop = 10; //break after 10
comb = new RepeatComb(text, 3);
comb.resume(state); // resume here
do {
if (stop-- == 0) break;
System.out.println(comb.getCur());
} while (comb.next());
}
}
Update: I've added functions for getting state and resuming from it
and example of use. state array can be saved in file, then restored.
been working on this program for a while and I think I've made much more progress. My java skills are not very good, but I think I'm close. Everything should compile without issue except for my "public void run" in my worker class. The program prompts the user for how many threads they want and then parses through a text file of random numbers to find all the prime numbers. My issue seems to be in the algorithm for the prime numbers. How do I write the algorithm so it parses the data down and finds the prime numbers?
I have posted the entire program below, but please see the worker class towards the bottom. Any help would be greatly appreciated in solving this issue. Thank you.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class PrimeNumbers{
public static void main(String[] args) throws IOException {
int[] numbers = new int[100000];
int count;
int index = 0;
String datafile = "dataset529.txt"; //string which contains datafile
String line; //current line of text file
try (BufferedReader br = new BufferedReader(new FileReader(datafile))) { //reads in the datafile
while ((line = br.readLine()) != null) { //reads through each line
numbers[index++] = Integer.parseInt(line); //pulls out the number of each line and puts it in numberset[]
}
}
System.out.println("How many threads would you like to use?");
Scanner scan = new Scanner(System.in);
int z = scan.nextInt();
Thread[] threads = new Thread[z]; //creates threads as per user
worker[] finder = new worker[z]; //assigns finder to each thread created
int range = numbers.length / z; //breaks up each worker into a section depending on thread count.
for (count = 0; count < z; count++) {
int startAt = count * range;
int endAt = startAt + range;
finder[count] = new worker(startAt, endAt, numbers);
}
for (count = 0; count < z; count++) { //moves to next thread
threads[count] = new Thread(finder[count]);
threads[count].start();
}
boolean processing = false;
do {
processing = false;
for (Thread t : threads) {
if (t.isAlive()) {
processing = true;
break;
}
}
} while (processing);
for (worker worker : finder) {
System.out.println("Max of thread is: " + worker.getPrime());
}
}
public static class worker implements Runnable {
private int start;
private int stop;
private int numberset[];
public worker(int start, int stop, int[] numberset) {
this.start = start;
this.stop = stop;
this.numberset = numberset;
}
#Override
public void run() {
for (int x = start; x < stop; x++) {
if (numberset[]%3 && != 1 && != 2 && !=3)
return prime
}
}
public int getPrime() {
return true
}
}
}