Reading From Text-file and Implementing Switch Statement - java

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

Related

This code is supposed to get N values from the user. Then input then into a .txt file [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 3 years ago.
Improve this question
This code is supposed to get N values from the user. Then input the values into a .txt file. I'm having trouble getting the values to show in the .txt file. Not sure why.
// This program writes data into a file.
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("namef.txt");
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
PrintWriter outputfile = new PrintWriter("/Users/******/Desktop/namef.txt");
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for ( int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
input.nextInt();
outputfile.print(N);
}
System.out.println("Data entered into the file.");
inputFile.close(); // Close the file.
}
} // End of class
In your program you seemed to have thrown everything and hoping that it works. To find out what class you should use you should search it in Javadoc of you Java version.
Javadoc of Java 12
PrintWriter:
Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
FileWriter:
Writes text to character files using a default buffer size. Encoding from characters to bytes uses either a specified charset or the platform's default charset.
Scanner (File source):
Constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.
Now you can see what each class is for. Both PrintWriter and FileWriter are used to write file however PrintWriter offer more formatting options and Scanner(File source) is for reading files not writing files.
Since there is already an answer with PrintWriter. I am writing this using FileWriter.
public static void main(String[] args) throws Exception {
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
// You can provide file object or just file name either would work.
// If you are going for file name there is no need to create file object
FileWriter outputfile = new FileWriter("namef.txt");
System.out.print("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++) {
System.out.print("Enter the number into the file: ");
// Writing the value that nextInt() returned.
// Doc: Scans the next token of the input as an int.
outputfile.write(Integer.toString(input.nextInt()) + "\n");
}
System.out.println("Data entered into the file.");
input.close();
outputfile.close(); // Close the file.
}
Output:
Enter the number of data (N) you want to store in the file: 2
Enter 2 numbers below:
Enter the number into the file: 2
Enter the number into the file: 1
Data entered into the file.
File:
2
1
Here's a working variant of what you want to achieve:
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("path/to/your/file/namef.txt");
PrintWriter outputfile = new PrintWriter(fname);
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
int tmp = input.nextInt();
outputfile.print(tmp);
}
System.out.println("Data entered into the file.");
outputfile.close(); // Close the file.
}
}
Several comments on above:
1) Got rid of redundant rows:
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
You actually didn't use them at all.
2) In PrintWriter we pass File object, not String.
3) In for loop there was a logic mistake - on every iteration you should have written N instead of actual number which user entered on console.
4) Another mistake was in closing wrong file in the last line.
EDIT: adding according to comment.
in point 2) there's an alternative way - you can skip creating File object and pass as a String a path to even non-existing file directly in PrintWriter, like this:
PrintWriter outputfile = new PrintWriter("path/to/your/file/namef.txt");

Printer Writer making me input twice to loop once

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

Searching a list of names in a text file from user input

I'm currently in an Introductory Java class at University and I'm having a bit of trouble. Last semester we started with Python and I became very acquainted with it and I would say I am proficient now in writing Python; yet Java is another story. Things are alot different. Anyway, Here is my current assignment: I need to write a class to search through a text document (passed as an argument) for a name that is inputted by the user and output whether or not the name is in the list. The first line of the text document is the amount of names in the list.
The text document:
14
Christian
Vincent
Joseph
Usman
Andrew
James
Ali
Narain
Chengjun
Marvin
Frank
Jason
Reza
David
And my code:
import java.util.*;
import java.io.*;
public class DbLookup{
public static void main(String[]args) throws IOException{
File inputDataFile = new File(args[0]);
Scanner stdin = new Scanner(System.in);
Scanner inFile = new Scanner(inputDataFile);
int length = inFile.nextInt();
String names[] = new String[length];
for(int i=0;i<length;i++){
names[i] = inFile.nextLine();
}
System.out.println("Please enter a name that you would like to search for: ");
while(stdin.hasNext()){
System.out.println("Please enter a name that you would like to search for: ");
String input = stdin.next();
for(int i = 0;i<length;i++){
if(input.equalsIgnoreCase(names[i])){
System.out.println("We found "+names[i]+" in our database!");
break;
}else{
continue;
}
}
}
}
}
I am just not getting the output I am expecting and I cannot figure out why.
Try this
You should trim() your values as they have extra spaces
if(input.trim().equalsIgnoreCase(names[i].trim()))
I have run your example it runs perfectly after using trim(), you have missed to trim()
Create a seperate scanner class to read line by line.You can use BufferedReader also.
final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String str= scanner.nextLine();
if(str.contains(name)) {
// Found the input word
System.out.println("I found " +name+ " in file " +file.getName());
break;
}
}
If you use Java 8:
String[] names;
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
names = stream.skip(1).toArray(size -> new String[size]);
} catch (IOException e) {
e.printStackTrace();
}

