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.
Related
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);
}
}
So my program is supposed to read a list of names from a URL in order to play guess the name game; however, the program does not seem to be able to read anything from the URL, let alone add it onto an ArrayList. When running the program, all I get is "There are 0 names in this list" meaning that no names had been added from the URL.
When I use the debugger and step into the URL, I get an error saying "can't step, selected thread is not suspended."
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class NameGuesser {
private ArrayList<String> lastNames = new ArrayList<String>();
Scanner input = new Scanner(System.in);
public void readNames() throws IOException, MalformedURLException {
// Read the last names
URL url = new URL(
"http://www2.census.gov/topics/genealogy/1990surnames/dist.all.last");
Scanner in = new Scanner(url.openStream());
while (in.hasNext()) {
// Read the last name
String lastName = in.next();
lastNames.add(lastName);
// Ignore the statistical information
// in.nextDouble();
// in.nextDouble();
// in.nextInt();
}
in.close();
// Print out the number of names in the file and
// Sort the names using Collections
Collections.sort(lastNames);
System.out.println("There are " + lastNames.size() + " names in this list");
}
public int guessName() {
int counter = 0;
int low = 0;
int high = lastNames.size();
int mid = high / 2;
boolean notFound = true; //variables to hold game info
String userInput = "";
while (notFound) { //while the name is not found
System.out.println("Does your name come before " + lastNames.get(mid) + " in the dictionary? (Y/N), or is " + lastNames.get(mid) + " your name? (S)");
userInput = input.next(); //ask if it is in the middle
if (userInput.equalsIgnoreCase("Y")) { //if before, set new upper bound
high = mid;
mid = ((high - low)/2) + low;
counter++;
} else if(userInput.equalsIgnoreCase("N")){ //if after, set new lower bound
counter++;
low = mid;
mid = ((high - low)/2) + low;
}
else{ //if name is found, return counter
System.out.println("Your name, " + lastNames.get(mid) + ", was found with " + counter + " guesses.");
input.close();
return counter;
}
if(high == low){ //if upper and lower bounds are equal
System.out.println("Is your name: " + lastNames.get(mid) + " ? (Y/N)");
userInput = input.next(); //ask if name is found
if(userInput.equalsIgnoreCase("Y")){ //if yes, print success, counter, and return counter
System.out.println("Your name, " + lastNames.get(mid) + ", was found with " + counter + " guesses.");
input.close();
return counter;
}
else if(userInput.equalsIgnoreCase("N")){ //if no, inform user that guesser failed
System.out.println("Name not found. Attempted locating with " + counter + " guesses");
input.close();
return counter;
}
}
}
input.close();
return counter;
}
}
Tester Method:
import java.io.IOException;
import java.net.MalformedURLException;
public class NameGame {
public static void main(String[] args) throws MalformedURLException, IOException {
NameGuesser game = new NameGuesser();
game.readNames();
}
}
Have you tried opening the URL in a browser? It redirects to a secure protocol (HTTPS).
Change your URL to "https://www2.census.gov/topics/genealogy/1990surnames/dist.all.last" and it should work fine.
I'm new to Java and I'm attempting to learn off different sites and videos and I've been stuck on a problem for a couple of days now and I'm wondering can anyone help out. What I'm trying to do is ask the user how many key actors are in a film. Then i want to ask the actors name and the role they play in the film, this should be asked for each actor for however many the user specified are in the film before finally displaying the actors name and his role?
import java.util.Scanner;
public class rough {
public static void main(String[] args) {
// TODO Auto-generated method stub
int actorCount;
Scanner input = new Scanner(System.in);
Scanner kb = new Scanner(System.in);
System.out.println("How many actors are in the film? ");
actorCount = kb.nextInt();
for (int k = 1; k <= actorCount ; k++)
{
float actor, character;
System.out.println("What is the actors name? ");
actor = kb.nextFloat();
System.out.println("What is " + actor + "'s character?");
character = kb.nextFloat();
System.out.print(actor + " - " + character);
}
kb.close();
input.close();
}
}
This is what I would have done:
import javax.swing.*;
public class rough {
public static void main(String[] args) {
// TODO Auto-generated method stub
int actorCount;
String output = "";
actorCount = Integer.parseInt(JOptionPane.showInputDialog(null,"How many actors are in the film? "));
for (int k = 1; k <= actorCount ; k++)
{
String actor, character;
actor = JOptionPane.showInputDialog(null, "What is the actors name?");
character = JOptionPane.showInputDialog(null, "What is " +actor + "s character?");
output += actor + " - " + character + "\n";
}
JOptionPane.showMessageDialog(null, output);
}
}
Remember that if you want all of the roles/actors to be printed at the same time you must put the print outside the for loop and store the roles/actors to some output String. Moreover, I cannot see why you have used a float variable for the roles/actors a String would be the most logical.
So you should do it in this way:
public static void main(String[] args) {
int actorCount;
Scanner input = new Scanner(System.in);
Scanner kb = new Scanner(System.in);
System.out.println("How many actors are in the film? ");
actorCount = kb.nextInt();
String[][] actorValues = new String[actorCount][2];
for (int k = 0; k < actorCount ; k++)
{
String actor, character;
System.out.println("What is the actors name? ");
actor = kb.next();
System.out.println("What is " + actor + "'s character?");
character = kb.next();
System.out.print(actor + " - " + character +"\n");
actorValues[k][0] = actor;
actorValues[k][1] = character;
}
//Printout the Characters in the List
System.out.println("All Actors:");
for (int i = 0; i < actorValues.length; i++) {
String[] strings = actorValues[i];
System.out.println("Actorssname: "+strings[0]+" Character:"+strings[1]);
}
kb.close();
input.close();
}
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.
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)"));