Export Program that references files on my computer - java

So here is my program:
import java.util.*;
import java.io.*;
import java.util.Random;
public class cardsAgainstHumanity
{
public static void main(String[] args) throws FileNotFoundException
{
Random rand = new Random();
int again = 1;
String blank1 = "";
String blank2 = "";
int playerOneScore = 0;
int playerTwoScore = 0;
String playerOneCard = "";
String playerTwoCard = "";
String[] oneHand = new String[10];
String[] twoHand = new String[10];
Scanner input = new Scanner(System.in);
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
System.out.println("1 = Vanilla \n2 = Rando Cardrissian \n3 = God Is Dead \nInput Game Type (using those numbers) \nJust a note, players hands reset after each round.");
String gameMode = input.nextLine();
Scanner whiteScanner = new Scanner(new File("C:/Users/William/Documents/CardsAgainstHumanityWhite.txt"));
whiteScanner.useDelimiter("<>");
Scanner blackScanner = new Scanner(new File("C:/Users/William/Documents/CardsAgainstHumanityBlack.txt"));
blackScanner.useDelimiter("<>");
int whitecount = 0;
int blackcount = 0;
String[] whiteCardsArray = new String[538];
String[] blackCardsArray = new String[92];
//Inputing cards into array
while(whitecount<=537)
{
whiteCardsArray[whitecount]=whiteScanner.next();
whitecount++;
}
while(blackcount<92)
{
blackCardsArray[blackcount]=blackScanner.next();
blackcount++;
}
//Keeps going and asking questions until again = 0 (meaning they dont want to play again)
while(again == 1)
{
//Asking player One
String currentQuestion = blackCardsArray[rand.nextInt(91)+0];
System.out.println("This is the question: " + currentQuestion);
System.out.println("Player Two look away, Player One hit enter to see your cards.");
blank1 = input1.nextLine();
System.out.println("These are player ones cards: ");
for(int x = 0; x<10; x++)
{
String tmpWhiteString = whiteCardsArray[rand.nextInt(537)+0];
oneHand[x] = tmpWhiteString;
System.out.println((x+1)+":" + " " + oneHand[x]);
}
System.out.println("Please select your card");
playerOneCard = oneHand[(input.nextInt())-1];
//Asking player Two
System.out.println("Player One look away, Player Two hit enter to see your cards.");
blank2 = input2.nextLine();
System.out.println("This is the question: " + currentQuestion);
System.out.println("These are player twos cards: ");
for(int x = 0; x<10; x++)
{
String tmpWhiteString = whiteCardsArray[rand.nextInt(537)+0];
twoHand[x] = tmpWhiteString;
System.out.println((x+1)+":" + " " + twoHand[x]);
}
System.out.println("Please select your card");
playerTwoCard = twoHand[(input.nextInt())-1];
//Tallying Score
System.out.println("Player one selected: " + playerOneCard);
System.out.println("Player two selected: " + playerTwoCard);
System.out.println("The question was: " + currentQuestion);
System.out.println("Who won?");
if(input.nextInt() == 1) playerOneScore++;
else if(input.nextInt() == 2) playerTwoScore++;
System.out.println("Player Ones score is: " + playerOneScore);
System.out.println("Player Twos score is: " + playerTwoScore);
//play another?
System.out.println("Would you like to play another round? (1 for yes, 0 for no)");
again = input.nextInt();
}
if(playerOneScore>playerTwoScore)
{
System.out.println("Player One wins with " + playerOneScore + " points.");
System.out.println("Player Two has " + playerTwoScore + " points");
}
else
{
System.out.println("Player Two wins with " + playerTwoScore + " points.");
System.out.println("Player One has " + playerOneScore + " points");
}
}
}
As you may be able to tell it is a cards against humanity program. I am referencing two files that have the different cards delineated by <>. So white cards are in one file and black cards are in another.
As you can see the program references these files. How can I export the program but still have it work? (P.S. I am a beginner so I have never exported before).
I will be changing this into a form that opens up a basic UI but I just have the basics for now.
Thanks so much in advance,
William