Read specific characters from specific line of text in java

I am working on a program that involves me having to search a specific line in a .txt file and convert the string inside of it into something else.
For example, the string is actually made of numbers which I suppose I can convert into ints. The main thing is that for example, on line 2, there are 5 digits for zip code stored. I need to convert that into certain outputs, depending on the numbers. In other words, I need variables from digits 0-9 and depending on each digit, output a specific output.
Right now here is the code I have to prompt the user for information that is stored in the file, and can read and print all of the information that was just typed, but I'm unsure how to go about the rest.
import java.io.*;
import java.util.*;
import java.io.FileReader;
import java.io.IOException;
public class ObjectTest2 {
public static void main(String [] args) throws FileNotFoundException, IOException {
// The name of the file to open.
String fileName = "information.txt";
Scanner myScanner = new Scanner(System.in);
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
// append a newline character.
//This shit here prompts the user for information and stores it in seperate lines to be
//called on by the later section.
System.out.print("What is your name? ");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your 5 digit zip code?");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your +4 digit zip? ");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your address? ");
bufferedWriter.write(myScanner.nextLine());
// Always close files.
bufferedWriter.close();
//reads the information file and prints what is typed
BufferedReader reader = new BufferedReader(new FileReader("information.txt")); {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
}
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
You are left with no choice but to iterate over each line of the file and search for the String. If you want to get a line of string from the file based on line number, consider creating a method. If the operation is required to be performed several times on the same file and if the contents of the file do not change, use a map to cache the file contents based on the line number.

Program does not scan a text file (Java)

I was having trouble getting my program to read from a file "lexicon.txt"
My task was to have the program scan a user input and getting the word count for the program in return. Do you guys know what's going on in my code?
import java.io.*;
import java.util.Scanner;
public class searchFile {
public static void main (String args[]) throws IOException {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the file name (e.g: nonamefile.txt)");
String objective = reader.nextLine();
if (!(objective.equals("lexicon.txt"))) {
System.out.println("ERROR: Missing File");
}
else {
Scanner reader2 = new Scanner(System.in);
Scanner lexicon = new Scanner(new File("lexicon.txt"));
int wordCount = 0;
System.out.println("What word do you need to look up?");
String objective2 = reader2.nextLine();
while (lexicon.hasNext()) {
String word = lexicon.next();
if (word.equalsIgnoreCase(objective2)){
wordCount++;
}
}
System.out.println("Word count = " + wordCount);
}
} // end main method (String Args[])
} // end class searchFile
I ran your code on my computer. It is to help you. may be you are not doing same.
Please enter the file name (e.g: nonamefile.txt)
lexicon.txt
What word do you need to look up?
three
Word count = 3
The text I used in lexicon.txt was that :
one
two two
three three three
And it is working fine.
Remember, just copy paste is not like what you think it. there could be any character in clipboard when you copy that you cannot see, and pasting it also pastes these code too in your text file.
Scanner.next() looks for the next string delimited by word boundries.
Suppose there is a text that you copy pasted :
which is not visible in notepad :
So when you will search for "Hello", it will not be there.
You will have to search for instead, but you cannot write this easily.

Categories