Java reading a string from a text(txt) file - java

Rod
Rae
Bryan
Shiroe
Ric
Kirito
Asuna
Elsa
Akutabe
Shino
I have that list saved in a text file. If I were to enter Rod, it should say "Exists" and if I enter a name that is not on the list, it should say "Does not exist." But what is happening on my code is that it reads the file per line and prints "Does not exist" if it does not match the string line.
So if I were to enter a name that does not exist in the txt file, it would print 10 "Does not exist" lines.
This is my code below:
Scanner in = new Scanner(System.in);
out.print("Enter name: ");
String name = in.nextLine();
BufferedReader br = new BufferedReader(new FileReader("name.txt"));
String line;
while ((line = br.readLine()) != null) {
if (line.contains(name)) {
out.println("Exists");
break;
} else {
out.println("Does not exist");
}
}
br.close();
An example of a what would be output is:
name = Kirito
Does not exist
Does not exist
Does not exist
Does not exist
Exists
Why does my program print so many Does not exist before finding the exact match?

Use a boolean to remember whether you have found a match, and display "Does not exist" only after checking every item and only if you have not found a match.

You were almost there. You are just preemptively printing the error message. I would have also used equals instead of contains and pre-loaded the entire file into. HashSet if multiple queries need to be answered
Scanner in = new Scanner(System.in);
out.print("Enter name: ");
String name = in.nextLine();
BufferedReader br = new BufferedReader(new FileReader("name.txt"));
String line;
boolean found = false;
while ((line = br.readLine()) != null) {
if (line.contains(name)) {
out.println("Exists");
found = true;
break;
}
}
if (!found) {
out.println("Does not exist");
}
br.close();