OK, I'm assuming you want to export your program as a JAR. This method will allow you to do this.
Just put the files in your compiled programs folder (typically /bin; if you're in Eclipse, you can put them in /src and have them copied over automatically).
Then get your scanner by using:
Scanner fileScanner = new Scanner(getClass().getResourceAsStream
("Where you kept the file (the root is the bin folder)"));

Related

how to go through a file with names and number scores and figure out who has first, second, third place

I'm having trouble with a problem. I can't figure out why my code is working incorrectly on this problem. The problem description is this -
Ask the user for the file name of the file they want to read from.
If a file is specified that is not available, throw an exception and output "File not found." and close the program.
Otherwise, open the specified file.
Each file will have a list of users' names and their (integer) high scores for the game.
Each line will have one name and one score. This is guaranteed - you don't have to plan for anything else.
Go through all of the users and determine who won first, second, and third place.
You can assume that each file will always have at least three names/scores.
The file I'm working with is a text file called Game1Winners. This is the content of the file:
Mario 58
Link 576
Bowser 354
Yoshi 798
Waluigi 39
Wario 521
Toadsworth 7
Pikachu 21
Luigi 243
This is my code but it's working incorrectly..It's printing out first place correctly, but second and third place are out of order..
import java.util.*;
import java.io.*;
public class HighScores
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.print("What file? ");
String filename = kb.nextLine();
Scanner theFile = null;
try
{
theFile = new Scanner(new FileInputStream(filename));
}
catch(Exception e)
{
System.out.println("File not found.");
System.exit(0);
}
int score = 0;
int high_Score = 0;
int second_Place = 0;
int third_Place = 0;
String name = "";
String store1 = "";
String store2 = "";
String store3 = "";
while(theFile.hasNextLine())
{
name = theFile.next();
score = theFile.nextInt();
if(score > high_Score)
{
high_Score = score;
store1 = name + " with a score of " + high_Score;
}
if(score > second_Place && score < high_Score)
{
second_Place = score;
store2 = name + " with a score of " + second_Place;
}
if(score > third_Place && score < second_Place)
{
third_Place = score;
store3 = name + " with a score of " + third_Place;
}
}
System.out.println("First place: " + store1);
System.out.println("Second place: " + store2);
System.out.println("Third place: " + store3);
}
}

Random poem generator

I need to create a random poem generator while using arrays and input from the user (the user needs to input a minimal of 3 adjectives and 3 nouns) then the program has to randomly combine an adjective with a noun (a noun and an adjective can not be re-used twice) and display it. There needs to be 3 lines in the poem. Here's my code but it doesn't function at all the way it's supposed to! Please tell me what i did wrong!
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner kb = new Scanner (System.in);
char ch;
do{
int x,y;
String noun2, adj;
//The following is my "Welcome"/Opening message to the user
System.out.println(" ---------------------------------------");
System.out.println(" Welcome to the random poem generator!!!");
System.out.println(" ---------------------------------------\n\n");
System.out.println("Please enter a set of relevant nouns and adjectives that are inspired by the themes of nature and wilderness! \n\n");
//The following will work as a prompt message for the user to input a value when demanded
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
if (x >= 3){
String[] noun = new String [x];
for(int j=0; j<noun.length;j++){
System.out.println("Enter your " + x + " nouns: ");
System.out.println(j);
noun[j] = kb.nextLine();
}
}
else{
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
}
if (y >=3){
String[] adjective = new String [y];
for(int j=0; j<adjective.length;j++){
System.out.println("Enter your " + y + " adjectives: ");
System.out.println(j);
adjective[j] = kb.nextLine();
}
}
else{
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
}
System.out.println(" --------------------");
System.out.println(" Here is your poem!!!");
System.out.println(" --------------------\n\n");
String[] poemline = new String[3];
poemline[0] = adj + noun2;
poemline[1] = adj + noun2;
poemline[2] = adj + noun2;
System.out.println(poemline[0]);
System.out.println("/t/t" + poemline[1]);
System.out.println("/t/t/t/t" + poemline[2]);
System.out.println("Would you like to try another poem (y/n)? ");
String answer;
answer = kb.nextLine().trim().toUpperCase();
ch = answer.charAt(0);
}while(ch == 'Y');
}
}
Try this
import java.util.Random;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner (System.in);
char ch;
do{
int x,y;
String noun2 = null;
String adj = null;
//The following is my "Welcome"/Opening message to the user
System.out.println(" ---------------------------------------");
System.out.println(" Welcome to the random poem generator!!!");
System.out.println(" ---------------------------------------\n\n");
System.out.println("Please enter a set of relevant nouns and adjectives that are inspired by the themes of nature and wilderness! \n\n");
//The following will work as a prompt message for the user to input a value when demanded
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
String[] noun = null;
String[] adjective = null;
if (x >= 3){
noun = new String [x];
for(int j=0; j<noun.length;j++){
System.out.println("Enter your " + x + " nouns: ");
System.out.println(j);
noun[j] = kb.nextLine();
}
}
else{
System.out.println("Number of nouns you prefer (minimum 3): ");
x = kb.nextInt();
}
if (y >=3){
adjective = new String [y];
for(int j=0; j<adjective.length;j++){
System.out.println("Enter your " + y + " adjectives: ");
System.out.println(j);
adjective[j] = kb.nextLine();
}
}
else{
System.out.println("Number of adjectives you prefer (minimum 3): ");
y = kb.nextInt();
}
System.out.println(" --------------------");
System.out.println(" Here is your poem!!!");
System.out.println(" --------------------\n\n");
String[] poemline = new String[3];
Random rnd = new Random();
poemline[0] = adjective[rnd.nextInt(y-1)] +" "+ noun[rnd.nextInt(x-1)];
poemline[1] = adjective[rnd.nextInt(y-1)] +" "+ noun[rnd.nextInt(x-1)];
poemline[2] = adjective[rnd.nextInt(y-1)] +" " +noun[rnd.nextInt(x-1)];
System.out.println(poemline[0]);
System.out.println("\t\t" + poemline[1]);
System.out.println("\t\t\t\t" + poemline[2]);
System.out.println("Would you like to try another poem (y/n)? ");
String answer;
answer = kb.nextLine().trim().toUpperCase();
ch = answer.charAt(0);
}while(ch == 'Y');
}
}

