So i am currently trying to figure out how my code can read my txt file. My objective is to prompt what ever i have for initialization, then ask me to type a number but 0 to get a message that i have written on my txt file. Then finally by finishing by typing 0 and getting what ever message i have for the finish. I have read online articles but i still have trouble. This is what i have so far:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.ArrayList;
public class FortuneFile
{
static Scanner keyboard;
static int inputLine;
static Scanner inputFile;
static boolean done;
public static void main(String[] args) throws Exception
{
initialization();
while (inputFile.hasNext())
while (!done)
{
mainLoop();
}
finish();
}
public static void initialization() throws Exception
{
Scanner inputFile = new Scanner(new File("FortuneCookie.txt"));
keyboard = new Scanner(System.in);
done = false;
System.out.println("");
System.out.println("Welcome to the Command Box FortuneCookie game!");
System.out.println("====================================================================");
System.out.println("Dare to try your luck?... You could be a Winner or a Looser!");
System.out.println("");
System.out.println("Enter \"0\" if you are scared, or if you are brave, try any number: ");
System.out.println("====================================================================");
}
public static void mainLoop() throws Exception
{
inputLine = inputFile.nextInt();
i++;
if (keyboard.equals("0"))
{
done = true;
}
else
{
{
System.out.println("");
}
System.out.print("Care to try again? ");
System.out.println("");
}
}
public static void finish()
{
System.out.println("====================================================================");
System.out.println("Thanks for playing along. I hope you are not traumatised!");
}
}
Thank you!! :)
There are some problems in your code:
First, You missed declaring i in your mainLoop() method so that it can't compile successfully.
Second, keyboard is a Scanner object which can't be compared with String object 0 by equals()
keyboard is a Scanner object. It can't be compared like String with equals("0").
When you are reading nextInt(), store the value in int variable and compare thar value is 0 or not to end the loop.
You are using keyboard.equals() which is wrong as keyboard is a Scanner object and not a String. You should use keyboard.nextLine() to get the input from the user and store this in a String. So you'll have something like,
String holder = keyboard.nextLine();
An easier way to to this would be to read in the integer using something like,
int holder = keyboard.nextInt();
and then compare this integer with 0 using ==
Check out this link for more information on Scanners in Java;
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Also in initialize() you're making a new local Scanner inputFile that you use in the method. The problem with this is that when you make calls to inputFile outside initialize() you'll run into problems as inputFile outside initialize() is not defined to operate on the file you're using. This is a scope resolution issue.
You'd just want to do, inputFile = new Scanner(new File("FortuneCookie.txt"));
Also make sure that this text file is in the same directory as your project's, otherwise you'll have to describe the complete path.
Make sure you understand your scope resolution as this can cause various problems.
I hope this was helpful!
Good luck!
Try this:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.ArrayList;
public class FortuneFile
{
static Scanner keyboard;
static int inputLine;
static Scanner inputFile;
static boolean done;
static String myMessage;
public static void main(String[] args) throws Exception
{
initialization();
//create an object that reads integers:
Scanner Cin = new Scanner(System.in);
inputLine = Cin.nextInt();
while(inputLine != 0){
System.out.println("");
System.out.print("Care to try again? ");
System.out.println("");
System.out.println("Enter another integer: ");
inputLine = Cin.nextInt();
}
System.out.println(myMessage);
finish();
}
public static void initialization() throws Exception
{
Scanner inputFile = new Scanner(new File("C:/FortuneCookie.txt"));
//keyboard = new Scanner(System.in);
//Read the first line
myMessage = inputFile.nextLine();
//System.out.println(myMessage);
done = false;
System.out.println("");
System.out.println("Welcome to the Command Box FortuneCookie game!");
System.out.println("====================================================================");
System.out.println("Dare to try your luck?... You could be a Winner or a Looser!");
System.out.println("");
System.out.println("Enter \"0\" if you are scared, or if you are brave, try any number: ");
System.out.println("====================================================================");
}
public static void finish()
{
System.out.println("====================================================================");
System.out.println("Thanks for playing along. I hope you are not traumatised!");
}
}
You can remove my main loop and put it in another procedure if you want. I am checking the input with 0. If it is zero, it is the end. If not, it will remain in the loop. I put my file in drive c. You can change your address to your file location. This is the result:
And this was the body of my text file:
I hope this solves your problem. Please let me know if you have any other question.
Related
So, I am creating a program in which the user has to enter the body(message) of the email. Now when I display that instead of doing it in a proper way the compiler just displays a long line. I have tried using \n but it doesn't work.
System.out.println("Enter message");
Scanner e4 = new Scanner(System.in);
String message = e4.nextLine();
System.out.println(message);
I have a solution for you. You can keep pushing line after line onto an ArrayList until you see a particular end string. In my example it's "end", but equally it could be "</p>" or something else.
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Scan {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter here:");
List<String> input = new ArrayList<String>();
while(true) {
String temp = in.nextLine();
if(temp.equals("end"))
break;
input.add(temp);
}
for(String s : input) {
System.out.println(s);
}
}
}
I know this is going to be stupid easy to fix but I've been battling it for an hour. I need to keep getting words from the user until they type "quit" and write them to a file in the process. But here's the problem, it comes up with the "Enter Word: " but then I type it and hit enter it doesnt take it until I write something a SECOND time then it works and uses the second one.
//#Author: Tyler Cage
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class week12Program1 {
public static void main(String[] args) throws FileNotFoundException, IOException{
//declaring the writer and initlizing it
FileOutputStream fileByteStream = new FileOutputStream("C:/Users/tyl3r/Desktop/test.txt");
PrintWriter outFS = new PrintWriter(fileByteStream);
Scanner scnr = new Scanner(System.in);
//declainrg ints
int i = 0;
//open file and print
while(i<1){
System.out.println("Enter word: ");
outFS.println(scnr.next());
outFS.flush();
if(scnr.next().equalsIgnoreCase("quit")){
System.out.println("Shutting down...");
fileByteStream.close();
i++;
}
}
}
}
The problem in this section of code:
while(i<1){
System.out.println("Enter word: ");
outFS.println(scnr.next()); // first time scanning input
outFS.flush();
if(scnr.next().equalsIgnoreCase("quit")){ // second time scanning input
System.out.println("Shutting down...");
fileByteStream.close();
i++;
}
Actually you are reading the inputs 2 times so you need to enter the word another time to get the expected result.
To solve the problem you only need to declare variable to save input in it and then check the variable content at if condition:
while(i<1){
System.out.println("Enter word: ");
String word = scnr.next();
outFS.println(word);
outFS.flush();
if(word.equalsIgnoreCase("quit")){
System.out.println("Shutting down...");
fileByteStream.close();
i++;
}
Following is my code that I am working on for a school project. It does ok up until I try to read the animal.txt file. Can someone please tell me what I am doing wrong? I am attaching my compilation error as an image. Thanks in advance.
[input error image1
package finalproject;
//enabling java programs
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.FileInputStream;
import java.io.IOException;
public class Monitoring {
public static void choseAnimal() throws IOException{
FileInputStream file = null;
Scanner inputFile = null;
System.out.println("Here is your list of animals");
file = new FileInputStream("\\src\\finalproject\\animals.txt");
inputFile = new Scanner(file);
while(inputFile.hasNext())
{
String line = inputFile.nextLine();
System.out.println(line);
}
}
public static void choseHabit(){
System.out.println("Here is your list of habits");
}
public static void main(String[] args) throws IOException{
String mainOption = ""; //user import for choosing animal, habit or exit
String exitSwitch = "n"; // variable to allow exit of system
Scanner scnr = new Scanner(System.in); // setup to allow user imput
System.out.println("Welcome to the Zoo");
System.out.println("What would you like to monitor?");
System.out.println("An animal, habit or exit the system?");
mainOption = scnr.next();
System.out.println("you chose " + mainOption);
if (mainOption.equals("exit")){
exitSwitch = "y";
System.out.println(exitSwitch);
}
if (exitSwitch.equals( "n")){
System.out.println("Great, let's get started");
}
if (mainOption.equals("animal")){
choseAnimal();
}
if (mainOption.equals("habit")) {
choseHabit();
}
else {
System.out.println("Good bye");
}
}
}
\\src\\finalproject\\animals.txt suggests that the file is an embedded resource.
First, you should never reference src in you code, it won't exist once the program is built and package.
Secondly, you need to use Class#getResource or Class#getResourceAsStream in order to read.
Something more like...
//file = new FileInputStream("\\src\\finalproject\\animals.txt");
//inputFile = new Scanner(file);
try (Scanner inputFile = new Scanner(Monitoring.class.getResourceAsStream("/finalproject/animals.txt"), StandardCharsets.UTF_8.name()) {
//...
} catch (IOException exp) {
exp.printStackTrace();
}
for example
Now, this assumes that file animals.txt exists in the finalproject package
The error message clearly shows that it can't find the file. This means there's two possibilities:
File does not exist in the directory you want
Directory you want is not the directory you have.
I would start by creating a File object looking at "." (current directory) to and printing that to see what directory it looks by default. You may need to hard code the file path, depending on what netbeans is using for a default directory.
I am trying to write a program that inputs a text file through the command line and then prints out the number of words in the text file. I've spent around 5 hours on this already. I'm taking an intro class using java.
Here is my code:
import java.util.*;
import java.io.*;
import java.nio.*;
public class WordCounter
{
private static Scanner input;
public static void main(String[] args)
{
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
openFile();
readRecords();
closeFile();
}
public static void openFile()
{
try
{
input = new Scanner(new File(file));
}
catch (IOException ioException)
{
System.err.println("Cannot open file.");
System.exit(1);
}
}
public static void readRecords()
{
int total = 0;
while (input.hasNext()) // while there is more to read
{
total += 1;
}
System.out.printf("The total number of word without duplication is: %d", total);
}
public static void closeFile()
{
if (input != null)
input.close();
}
}
Each way I've tried I get a different error and the most consistent one is "cannot find symbol" for the file argument in
input = new Scanner(new File(file));
I'm also still not entirely sure what the difference between java.io and java.nio is so I have tried using objects from both. I'm sure this is an obvious problem I just can't see it. I've read a lot of similar posts on here and that is where some of my code is from.
I've gotten the program to compile before but then it freezes in command prompt.
java.nio is the New and improved version of java.io. You can use either for this task. I tested the following code in the command line and it seems to work fine. The "cannot find symbol" error message is resolved in the try block. I think you were confusing the compiler by instantiating a File object named file twice. As #dammina answered, you do need to add the input.next(); to the while loop for the Scanner to proceed to the next word.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class WordCounter {
private static Scanner input;
public static void main(String[] args) {
if(args.length == 0) {
System.out.println("File name not specified.");
System.exit(1);
}
try {
File file = new File(args[0]);
input = new Scanner(file);
} catch (IOException ioException) {
System.err.println("Cannot open file.");
System.exit(1);
}
int total = 0;
while (input.hasNext()) {
total += 1;
input.next();
}
System.out.printf("The total number of words without duplication is: %d", total);
input.close();
}
}
Your code is almost correct. Thing is in the while loop you have specified the terminating condition as follows,
while (input.hasNext()) // while there is more to read
However as you are just increment the count without moving to the next word the count just increases by always counting the first word. To make it work just add input.next() into the loop to move to next word in each iteration.
while (input.hasNext()) // while there is more to read
{
total += 1;
input.next();
}
I am trying to have user input an interger, based on the integer value, I am calling mix function to read in the file contents as code shows below. I am getting, this error:
Project2.java:43: variable urlScan might not have been initialized
while (urlScan.hasNext())
^
Project2.java:34: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
fileScan = new Scanner (new File("input.txt"));
^
Any ideas, what I might be doing wrong here?
import java.util.Scanner;
import java.io.*;
public class Project2
{
public static void main(String[] args)
{
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan= new Scanner(System.in);
input = scan.nextInt();
System.out.println(input);
if(input==1) {
mix();
}
else{
System.out.println("this is exit");
}
}
public static void mix()
{
String url;
Scanner fileScan, urlScan;
fileScan = new Scanner (new File("input.txt"));
// Read and process each line of the file
while (fileScan.hasNext())
{
url = fileScan.nextLine();
System.out.println ("URL: " + url);
//urlScan = new Scanner (url);
//urlScan.useDelimiter("/");
// Print each part of the url
while (urlScan.hasNext())
System.out.println (" " + urlScan.next());
System.out.println();
}
}
}
The errors are pretty expressive.
Initialize your urlScan local variable(local variables don't get default values)
Wrap the fileScan = new Scanner (new File("input.txt")); around try/catch. or declare that your method might throw FileNotFoundException in your method signature. (new File(str) might throw FileNotFoundException which is a checked exception and compiler will force your handled it).
First, urlScan isn't initialized.
Second, you should surround fileScan = new Scanner (new File("input.txt")); with an try/catch for FileNotFoundException.
Local variables must be initialized before use, so uncomment this line:
urlScan = new Scanner (url);