Issue with file processing - java

I'm a novice java programmer and I am having trouble with file output with my java project. In this project, I'm supposed to have a "Rock, Paper, Scissors" program which will output the results onto a separate file. When I run the program and then look at the file, it only records the most recent result instead of every one. Any advice on what to do would be great. Please excuse the poor form; I will clean it up later. I've also erased most of the comments in order to shorten it. Thanks.
import java.util.*;
import java.awt.*;
import java.io.*;
public class RockPaperScissors {
public static int count = 0;
public static void main(String[] args) {
execute();
}
public static void execute(){
System.out.println("This program will allow you to play \n\"Rock, Paper, Scissors\" against a computer.");
System.out.println();
System.out.println("Enter 'r' for Rock, 'p' for Paper, or s for Scissors.");
System.out.println("Enter 'w' to have an insta-win for that round. Enter '-1' at anytime to exit program.");
String info = userInput();
int value = guessCode();
decideOutcome(value, info);
again();
}
public static String userInput() {
Scanner console = new Scanner (System.in);
String s = console.next();
return s;
}
public static int guessCode() {
Random r = new Random ();
return (r.nextInt(3)+1); // Random integer between 1 and 3;
}
public static void decideOutcome(int i, String j) {
try {
PrintStream output = new PrintStream(new File ("records.txt"));
if (j.equalsIgnoreCase("rock")|| j.equalsIgnoreCase("r")) {
count++;
switch (i){
case 1:
System.out.println("You've won! Computer picked scissors.");
output.println(count + " Win ");
break;
case 2:
System.out.println("You've tied.... Computer also picked rock.");
output.println(count + " Tie ");
break;
case 3:
System.out.println("You've lost. Computer picked paper.");
output.println(count + " Loss ");
break;
}
} else if (j.equalsIgnoreCase("paper")|| j.equalsIgnoreCase("p")) {
count++;
switch (i){
case 1:
System.out.println("You've lost; Computer picked scissors.");
output.println(count + " Loss ");
break;
case 2:
System.out.println("You've won! Computer picked rock.");
output.println(count + " Win ");
break;
case 3:
System.out.println("You've tied.... Computer also picked paper.");
output.println(count + " Tie ");
break;
}
} else if (j.equalsIgnoreCase("scissors")|| j.equalsIgnoreCase("s")) {
count++;
switch (i){
case 1:
System.out.println("You've tied.... Computer picked scissors.");
output.println(count + " Tie ");
break;
case 2:
System.out.println("You've lost; Computer picked rock.");
output.println(count + " Loss ");
break;
case 3:
System.out.println("You've won! Computer also picked paper.");
output.println(count + " Win ");
break;
}
} else if (j.equalsIgnoreCase("w")) {
count++;
System.out.println("You've effortlessly defeated the computer!");
output.println(count + " Win ");
} else if (j.equals("-1")) {
System.out.println("Thanks for playing!"); // need to find way to reach end.
if (count == 1) { // If the user terminates after the first match.
System.out.println("You've played a single match.");
} else if (count > 1) { // Anything more than 1 match played upon termination.
System.out.println("You've played " + count + " matches total.");
} else { // This is for exceptions when user inputs gibberish for their sign and then 'no' for the second input.
System.out.println("No matches were played.");
}
System.out.println("Good Bye!");
System.exit(0);
} else {
System.out.println("You didn't input the right thing.");
}
} catch (FileNotFoundException e) {
System.out.println("File was not found; try again");
}
}
public static void again() {
System.out.println("Do you want to play again? (Type in 'y' for Yes or 'n' for No.)");
Scanner console2 = new Scanner (System.in);
String t = console2.next();
while (t.equalsIgnoreCase("yes")||t.equalsIgnoreCase("y")) {
System.out.println();
System.out.println();
execute(); //
}
if (t.equalsIgnoreCase("no") || t.equalsIgnoreCase("n") || t.equals("-1")) {
System.out.println("Hope you had fun! I'm sure I've had just as much fun with making this program! Good Bye!");
if (count == 1) { // If the user terminates after the first match.
System.out.println("You've played a single match.");
} else if (count > 1) { // Anything more than 1 match played upon termination.
System.out.println("You've played " + count + " matches total.");
} else { // This is for exceptions when user inputs gibberish for their sign and then 'no' for the second input.
System.out.println("No matches were played.");
}
System.exit(0);
} else { // If the user doesn't input 'yes' or 'no.'
System.out.println("Not the proper response, but it's assumed that you don't want to continue.");
if (count == 1) { // If the user terminates after the first match.
System.out.println("You've completed a single match.");
} else if (count >= 2) { // Anything more than 1 match played upon termination.
System.out.println("You've completed " + count + " matches total.");
} else { // The user haphazardly messes up both inputs.
System.out.println("No matches were finished.");
}
System.exit(0);
}
}
}