You're breaking the loop if the name exists, so you should only print the "not exists" message if the loop doesn't break:
Scanner in = new Scanner(System.in);
out.print("Enter name: ");
String name = in.nextLine();
BufferedReader br = new BufferedReader(new FileReader("name.txt"));
String line;
boolean nameFound = false;
while ((line = br.readLine()) != null) {
if (line.contains(name)) {
out.println("Exists");
nameFound = true;
break;
}
if (!nameFound) {
out.println("Does not exist");
}
br.close();

PrintStream out = System.out;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
out.print("Enter name: ");
String name = in.readLine();
BufferedReader br = new BufferedReader(new FileReader("name.txt"));
String line;
boolean ifexist = false;
while ((line = br.readLine()) != null) {
if (line.contains(name)) {
ifexist = true;
break;
}
}
if (ifexist) {
out.print("Exist");
} else {
out.println("Does not exist");
}
br.close();
Add a boolean var default false, when exist set it to true and break. Than output.

Related

I/O with an array list

I was just wondering if there is a way to loop through a text file until a particular string is found.
For example, say you have a text file with the following in it:
banana
apple
grapes
melon
orange
cherries
strawberry chocolate vanilla
I basically want to write a program that loops through the input file until it gets to a particular string the user specifies and then stores the next line in an array list. So, basically say if I imputed cherries I want it to store strawberry, chocolate, vanilla in an array list. For the life of me I cannot figure out how to do this though, so anything would be appreciated. What I have so far is below.
public static void main(String[] args) throws IOException {
String line;
ArrayList<String> names = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the input file: ");
String input = in.next();
FileReader file = new FileReader(input);
BufferedReader reader = new BufferedReader(file);
System.out.print("What fruit do you want: ");
String fruit = in.next();
line = reader.readLine();
while ((line != null)) {
if(line.equals(fruit){
}
}
Just loop through the input until the searched line is encountered and store every line found afterwards in the list.
String line;
while((line = reader.readLine()) != null)
if(line.equals(fruit))
break;
ArrayList<String> lines = new ArrayList<>();
while((line = reader.readLine()) != null)
lines.add(line);
if I understand your question correctly, I have an idea that you can start from
Scanner scanner = new Scanner(file);
List<String> list = new ArrayList<String>();
while (scanner.hasNextLine()) { // read the entire file into list but it consumes time especially if the file is big (not perfect choice)
list.add(scanner.nextLine());
}
now what you can do
// add boolean to announce the occurrance of the word
boolean found = false;
for(String word: list){ // then you have a greater control over it to search
if(word.equals(fruit)){
found = true;
}
if (found) {
// start taking the rest of the array into a new array or whatever you want to do
}
}
You could use a boolean to indicate when the value is found and when it is true you can add the line in the List :
boolean isFound = false;
String line;
while ((line=reader.readLine())!= null) {
if(!isFound && line.equals(fruit){
isFound = true;
}
else if (isFound){
names.add(line);
}
}
Create flag isFound. Set it to true when you find the string.
It will then process on the next loop and set to false like so.
bool isFound=false;
while ((line != null)) {
if(isFound==true){
names.add(string)
isFound=false;
}
if(line.equals(fruit){
isFound=true;
}
}
check it out:
public static void main(String[] args) throws IOException {
String line;
List<String> names = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the input file: ");
String input = in.next();
FileReader file = new FileReader(input);
BufferedReader reader = new BufferedReader(file);
System.out.print("What fruit do you want: ");
String fruit = in.next();
boolean found=false;
while ((line = reader.readLine()) != null){
if (line.equals(fruit) || found) {
names.add(line);
found=true;
}
}
}

Count the lines of several methods but return separate values not the sum of all

I'm going to elabortate my question because I had a hard time labeling the question the right way.
I'm labeling my methods like this:
/*Start*/
public void contadorDeLineas(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
/*Finish*/
I have several methods labeled like that but I want to count them separately, but the code I wrote counts the lines inside the methods starting from public and finishing in "Finish". But as for now the code I wrote counts all the lines inside the methods and return the sum of all the lines. What I want to do is read the first block return that value and continue searching for the next block of code.
This is the code I wrote
public void LinesMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int lines_inside = 0;
while((line = br.readLine())!=null){
if(line.startsWith("/*St")){
do{
line = br.readLine();
line = line.trim();
System.out.println(line);
if(!(line.equals("") || line.startsWith("/*"))){
lines_inside++;
}
}while(!line.startsWith("/*Fi"));
}
}
br.close();
System.out.println("Found: " + lines_inside);
}
This is an example of what my code is showing in the console
/*Start*/
public void LineMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
/*Finish*/
/*Start*/
public static void main(String[] args)throws IOException{
program2 test = new program2();
File root = new File(args[0]);
test.LOC(root);
System.out.println("Found: " + test.lines);
System.out.println("Other type of lines: " + test.toDo);
}
}
/*Finish*/
Block comments lines: 11
Instead I'm looking for a result like a first print showing the number 3 and then a number 8.
Any guidance will be appreciated.
Try this
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
boolean inside = false;
int count = 0;
String line;
while ((line = br.readLine()) != null) {
if (line.contains("/*Start*/")) {
inside = true;
count = 0;
} else if (line.contains("/*Finish*/")) {
System.out.println("Found: " + count);
inside = false;
} else if (inside) {
++count;
}
}
if (inside && count > 0)
System.out.println("Found: " + count);
}
if you have several methods printing out all the lines may be to much when you are only interested in the number of lines. You can put the names of the methods and the number of lines in a map and print that out.
public static void LinesMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int lines_inside = 0;
Map<String, Integer> map = new HashMap<>();
while((line = br.readLine())!=null){
lines_inside = 0;
if(line.startsWith("/*St")){
String method = "";
do{
line = br.readLine();
if(line.contains("public")){
method = line.substring(0, ine.indexOf('('));
}
line = line.trim();
if(!(line.equals("") || line.startsWith("/*"))){
lines_inside++;
}
}while(!line.startsWith("/*Fi"));
map.put(method, lines_inside);
}
}
br.close();
for(String s :map.keySet()){
System.out.println(s +" : "+ map.get(s));
}
}
Try to put lines_inside++; in the code like this:
while((line = br.readLine())!=null){
lines_inside++;
...
This gives you the rught number of elements in file.

How to append multiple text in text file

I want the results from 'name' and 'code' to be inserted into log.txt file, but if I run this program only the name results gets inserted into .txt file, I cannot see code results appending under name. If I do System.outprintln(name) & System.outprintln(code) I get results printed in console but its not being inserted in a file.Can someone tell me what am I doing wrong?
Scanner sc = new Scanner(file, "UTF-8");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("text1")) {
String[] splits = line.split("=");
String name = splits[2];
for (int i = 0; i < name.length(); i++) {
out.println(name);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
String code = splits[2];
for (int i = 0; i < code.length(); i++) {
out.println(code);
}
}
out.close()
}
File looks like:
Name=111111111
Code=333,5555
Category-Warranty
Name=2222222
Code=111,22
Category-Warranty
Have a look at this code. Does that work for you?
final String NAME = "name";
final String CODE = "code";
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
String[] splits = line.split("=");
String key = splits[0];
String value = splits[1];
if (key.equals(NAME) || key.equals(CODE)) {
out.println(value);
}
}
out.close();
You have a couple of problems in your code:
you never actually assign the variables name and code.
you close() your PrintWriter inside the while-loop, that means you will have a problem if you read more than one line.
I don't see why this wouldn't work, without seeing more of what you are doing:
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("=")) {
if (line.contains("text1")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
}
}
out.flush();
out.close();
Make sure the second if condition is satisfied i.e. the line String contains "text2".

