Printer Writer making me input twice to loop once - java

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++;
}

Related

How to input String in Java in line by line or like 50 characters per line

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);
}
}
}

How to print a specific word in a text file in Java

so as you can see i have a text file that goes like this one:
unbelievable, un, believe, able
mistreatment, mis, treat, ment
understandable, understand, able
I need to get the morphemes or each word like for example if I typed in the word MISTREATMENT, the output would be MIS, TREAT, MENT and the root word is TREAT.
Here's my code so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class morph {
public static void main(String[] args) throws IOException {
System.out.println("Enter a word: ");
Scanner sc = new Scanner (System.in);
sc.nextLine();
BufferedReader br = new BufferedReader(new FileReader("C:/Users/xxxx/Desktop/morphemes.txt"));
String line = null;
while ((line = br.readLine()) != null) {
//i'm stuck
System.out.println("The morpheme words are: "); // EG: mis , treat, ment
System.out.println("The Root word is: "); // EG: treat
}
}
}
The output should be:
Enter a word: mistreatment
The morpheme words: mis, treat, ment
The root word is: treat
The question is how do i print a specific data in the text file. I don't know i am gonna use an if else statement or a dictionary. If you're gonna tell me that it should be a dictionary please help me out. This is an NLP topic btw
I guess the method String.split() can help you here.
public String[] words = line.split(String ",");
// Check if first word in the line equals to the input
if (words != null && !words.isEmpty() && words[0].equals(sc.toString()))
{
System.out.println("The morpheme words are: "+words[1]+words[2]);
System.out.println("The Root word is: "+words[2]);
}

Creating a File that will read a txt file

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.

Reading From Text-file and Implementing Switch Statement

I need help to read data from text file and give output based on user input.
Here is data I have saved in notepad under "data.txt" file
C|C,370,0.154
C||C,680,0.13
C|||C,890,0.12
C|H,435,0.11
C|N,305,0.15
C|O,360,0.14
C|F,450,0.14
C|Cl,340,0.18
O|H,500,0.10
O|O,220,0.15
O|Si,375,0.16
N|H,430,0.10
N|O,250,0.12
F|F,160,0.14
H|H,435,0.074
this is how I have data in notepad. yes, each entry is separated by comma
I know basic reading operation Scanner class reads line and spits out text from each line but this time I am inputting either number of bonds or bond length and it gives me the output of remaining two value.
Assignment:
No, I am not here to ask you to do homework but rather help me learn the process.
import java.io.*;
import java.io.FileNotFoundException;
import java.util.*;
public class LearnReadText
{
public static void main (String args[]) throws FileNotFoundException
{
Scanner input = new Scanner(System.in);
String strResponse="";
do
{
System.out.println("\nChapter 7");
System.out.println("L - Bond Length");
System.out.println("N - Bond Numbers (1=single, 2=double, 3=triple)\n");
System.out.println("Q - quit program.");
strResponse = input.nextLine();
strResponse = strResponse.toUpperCase();
Scanner file = new Scanner(new File("data.txt"));
file.close();
}
while (!strResponse.equals("Q"));
System.out.println("\n\nThank you and have a nice day.");
input.close();
}
}

regext copying second, third and fourth word

I am trying to get the 2nd, 3rd, and 4th word from a file into another file, so far I know how to read a file and I have been trying different things but I don't get it right the code to get the words. This program will read the file.
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
class PrintLines{
public static void main(String[] args) throws FileNotFoundException {
Scanner me = new Scanner(System.in);
System.out.print("File Name: ");
String s = me.next();
File inFile = new File(s);
Scanner in = new Scanner(inFile);
while(in.hasNextLine()){
String line = in.nextLine();
System.out.print(line + "\n");
}
in.close();
}
}
I have tried:
int i=0;
while(!Character.isDigit(in.charAt(i))){
i++;
}
to skip the first numbers, and then get the next three words, but I don't get it right:
986 Nasir 829 0.0040 Janine 1352 0.0069
I would appreciate any advice. Thank you
You can use String.split method
String[] split = line.split(" "); // split by space
System.out.println(split[1] + split[2] + split[3]); // watch out for the array's bounds

Categories