When you decideOutcome(), you reopen a PrintStream to the file each time.
But this constructor does not seek to the end of the file! Which means you overwrite the contents each time.
Try using a FileWriter instead, with the appropriate constructor.
Edit: since the assignment seems to require that you use a PrintStream (why?), you will have to do this instead:
PrintStream output = new PrintStream(new FileOutputStream("records.txt", true));
But in real life, you will probably use a BufferedWriter instead; pretty much nobody uses PrintStream.

The Printstream you are using starts writing to the file from the beginning and not from where the last line is.
It will be better to use Filewriter to work on files as it has append and insert modes.
What you need is the append mode.

You can never use a PrintStream to accomplish this task in the way you are doing it. The API clearly states that the constructor of the PrintStream does the following:
PrintStream(File file)
Creates a new print stream, without automatic line flushing, with the specified file.
file - The file to use as the destination of this print stream. If the
file exists, then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
There are no constructors that allow you to append to the previous file.
The solution therefore lies in the fact that you can only use the PrintStream constructor exactly ONCE. This can be achieved by making your output variable a class variable and getting rid of your declaration (as well as the try-catch) in decideOutcome().
private static PrintStream output;
public static void main(String[] args) {
try {
output = new PrintStream(new File("records.txt"));
execute();
} catch (FileNotFoundException e) {
System.out.println("File was not found; try again");
} finally {
output.close();
}
}
Another important thing to note is that whenevre you open a stream such as a Scanner or a PrintStream you should always close it. The best place to close them is in a finally clause as that part of your code is guaranteed to run.

Related

How to stop this algorithm without using return;

import java.util.Scanner;
public class JavaClass {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
System.out.println("Welcome to Baugette Store! ");
System.out.println("*****Bakery Inventory*****");
System.out.print("Enter amount of Baugette:");
int amount1=scan.nextInt();
if(amount1<0) {
System.out.println("Error.");
return;
}
System.out.print("Enter Price of Baugette:");
double price1=scan.nextDouble();
*if(price1<0) {
System.out.println("Error.");
return;
}
System.out.println("**Customer Interface**");
System.out.println("Welcome to our baugette store. ");
System.out.println("We have "+price1+ " baugette(s) available.");
System.out.println("How Many Baugette(s) Do You Want to Buy?");
int amount2=scan.nextInt();
if(amount2<=0) {
System.out.println("Error.");
return;
}
if(amount2>amount1) {
System.out.println("Error.");
return;
}
else {
System.out.println("You want to buy "+amount2+ " baugette(s).");
double totalcost,r;
totalcost=amount2*price1;
r=amount1-amount2;
System.out.println("Yours cost is "+(int)totalcost+" Turkish lira(s)");
System.out.println("Now, We have "+(int)r+" baugette(s) remaining.");
System.out.println("Thank you for shopping from Kolantro Baugette Shop today.");
System.out.println("Good bye :)");
}
}
}
I want to learn how do i stop this algorithm without using return; for each if block. When I delete all return;s complier keeps reading codes. I want to execute when i type -3 for first if block Algorithm must be stopped without using return;.
As the comments below your question suggest, you can use a if-else-statement:
if (amount1 == -3) {
return;
} else {
// ...
}
Or short:
if (amount1 == -3) {
return;
}
// ...
But this way you have a return, which you don't want if I understand you correctly. You can invert the logic and run your code only if the amount1 is not -3. This way there is no return-statement:
public static void main(String args[]) {
// ...
if (amount1 != -3) {
// ...
}
}
If you asked for -3 as an example, here is the code if you want to skip if the amount is below or equals 0:
if (amount1 > 0) { // One ore more baugettes available, shop is open
// ...
}
Take your time to think about how if-statements work and how the condition(s) are evaluated. You can also nest if-statements:
if (1>0) {
if (a==b) {
}
}
This way you can structure your algorithms in a neat way.
Btw, you have a bug:
"We have " + price1 + " baugette(s) available."
must be
"We have " + amount1 + " baugette(s) available."
Consider using meaningful names for your variables, e.g. amountBaugettesInStore. This way you don't mix them up so easily.

