How would i go around getting my txt to output the following format ! It only outputs the first line i input but would like it look like the following>>
This is an example of how I would like an output to look - http://i.stack.imgur.com/7Lfr0.png
import java.io.FileOutputStream;
import java.io.IOException;
import java.io[enter image description here][1].PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class GAMESCORE {
private static char[] input;
public static void main(String[] args) {
int[] minutesPlayed = new int [100];
String gamerName, gamerReport;
String[] gameNames = new String[100];
int[] highScores = new int[100];
#SuppressWarnings("resource")
Scanner Scan = new Scanner(System.in);
System.out.println("-------------- Game Score Report Generator --------------");
System.out.println(" ");
System.out.println("Enter Your Name");
gamerName = Scan.nextLine();
boolean isEmpty = gamerName == null || gamerName.trim().length() == 0;
if (isEmpty) {
System.out.print("Enter your Name.");
gamerName = Scan.nextLine();
}
System.out.println("Enter details in this format - " + " -->");
System.out.println(" ");
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
Scanner scanner = new Scanner(System.in);
List<String> al = new ArrayList<String>();
String word;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("quit")) {
break;
}
al.add(word);
} else {
break;
}
}
String[] splitUpReport;
splitUpReport = gamerReport.split(":");
int i = 0;
gameNames[i] = splitUpReport[0];
highScores[i] = Integer.parseInt(splitUpReport[1].trim() );
minutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());
try
{
PrintWriter writer = new PrintWriter(new FileOutputStream("Gaming Report Data.txt", true));
writer.println("Player : " + gamerName);
writer.println();
writer.println("--------------------------------");
writer.println();
String[] report = gamerReport.split(":");
writer.println("Game: " + report[0] + ", score= " +report[1] + ", minutes played= " +report[2]);
//writer.println("Games Played : " + minutesPlayed);
writer.close();
} catch (IOException e)
{
System.err.println("You have made an error with data input");
}
System.out.println("You have quit!");
}
public static char[] getInput() {
return input;
}
public static void setInput(char[] input) {
GAMESCORE.input = input;
}
}
Well the variable "gamerReport" is set for the first line, and is never touched again other than to print it, and the list "al" has stuff added to it, but is never used. Maybe try something like this?
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class GAMESCORE {
private static char[] input;
public static void main(String[] args) {
int totalGames, totalAchievements, totalTime;
totalGames = 0;
totalAchievements = 0;
totalTime = 0;
String gamerName, gamerReport;
#SuppressWarnings("resource")
Scanner Scan = new Scanner(System.in);
System.out.println("-------------- Game Score Report Generator --------------");
System.out.println(" ");
System.out.println("Enter Your Name");
gamerName = Scan.nextLine();
boolean isEmpty = gamerName == null || gamerName.trim().length() == 0;
if (isEmpty) {
System.out.print("Enter your Name.");
gamerName = Scan.nextLine();
}
System.out.println("Enter details in this format - " + " -->");
System.out.println(" ");
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
Scanner scanner = new Scanner(System.in);
List<String> al = new ArrayList<String>();
String word;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("quit")) {
break;
}
al.add(word);
} else {
break;
}
}
try
{
PrintWriter writer = new PrintWriter(new FileOutputStream("Gaming Report Data.txt", true));
writer.println("Player : " + gamerName);
writer.println();
writer.println("--------------------------------");
writer.println();
for(String listString : al){
String[] splitUpReport;
splitUpReport = listString.split(":");
writer.println("Game: " + splitUpReport[0].trim() + ", score= " + splitUpReport[1].trim() + ", minutes played= " +splitUpReport[2].trim());
totalGames++;
totalTime += Integer.parseInt(splitUpReport[2].trim());
totalAchievements += Integer.parseInt(splitUpReport[1].trim());
}
writer.println();
writer.println("--------------------------------");
writer.println();
writer.println("Games Played: " + String.valueOf(totalGames));
writer.println("Total Achievement: " + String.valueOf(totalAchievements));
writer.println("Total Time: " + String.valueOf(totalTime) + " (" + String.valueOf(totalTime/60) + " hours and " + String.valueOf(totalTime%60) + " minutes)");
//writer.println("Games Played : " + minutesPlayed);
writer.close();
} catch (IOException e)
{
System.err.println("You have made an error with data input");
}
System.out.println("You have quit!");
}
public static char[] getInput() {
return input;
}
public static void setInput(char[] input) {
GAMESCORE.input = input;
}
}
Related
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string:");
String name = sc.nextLine();
while(name.contains(",") == false) {
System.out.println("Error: No comma in string.");
System.out.println("Enter input string:");
name = sc.nextLine();
}
while(!name.equals("q") && !name.equalsIgnoreCase("q")) {
String[] splitting = name.split(",");
String first;
String second;
if(name.compareTo("q") == 1) {
break;
}
if(splitting[1].contains(" ")) {
first = splitting[0];
second = splitting[1].substring(splitting[1].indexOf(' ') + 1, splitting[1].length());
}
else {
first = splitting[0];
second = splitting[1];
}
System.out.println("First word: " + first);
System.out.println("Second word: " + second);
System.out.println("Enter input string:");
name = sc.nextLine();
while(name.contains(",") == false && name.equalsIgnoreCase("q")) {
System.out.println("Error: No comma in string.");
System.out.println("Enter input string:");
name = sc.nextLine();
}
}
System.out.println("Thank you!");
sc.close();
}
}
I'm trying to get this to work when the user inputs a q and it stops the while loop and says thank you at the end.
I have tried so many different ways to do this already.
sometimes it is simpler to break out of an endless loop:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter input string (q to quit):");
String input = sc.nextLine();
if ("q".equals(input.toLowerCase())) {
break;
} else if (input.contains(",")) {
String[] splitting = input.split(",");
String first;
String second;
if (splitting[1].contains(" ")) {
first = splitting[0];
second = splitting[1].substring(
splitting[1].indexOf(' ') + 1,
splitting[1].length());
} else {
first = splitting[0];
second = splitting[1];
}
System.out.println("First word: " + first);
System.out.println("Second word: " + second);
}
}
System.out.println("Thank you!");
sc.close();
}
}
I just want to print the String "code", which the user enters in the method, but it is printing "null", but when i want to print int num, it prints what the user enters. The output should print all the details that the user entered; sort of like an ID thing. This should be very simple but for some reason I am not able to do it and Im starting to lose hope. Any help would be appreciated. Thanks
public class Lab2 {
static String code;
static String num;
int year;
static int sem;
public static void main(String[] args) {
info();
num();
sem();
System.out.println(num + " " + sem + " " + code);
}
public static void info() {
Scanner sc = new Scanner(System.in);
System.out.println("Course ID Generator\n--------------------------");
System.out.println("Please Enter Course Information:");
String message = "Initial";
String code = "";
while (!message.isEmpty()) {
if (!message.equals("Initial")) {
System.out.println(message);
}
System.out.print("Course Code (only capital letters " + "with a length between 2 and 4): ");
code = sc.nextLine();
message = checkLength(code);
if (message.isEmpty()) {
message = checkUpperCase(code);
}
}
}
private static String checkLength(String code) {
String output = "";
if (code.length() < 2 || code.length() > 4) {
output = "Course Code length was not between " + "2 and 4, Please try again";
}
return output;
}
private static String checkUpperCase(String code) {
String output = "";
for (int i = 0; i < code.length(); i++) {
char ch = code.charAt(i);
if (Character.isAlphabetic(ch) && Character.isUpperCase(ch)) {
} else {
output = "Course Code must only have capital " + "letters, please try again";
break;
}
}
return output;
}
public static void num() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Course Number (consists of only 3 digits): ");
num = sc.nextLine();
if (num.length() == 3) {
break;
} else {
System.out.println("Course Number length was not 3, please try again");
}
sc.close();
}
}
public static void sem() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Semester (Fall=01, Sprint=02, Summer=03):");
sem = sc.nextInt();
if (sem > 0 && sem < 4) {
break;
} else {
System.out.println("Please enter correct semester code, try again");
}
}
sc.close();
}
}
Remove the line
String code = "";
in your info Method
You are using the same variable code twice.
Read this for further information https://dzone.com/articles/variable-shadowing-and-hiding-in-java
I have this hangman program but have an issue with asking the user if they want to play again, it always just ends the program. How can i fix this issue. Thanks for future reply's.
package hangman. I hope editing is okay with this
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Hangman {
static Scanner keyboard = new Scanner(System.in);
static int size, size2;
static boolean play = false;
static String word;
static String[] ARRAY = new String[0];
static String ANSI_RESET = "\u001B[0m";
static String ANSI_BLUE = "\u001B[34m";
static String ANSI_GREEN = "\u001B[32m";
static String ANSI_RED = "\u001B[31m";
static String ANSI_LIGHTBLUE = "\u001B[36m";
//^declarations for variables and colors for display^
public static void main(String[] args) {
randomWordPicking();
//^calls method^
}
public static void setUpGame() {
System.err.printf("Welcome to hangman.\n");
try {
Scanner scFile = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
String line;
while (scFile.hasNext()) {
line = scFile.nextLine();
Scanner scLine = new Scanner(line);
size++;
}
ARRAY = new String[size];
Scanner scFile1 = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
while (scFile1.hasNext()) {
String getWord;
line = scFile1.nextLine();
Scanner scLine = new Scanner(line);
word = scLine.next();
ARRAY[size2] = word;
size2++;
//calls method for picking word^
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
public static void randomWordPicking() {
setUpGame();
int LEFT = 6;
do {
int random = (int) (Math.random() * ARRAY.length);
//^genertates a random number^
String randomWord = ARRAY[random];
String word = randomWord;
//^chosses a random word and asgins it to a variable^
char[] ranWord = randomWord.toCharArray();
char[] dash = word.toCharArray();
//^Creates a char array for the random word chosen and for the dashs which are displayed^
for (int i = 0; i < dash.length; i++) {
dash[i] = '-';
System.out.print(dash[i]);
//^displays dashs to the user^
}
for (int A = 1; A <= dash.length;) {
System.out.print(ANSI_BLUE + "\nGuess a Letter: " + ANSI_RESET);
String userletters = keyboard.next();
//^gets user input^
if (!userletters.equalsIgnoreCase(randomWord)) {
//^allows program to enter loop if user has entered a letter^
for (int i = 0; i < userletters.length(); i++) {
char userLetter = userletters.charAt(i);
String T = Character.toString(userLetter);
for (int B = 0; B < ranWord.length; B++) {
//^converts users input to a char and to a string^
if (userLetter == dash[B]) {
System.err.println("This " + userLetter + "' letter already exist");
B++;
//^tells user if the letter they entered already exists^
if (userLetter == dash[B - 1]) {
break;
}
} else if (userLetter == ranWord[B]) {
dash[B] = userLetter;
A--;
}
}
if (!(new String(ranWord).contains(T))) {
LEFT--;
System.out.println("You did not guess a correct letter, you have " + LEFT + " OF "
+ dash.length + " trys left to guess correctly");
}
//^shows how many trys the user has left to get the word right before game ends^
System.out.println(dash);
if (LEFT == 0) {
System.out.println("The word you had to guess was " + word);
break;
}
//^shows the user the word if they didnt guess correctly^
}
} else {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
if (LEFT == 0) {
break;
}
if ((new String(word)).equals(new String(dash))) {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
}
//^if user enters the word it will check and then display that they got the word correct^
System.out.println("Play agian? (y/n)");
String name = keyboard.next();
//^asks user if they want to play again^
if (name.equalsIgnoreCase("n")) {
play = true;
return;
}
//^stops program if user enters n to stop game^
} while (play = false);
}
}
If you want to compare two variables, do not use = operator, which means assignment. Use == instead. Additionally, in your case it should be !=:
while (play != false)
You should use
while (!play)
instead of
while (play = false)
I'm trying to get the "test" or whatever to be printed out inside a file called doctor.txt.
Whenever I run the program, it just comes out to be blank on the file. Also, do you have to make the .txt in the folder beforehand, or does it automatically make the file for you?
Here's my code:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
public class Vowels {
public static void main(String [] args) {
try {
int countA = 0;
int countE = 0;
int countI = 0;
int countO = 0;
int countU = 0;
Scanner in = new Scanner(new File("poetry.txt"));
String poetry = "";
while(in.hasNext()){
poetry = in.nextLine();
poetry = poetry.replaceAll(" ", "~");
System.out.println(poetry);
for(int v = 0; v < poetry.length(); v++) {
if(poetry.charAt(v) == 'a') {
countA++;
}
if(poetry.charAt(v) == 'e') {
countE++;
}
if(poetry.charAt(v) == 'i') {
countI++;
}
if(poetry.charAt(v) == 'o') {
countO++;
}
if(poetry.charAt(v) == 'u') {
countU++;
}
}
}
System.out.println();
System.out.println("The number of 'A's is: " + countA);
System.out.println("The number of 'E's is: " + countE);
System.out.println("The number of 'I's is: " + countI);
System.out.println("The number of 'O's is: " + countO);
System.out.println("The number of 'U's is: " + countU);
FileWriter doctor = new FileWriter("doctor.txt");
doctor.write("test");
}
catch(IOException i) {
System.out.println("Error: " + i.getMessage());
}
}
Put doctor.close(); after doctor.write("test");.
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;
}
}