Appending text to existing file without overwriting it

I'm adding some content into an existing file NameList.txt, which already contains some text there.
But when I run the program, it removes all the existing content before starting to write new ones.
Note: I also try to find where is the file ending line. E.g. by using while ((lines = reader.readLine()) == null), where the lines variable is of the type String.
public class AddBooks {
public static void main(String[] args) {
Path Source = Paths.get("NameList.txt");
Charset charset = Charset.forName("Us-ASCII");
try (
BufferedWriter write = Files.newBufferedWriter(Source, charset);
BufferedReader reader = Files.newBufferedReader(Source, charset);
) {
Scanner input = new Scanner(System.in);
String s;
String line;
int i = 0, isEndOfLine;
do {
System.out.println("Book Code");
s = input.nextLine();
write.append(s, 0, s.length());
write.append("\t \t");
System.out.println("Book Title");
s = input.nextLine();
write.append(s, 0, s.length());
write.append("\t \t");
System.out.println("Book Publisher");
s = input.nextLine();
write.append(s, 0, s.length());
write.newLine();
System.out.println("Enter more Books? y/n");
s = input.nextLine();
} while(s.equalsIgnoreCase("y"));
} catch (Exception e) {
// TODO: handle exception
}
}
}
My only requirement is to add new content to existing file.
Change your code like this!
BufferedWriter write = Files.newBufferedWriter(Source, charset, StandardOpenOption.APPEND);
And see this!
StandardOpenOption
2nd..
while ((str = in.readLine()) != null)
Appendix.. insert
writer.close();
before
} while(s.equalsIgnoreCase("y"));

Not reading from the file correctly in Java

I'm trying to make a game and I am sorting out the account's and im doing it in text files at the moment as im just playing around, the text file for example is,
username
password
and when I run the code below , it runs the else statement every time when the details I enter are correct.
String player;
Scanner loadPlayer = new Scanner(System.in);
System.out.print("Enter Username: ");
String username = loadPlayer.nextLine();
System.out.println();
System.out.print("Enter Passwork: ");
String password = loadPlayer.nextLine();
System.out.println();
try {
File file = new File("/home/kieran/Desktop/project/accounts/"+username+".txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
String userData[] = stringBuffer.toString().split("\n");
System.out.println(userData[0]);
System.out.println(userData[1]);
if (userData[0] == username && userData[1] == password){
player = username;
System.out.println(player);
}
else{
System.out.println("Username, "+username+" does not exist, please try again!");
loadPlayer();
}
} catch (IOException e) {
e.printStackTrace();
}
if (userData[0].equals(username) && userData[1].equals(password)){
player = username;
System.out.println(player);
}
Your string comparison implementation is not OK.
Replace this line
if (userData[0] == username && userData[1] == password){
with this one:
if (userData[0].trim().equals(username.trim()) && userData[1].trim().equals(password.trim())){
try this
if (userData[0].equals(username) && userData[1].equals(password)){
player = username;
System.out.println(player);
}
else{
System.out.println("Username, "+username+" does not exist, please try again!");
loadPlayer();
}

Categories

Resources