JAVA I don't understand Try-catch

This is my first time here. I'm starting to learn how to code, so I honestly hope this question I have is not something I can find over here! (I promise I searched for a while, but since I'm a noob in this topic, I didn't found anything understandable for me in order to resolve my doubt).
I'm doing a simple game in JAVA, in which the program generates a random number and the player has to guess the number generated.
When the player enters a number, the game displays a hint, saying if it is higher or lower than the number generated randomly.
The program itself works fine if you enter just numbers, but I want to add a try-catch statement to handle bad user input.
I tried using the statement as I show in my code, but I can't understand why it's not working properly, because when I enter something different of a number, the exception is catched and it prints on console the System.out.println(), but program terminates when this happens.
I would like to try-catch just to get the exception of entering not a number without terminating the program every time the exception is catched.
How can I fix this?
Thanks a lot for your help!
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); //Creates Scanner object to read from keyboard
String playAgain = ""; //if == y, game restarts
try {
do {
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
//System.out.println(theNumber); //Uncoment this in case we want to know the number (for testing).
int guess = 0; //Number entered by the player
int count = 0; //Number of tries of guessing the number
while(guess != theNumber){
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt(); //Reads the number typed on the keyboard by the player
count++; //Plus 1 every time a number is entered
System.out.println("You entered " + guess +".");
if(guess < theNumber) { //If number entered is smaller
System.out.println("The number is bigger" + ", try again!");
System.out.println("Number of tries: " + count);
} else if(guess > theNumber) { //If number entered is bigger
System.out.println("The number is smaller" + ", try again!");
System.out.println("Number of tries: " + count);
} else { //If both previous cases are false
System.out.println("Congratulations! You've found the number!");
}
}
//Once guess == theNumber
System.out.println("Number of tries: " + count);
System.out.println("Play again? (y/n)");
playAgain = scan.next(); //Reads the String entered from keyboard by the player
}
while(playAgain.equalsIgnoreCase("y")); //If player enters y, start again.
//Otherwise
System.out.println("Thank you for playing! Goodbye :)");
} catch (Exception e) {
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
}
scan.close(); //Close scanner
} //Close main
} //Close class
place try-catch inside the while loop and reinstantiate the scanner object (scan = new Scanner(System.in) inside the catch block.
while (guess != theNumber) {
try {
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt(); // Reads the number typed on the
// keyboard by the player
count++; // Plus 1 every time a number is entered
System.out.println("You entered " + guess + ".");
if (guess < theNumber) { // If number entered is smaller
System.out.println("The number is bigger" + ", try again!");
System.out.println("Number of tries: " + count);
} else if (guess > theNumber) { // If number entered is
// bigger
System.out.println("The number is smaller" + ", try again!");
System.out.println("Number of tries: " + count);
} else { // If both previous cases are false
System.out.println("Congratulations! You've found the number!");
}
} catch (Exception e) {
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
scan = new Scanner(System.in);
}
}
You need to understand the working of the try-catch block. You don't need to surround the entire code within try. Just put that part of the code which causes an exception. So, in your case just surround guess = scan.nextInt(); with try and then catch an exception. Because, here this statement raises an exception when the input is not an integer. This way you can ensure that the user input is valid for each iteration of the while(guess != theNumber) loop.
Edit_1:
I removed the try-catch blocks from your code and added the following & it works fine for me:
try{
guess = scan.nextInt();} //Reads the number typed on the keyboard by the player
catch (InputMismatchException e){
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
scan.nextLine();
continue;
}

Why does my program print out the exception statement endlessly give bad user input?

Ive no idea if my title made sense but here is the code ©
import java.util.InputMismatchException;
import java.util.Scanner;
public class Gussing {
public static void theGame(Scanner input){
int randomNum= (int)(Math.random()*101);//randomizes a number between 0-100 inclusive of both
System.out.println(randomNum); //for debugging purposes
int attemptCounter = 0; //counts how many attempts the user make
System.out.print("Welcome to the guess-the number game! Enter your guess: ");
while(true){
System.out.println("here is bad input");
try{
System.out.println("here is after the bad input");
int userInput= input.nextInt();
if (userInput==randomNum) //when usr input and generated random number are equal we print how many attempts
{
attemptCounter++;
System.out.println("Congrats you made the right guess after "+ attemptCounter + " attempts!");
break;
}
if(userInput<randomNum){
attemptCounter++;
System.out.print("Too low! Try again: ");
}
else {
attemptCounter++; //else clause does the opposite of if clause
System.out.print("Too high! Try again: ");
}
}
catch( Exception e){
System.out.println("Invalid input");
}
}
}
public static void main(String[] args){
Scanner input = new Scanner (System.in);
theGame (input);
System.out.println("Play again? (Y/N)");
try{
char answer=input.next().toLowerCase().charAt(0);
//toLowerCase method so that N =n = no !
if (answer =='y') theGame (input);
else if (answer =='n') System.out.println("Good bye");
input.close(); //no more input data
}
catch(Exception e){
System.out.println("invalid input");
}
}
}
so when the user types in the wrong type i.e not int it prints out invalid input. This is however not the problem the problem is that it prints that out infinitely. I tried adjusting the try catchblocks but it didnt help at all
nextInt doesnt remove non-integer data from the input buffer so it gets recycled indefinitely unless the data is consumed. In this case an InputMismatchException is thrown by the method so you could write your exception block as
} catch (InputMismatchException e) {
System.out.println("Invalid input " + input.nextLine());
}