Error: cannot find symbol compiling (elementary java)

I'm working on a programming project for my intro class. I have a code that I'm trying to compile, but I'm having a hard time getting it to work after I added the PrintWriter. All was running well until I tried to print to a text file. Can someone help me figure out how to get it to run?
(Also, if you find any errors in my logic/layout/whatever, try to contain it! I still want to debug the program myself, I just can't do that until it runs :)
Attempt: (so far)
import java.util.Scanner; //import scanner
import java.util.Random; //import randomizer
import java.io.*; //needed for throws clause
public class randomLottery
{
public static void main(String[] args) throws IOException
{
String fullName;
Scanner keyboard = new Scanner( System.in );
//so we can generate random numbers
Random rand = new Random();
//declare a constant number of numbers
final int LOTTERY_NUMBERS = 5;
//Retrieve names
System.out.print("Please enter a first and last name for lottery "
+ "entry (type 'quit' to end): ");
fullName = keyboard.nextLine();
while(!fullName.contains(" "))
{
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
while(!fullName.contains("quit"))
{
//separate first/last name
String[] parts = fullName.split(" ");
String firstName = parts[0];
String lastName = parts[1];
//Open the file
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
//Print the name onto the file
outputFile.print(lastName + ", " + firstName + ": ");
int number;
for (number = 1; number <= LOTTERY_NUMBERS; number++)
{
if (number == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.println(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
//get the next name
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
//Winning Lottery Numbers
outputFile.print("The winning numbers are: ");
int winning;
for (winning = 1; winning <= LOTTERY_NUMBERS; winning++)
{
if (winning == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
outputFile.close();
}
}
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
Should be outside (before) the while loop. Having it inside the loop means it is not in the scope of your other uses of outputFile after the while loop.

Check if user entered both a first and last name

I'm making a program that gives random lottery numbers to inputted names. The problem though is that I have to make sure the user entered both a first and last name. I'm using a method of finding the space in the users input, then creating substrings from that data, but I keep on getting the error "incompatible type" right under my for loop. Any help would be greatly appreciated!
enter code here
import java.util.Scanner; //Import scanner class
import java.util.Random; //Import random number generator
import java.io.*; //Import PrintWriter
public class Lab4ZinkovskyFl //Program that lets user enter a name and generates random lottery numbers for that name
{
public static void main (String[] args) throws IOException
{
Scanner keyboard = new Scanner (System.in);
Random randomNumbers = new Random();
String again = "y"; //Control the loop
int r1 = randomNumbers.nextInt(100)+ 1; //*******************
int r2 = randomNumbers.nextInt(100)+ 1; //* Random lottery
int r3 = randomNumbers.nextInt(100)+ 1; //* numbers for
int r4 = randomNumbers.nextInt(100)+ 1; //* program
int r5 = randomNumbers.nextInt(100)+ 1; //*******************
while (again.equalsIgnoreCase ("y")) // Allows the user to continue the loop
{
System.out.println ("Please enter first and last name to enter the lottery.");
String fullName = keyboard.nextLine();
boolean space = false; // Checks for first and last name
for (int i = 0; i < fullName.length(); i++)
{
if (fullName.indexOf(i) == " ")
{
space = true;
spaceIndex = i;
}
else
{
System.out.println ("Error, please enter both first and last name to continue.");
}
}
String firstName = fullName.substring (0, spaceIndex);
String lastName = fullName.substring (spaceIndex, fullName.length());
System.out.println (lastName + ", " + firstName + ": " + r1 + ", " + r2 + ", " + r3 + ", " + r4 + ", " + r5);
System.out.println ("Run the lottery again? (y=yes)");
again = keyboard.nextLine();
}
}
}
You can split the user input by " ", like this:
String[] names = fullName.split(" ");
And then you create a method to return true if the user do enters the full name.
for (int i = 0 ; i < names.length ; i++) {
if (names[i].trim().equals("")) {
names[i] = null;
}
}
int elementsWithText = 0;
for (int i = 0 ; i < names.length ; i++) {
if (names[i] != null) {
elementsWithText++;
}
}
return elementsWithText == 2;
Something like that. Hopefully you figure what I am doing. If you don't know what the methods calls are doing, they are all from String. Here is the docs:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
indexOf() takes in a char as input (in your case). Change i to " "(space)
You need to write like this
if (fullName.indexOf(" ") == -1)
{
System.out.println ("Error, please enter both first and last name to continue.");
}
else
{
space = true;
spaceIndex = i;
}
But why you choose for loop?
#sweeper has given the best solution.

Why variable outside for loop doesn't work? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a for loop which stores results in an int array and from these results I need to be able to search for eg. how many 1 are in the array so I declared an int variable outside the loop but it keeps saying that my array hasn't been initialized. Could you guys help me thanks.
import java.util.Scanner;
import java.util.Arrays;
class TestDie {
public static void main (String [] args)
{
Die firstDie = new Die();
int[] playerOneResults;
firstDie.roll();
System.out.println(firstDie.getFaceValue());
Scanner userInput = new Scanner(System.in);
System.out.println("PLease enter the name of player one");
String playerOneName = userInput.next();
System.out.println("Please enter the name of player two");
String playerTwoName = userInput.next();
System.out.println("Enter the number of dice to be thrown");
int numDice = userInput.nextInt();
System.out.println("First player's name: " + playerOneName);
System.out.println("Second player's name: " + playerTwoName);
System.out.println("Number of dice will be thrown: " + numDice);
for(int counter = 0; counter != numDice; counter++)
{
playerOneResults = new int[numDice];
firstDie.roll();
playerOneResults[counter] = firstDie.getFaceValue();
System.out.println("Player one results: " + playerOneResults[counter]);
}
Arrays.sort(playerOneResults);
int c = Arrays.binarySearch(playerOneResults, 1);
System.out.println(c);
}
}
Try this code
public static void main(String args[]) {
Die firstDie = new Die();
int[] playerOneResults = null;
firstDie.roll();
System.out.println(firstDie.getFaceValue());
Scanner userInput = new Scanner(System.in);
System.out.println("PLease enter the name of player one");
String playerOneName = userInput.next();
System.out.println("Please enter the name of player two");
String playerTwoName = userInput.next();
System.out.println("Enter the number of dice to be thrown");
int numDice = userInput.nextInt();
System.out.println("First player's name: " + playerOneName);
System.out.println("Second player's name: " + playerTwoName);
System.out.println("Number of dice will be thrown: " + numDice);
playerOneResults = new int[numDice];
for (int counter = 0; counter != numDice; counter++) {
firstDie.roll();
playerOneResults[counter] = firstDie.getFaceValue();
System.out.println("Player one results: " + playerOneResults[counter]);
}
Arrays.sort(playerOneResults);
int position=0;
while(position<0){
int c = Arrays.binarySearch(playerOneResults, position,playerOneResults.length-1, 1);
position=c;
System.out.println(c);
}
}

Categories