High low game logic for win [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Lost Newbie!
please improve the code it never shows the conditions. As well as i need to put four wins in a row for the user to win. please help!!
import java.util.Scanner;
import java.util.Random;
public class HiLoGame {
public static void main (String[] args) {
String guess=null;
String high= "high";
String low="low";
String equal = "equal";
int nextCard;
int card=3;
System.out.println("Current card is: "+ card);
if(card==11){
System.out.println ("Which means it is card jack!");
}else if(card==12){
System.out.print("which means it is card queen!");
}else if(card==13){
System.out.println("Which means it is card king!");
}else if (card==14){
System.out.println("Which means it is card Ace!");
}
System.out.println("WELCOME! to High-Low game.");
System.out.println("Guess four times in a row to win.");
while(true){
Random generator = new Random();
nextCard = generator.nextInt(14)+1;
System.out.println("Next card will be high, low or equal?");
Scanner input = new Scanner(System.in);
guess = input.next();
System.out.println("It is --> "+ nextCard);
card = generator.nextInt(14)+2;
nextCard = generator.nextInt(14)+2;
System.out.println("Next card will be high, low or equal?");
Scanner input1 = new Scanner(System.in);
guess = input1.next();
System.out.println("It is --> "+ nextCard);
while(true){
if (guess.equals(high))
{
if (card < nextCard)
{
System.out.println("NICE GUESS ");
System.out.println("KEEP PLAYING");
break;
}
else
{
System.out.println("Sorry WRONG GUESS!");
System.out.println("Better luck next time");
System.exit(0);
}
}
else if (guess.equals(low))
{
if (card > nextCard)
{
System.out.println("NICE GUESS");
System.out.println("KEEP PLAYING");
break;
}
else
{
System.out.println("Sorry WRONG GUESS!");
System.out.println("Better luck next time");
}
}
else if(guess.equals(equal))
{
if (card==nextCard)
{
System.out.println("NICE GUESS");
System.out.println("KEEP PLAYING");
break;
}
else
{
System.out.println("Sorry WRONG GUESS");
System.out.println("Better luck next time!");
System.exit(0);
}
}
}}}}
your code is a bit strange and confusing but I have taken the time to go through it, any questions feel free to ask:
import java.util.Scanner;
import java.util.Random;
public class HiLoGame {
public static void main(String[] args) {
Random generator = new Random();
Scanner input = new Scanner(System.in);
String guess = null, result = null;
Boolean won = false;
int nextCard, card = 3, count = 0;
System.out.println("Current card is: " + card);
switch (card) {
case 11:
System.out.println("Which means it is card jack!");
break;
case 12:
System.out.print("which means it is card queen!");
break;
case 13:
System.out.print("which means it is card king!");
break:
case 14:
System.out.println("Which means it is card Ace!");
break;
}
System.out.println("WELCOME! to High-Low game.\nGuess four times in a row to win.");
while (!won) {
nextCard = generator.nextInt(14) + 1;
System.out.println("You current card is: " + card + "\nWill the next card be high, low or equal?");
guess = input.next().toLowerCase();
System.out.println("The next card is:" + nextCard);
if(card<nextCard){
result = "high";
}
else if(card>nextCard){
result = "low";
}
else if(card==nextCard){
result = "equal";
}
if(guess.equals(result)){
System.out.println("NICE GUESS\nKEEP PLAYING");
card = nextCard;
count++;
}
else {
System.out.println("Sorry WRONG GUESS!\nBetter luck next time");
count=0;
}
if(count==4){
System.out.println("Congratulations, you have beaten the game!!!\nWould you like to play again? Yes/No");
guess = input.next().toLowerCase();
if(guess.equals("yes"))
{
count = 0;
card = generator.nextInt(14) + 1;
}
else{
System.out.println("Thank you for playing, goodbye");
System.exit(0);
}
}
}
}
}
Good luck with your learning!
A few of the things used in this code compared to the code in question are:
I have used a switch block, this is used instead of multiple if statements, you can pass in the variable and then in the line: case you put in what you want to match it against, this looks a lot nicer and is much more efficient than using multiple if statements.
I have also used a \n in the printline this is the escape xhar for a newline. You can use this instead of multiple print line statements.
You should try in your code to minimise the amount of repeated text, my code is far from perfect but if it was then you wouldn't have anything to look into.
Instead of calling multiple if statements also try doing one set of if statements to check a condition and then save the result in advance, this changes the amount of comparisons...
Hopefully that makes sense to you.

The Pig Dice Game Human vs Computer Java Program

I have been working on this program for about a week now and I think I have it down pack. The issue I am having when I ask the user at the beginning of the game (human vs computer) every time I run the program it asks me what my name is again. Here is what I have thus far:
import java.util.Scanner;
public class Assignment
{
Scanner usersName;
Boolean humanTurn = true;
Boolean computerTurn = true;
int dice;
int humanTurnPoints, computerTurnPoints;
int humanTotalPoints = 0;
int computerTotalPoints = 0;
private Scanner keyboard;
private Scanner key;
//System.out.print("Please enter your name: ");
//usersName = new Scanner(System.in);
//setStart(usersName.nextLine());
public void roll()
{
dice = (int)(Math.random()*6) + 1;
}
public int humanTurnScore()
{
{
humanTurnPoints = dice + humanTurnPoints;
System.out.println("You threw: " + dice);
System.out.println("You have scored: " + humanTurnPoints + " in your turn.");
} return humanTurnPoints;
}
public void humanTurnZero()
{
humanTurnPoints = 0;
}
public int computerTurnScore()
{
{
computerTurnPoints = dice + computerTurnPoints;
System.out.println("Computer has scored: " + computerTurnPoints + " in its turn.");
} return computerTurnPoints;
}
public void computerTurnZero()
{
computerTurnPoints = 0;
}
public Assignment()
{
humanGame();
if(!humanTurn)
{
computerTurn();
}
}
public int humanGame()
{
System.out.println("To start the game please press 'r'.");
key = new Scanner(System.in);
String start = key.nextLine();
if(!start.equalsIgnoreCase("R"))
{
System.out.println("Make sure you are pressing 'r'.");
humanGame();
}
if(start.equalsIgnoreCase("R"))
{
System.out.println("You pressed 'r'.");
System.out.println("Lets start.");
do{
roll();
if(dice == 1)
{
System.out.println("You got 1 and you lost your turn.");
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
humanTurnZero();
computerTurn();
}
else if(dice != 1)
{
humanTotalPoints += dice;
if(humanTotalPoints >= 100)
{
System.out.println("You threw: " + dice);
System.out.println("Your GRAND TOTAL score is: " + humanTotalPoints);
System.out.println("Congratulations, you win!");
System.exit(0);
}
humanTurnScore();
System.out.println("Your GRAND TOTAL score is: " + humanTotalPoints);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("You can hold or roll again.");
System.out.println("To roll again press 'r' or 'h' to hold.");
keyboard = new Scanner(System.in);
String choice = keyboard.nextLine();
if(choice.equalsIgnoreCase("R"))
{
System.out.println("You pressed 'r'.");
System.out.println("Lets roll again.");
roll();
if(!choice.equalsIgnoreCase("R"))
{
System.out.println("You didn't press 'r'. To make sure the program is running correctly please press 'r' to roll or 'h' to hold.");
humanGame();
}
}
if(choice.equalsIgnoreCase("h"))
{
System.out.println("You pressed 'h' and loose your turn.");
System.out.println("Your Grand total is: " + humanTotalPoints);
humanTurnZero();
computerTurn();
}
}
}while(humanTurn);
}return dice;
}
public int computerTurn()
{
System.out.println("Now it's computer turn.");
do {
roll();
if(dice != 1)
{
computerTotalPoints += dice;
if(computerTotalPoints >=100)
{
System.out.println("Computer threw: " + dice);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("Game Over! the computer wins");
System.exit(0);
}
System.out.println("Computer threw: " + dice);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("Your Grand total is: " + humanTotalPoints);
computerTurnScore();
roll();
}
if(dice == 1)
{
System.out.println("Computer thrown 1 therefore it's your turn now.");
computerTurnZero();
humanGame();
}
if(computerTurnPoints >= 20)
{
System.out.println("Computer scored already " + computerTurnPoints + " you'd better start to focus.");
System.out.println("Please play again");
humanGame();
}
}while (computerTurn);
return dice;
}
public static void main(String[] args)
{
new Assignment();
}
}
I commented out (up close to the top of the program) where I am asking the user at the beginning of the program what their name is. I actually need in all the System.out.println where it says 'You' I need it to say the usersName.
Would someone please help me with this program. I know someone is kind enough to help me out here.
Thank you in advance.
Of course it will ask you that every time!
You need to save this in a file, and then read from it!
//Write
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println(usersName.nextLine());
writer.close();
//Read
BufferedReader br = new BufferedReader(new FileReader("the-file-name.txt"));
try {
while (line != null) {
usersName = line;
line = br.readLine();
}
} finally {
br.close();
}
Add your logic for determining if there is sth in that file yourself please.
Okay, I think you might be getting confused about the lifetimes of variables. In java, variables like String username; exist only in their own scope.
If you define a variable inside a method, it will be forgotten about when the program exists the method.
If you define it as a field inside a class (what you were doing), it will only exist as long as the instance of the class exists. As soon as the program forgets about the instance of the class, it also forgets about anything attached to that instance, including its variables.
Once the program shuts down, the computer naturally forgets about all objects that the program held, and so the username ceases to exist.
If you want the program to remember some value across shutdowns, you have to store that value in a file or a database or whatever. I recommend using a file, to make a database for this would be overkill squared. I will refer you to Roberto's answer from an hour ago for more info on how to achieve this exacly.

Categories