I am trying to see if a string in my array matches a word. If so, perform the If statement.
Sounds simple as pie but the If statement does not see the string from the array!
The array (temps) contains nothing but "non"s so I know it's something wrong with the If statment.
Here is the snippet of code:
if ("non".equals(temps.get(3))) {
System.out.println("Don't know.");
}
Where temps is the array containing "non"s on different lines.
Here is the full code in case anyone is wondering:
public class Dump {
public static void main(String[] args) throws IOException {
String token1 = "";
//Reads in presidentsUSA.txt.
Scanner inFile1 = new Scanner(new File("presidentsUSA.txt"));
//Splits .txt file via new lines.
inFile1.useDelimiter("\\n");
List<String> temps = new ArrayList<String>();
while (inFile1.hasNext()) {
token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
// Stores each new line into an array called temps.
String[] tempsArray = temps.toArray(new String[0]);
if ("non".equals(temps.get(3))) {
System.out.println("Don't know.");
}
}
}
The most probable explanation why your if statement returns false is that you are on a Windows OS.
If you debug your code and watch temps.get(3) it will show the content as
non\r
and non\r does not equal non
Solution:
inFile1.useDelimiter("\\r\\n");
Check the accepted answere here (especially point 4): Difference between \n and \r?
Related
If I print directly as
System.out.println("a\nb");
the result will be as expected, with a new line between characters,
but if I read the same line from a text file using
public static void main(String[] args) throws IOException {
List<String> lines;
lines = Files.readAllLines(Paths.get("filename.txt"));
String[] array = lines.toArray(new String[0]);
System.out.println(array[0]);
the text displayed will be exactly as written in a file "a\nb" without a new line between the characters. toString and other methods do not help.
How should I update the code?
With the help of the colleagues and commenters got an explanation and an answer (not the most elegant approach though).
"\n" in the code is interpreted as a new line character, but when read from a file it becomes a set of two characters: "\" and "n" and is no longer properly recognized. The shortest way to eliminate the problem would be to replace these characters with the new line in the code of the program, adding "replace("\n", "\n")". So, the code becomes as follows:
public static void main(String[] args) throws IOException {
List<String> lines;
lines = Files.readAllLines(Paths.get("filename.txt"));
String[] array = lines.toArray(new String[0]);
System.out.println(array[0].replace("\\n", "\n"));
I am trying to write a code that looks at a text file, and does a while loop so that it reads each line, but I need each word per line to be in an array so I can carry out some if statements. The problem I am having at the moment is that my array is currently storing all the words in the file in an array.. instead of all the words per line in array.
Here some of my current code:
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("test.txt"));
List<String> listwords = new ArrayList<>();
while (in.hasNext()) {
listwords.addAll(Arrays.asList(in.nextLine().split(" ")));
}
if(listwords.get(4) == null){
name = listwords.get(2);
}
else {
name = listwords.get(4);
}
If you want to have an array of strings per line, then write like this instead:
List<String[]> listwords = new ArrayList<>();
while (in.hasNext()) {
listwords.add(in.nextLine().split(" "));
}
Btw, you seem to be using the term "array" and "ArrayList" interchangeably.
That would be a mistake, they are distinct things.
If you want to have an List of strings per line, then write like this instead:
List<List<String>> listwords = new ArrayList<>();
while (in.hasNext()) {
listwords.add(Arrays.asList(in.nextLine().split(" ")));
}
You can use
listwords.addAll(Arrays.asList(in.nextLine().split("\\r?\\n")));
to split on new Lines. Then you can split these further on the Whitespace, if you want.
I am a beginner in programming. I am currently learning how to convert texts from notepad into array line by line. An instance of the text in notepad,
I am a high school student
I love banana and chicken
I have 2 dogs and 3 cats
and so on..
In this case, the array[1] will be string 'I love banana and chicken'.
The lines in the notepad can be updated and I want the array to be dynamic/flexible. I have tried to use scanner to identify each of the lines and tried to transfer them to array. Please refer to my code:
import java.util.*;
import java.io.*;
import java.util.Scanner;
class Test
{
public static void main(String[] args)
throws Exception
{
File file = new File("notepad.txt");
Scanner scanner = new Scanner(file);
String line;
int i = 0;
int j = 0;
while (scanner.hasNextLine()) {
i++;
}
String[] stringArray = new String[i];
while (scanner.hasNextLine()) {
line = scanner.nextLine();
stringArray[j] = line;
j++;
}
System.out.println(stringArray[2]);
scanner.close();
}
}
I am not sure why there is runtime-error and I tried another approach but still did not produce the result that I want.
The first loop would be infinite because you check if the scanner has a next line, but never advance its position. Although using a Scanner is fine, it seems like a lot of work, and you could just let Java's nio package do the heavy lifting for you:
String[] lines = Files.lines(Paths.get("notepad.txt")).toArray(String[]::new);
You can simply do it by creating an ArrayList and then converting it to the String Array.
Here is a sample code to get you started:
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("notepad.txt"));
List<String> outputList = new ArrayList<>();
String input = null;
while (in.hasNextLine() && null != (input = in.nextLine())) {
outputList.add(input);
}
String[] outputArray = new String[outputList.size()];
outputArray = outputList.toArray(outputArray);
in.close();
}
Since you want array to be dynamic/flexible, I would suggest to use List in such case. One way of doing this -
List<String> fileLines = Files.readAllLines(Paths.get("notepad.txt"));
I'm trying to wrap my head around a problem I have in a programming set.
We're supposed to write code that reads from a file and prints it out. I get that, I can do it.
What he wants us to do is have it print out in reverse.
the file reads:
abc
123
987
He wants:
987
123
abc
The code, as it is, is as follows:
{
FileReader n=new FileReader("F:\\Java\\Set 8\\output1.txt");
Scanner in=new Scanner(n);
int l;
while (in.hasNext())
{
l=in.nextInt();
System.out.println(l);
}
in.close();
}
}
Yes, I am using java.io.*; and Scanner.
What would be the simplest way to do this?
EDIT EDIT EDIT
Here's the improved code, where I try to put it into an array.
The data in the array isn't printing out.
public static void main(String[] args) throws IOException
{
int[]Num=new int[20];
Scanner in=new Scanner(new FileReader("F:\\Java\\Set 8\\output1.txt"));
int k;
for (k=0;k<20;k++)
{
Num[k]=in.nextInt();
}
//in.close();
for (k=20;k<20;k--)
{
System.out.print(+Num[k]);
}
//in.close();
}
The most simplest way is to construct a List and add each line to the list while reading from the file. Once done, print the list items in reverse.
Here is my version of code for your problem.
public static void main(String[] args) throws FileNotFoundException {
FileReader n = new FileReader("/Users/sharish/Data/abc.xml");
Scanner in = new Scanner(n);
ArrayList<String> lines = new ArrayList<String>();
while (in.hasNext()) {
lines.add(in.nextLine());
}
in.close();
for (int i = lines.size() - 1; i >= 0; i--) {
System.out.println(lines.get(i));
}
}
Use Stack.
public static void displayReverse() throws FileNotFoundException {
FileReader n=new FileReader("C:\\Users\\User\\Documents\\file.txt");
Scanner in=new Scanner(n);
Stack<String> st = new Stack<String>();
while (in.hasNext()) {
st.push(in.nextLine());
}
in.close();
while(!st.isEmpty()) {
System.out.println(st.pop());
}
}
If you are permitted the use of third party APIs, Apache Commons IO contains a class, ReversedLinesFileReader, that reads files similar to a BufferedReader (except last line first). Here is the API documentation: http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/ReversedLinesFileReader.html
Another (less efficient) solution is hinted at in the comments. You can read your entire file into an ArrayList, reverse that list (e.g. by pushing its contents onto a stack and then popping it off), and then iterate through your reversed list to print.
EDIT:
Here is a crude example:
ArrayList<String> lines = new ArrayList<String>();
Scanner in = new Scanner(new FileReader("input.txt"));
while (in.hasNextLine())
{
lines.add(in.nextLine());
}
Use an ArrayList instead of a static array. We don't necessarily know the length of the file in advance so a static array doesn't make sense here. http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Your example input 123, abc, etc, contains characters as well as ints, so your calls to hasNextInt and nextInt will eventually throw an Exception. To read lines use hasNextLine and nextLine instead. These methods return String and so our ArrayList also needs to store String. http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextLine()
Once the file is in a list (not a good solution if the file is large - we've read the entire file into memory) we can either reverse the list (if keeping a reversed form around makes sense), or just iterate through it backwards.
for (int i=lines.size()-1; i>=0; i--) // from n-1 downTo 0
{
String line = lines.get(i);
System.out.println( line );
}
public static void main(String[] args) throws Exception{
String fileName = "F:\\Java\\Set 8\\output1.txt";
RandomAccessFile raf = new RandomAccessFile(fileName,"r");
int len = (int) raf.length();
raf.seek(len);
while(len >= 0){
if(len == 0){
raf.seek(0);
System.out.println(raf.readLine());
break;
}
raf.seek(len--);
char ch = (char)raf.read();
if(ch == '\n'){
String str = raf.readLine();
System.out.println(str);
}
}
}
try using org.apache.commons.io.input.ReversedLinesFileReader, it should do what you want.
You could read the lines like you are already doing, but instead of printing them (because that would print them in order and you need it the other way around), add them to some memory structure like a List or a Stack, and then, in a second loop, iterate this structure to print the lines in the needed order.
Using your code and the answers in the comments, here's an example of how you would store the strings into the arraylist and then print them out in reverse (building off of your own code)
{
FileReader n=new FileReader("F:\\Java\\Set 8\\output1.txt");
Scanner in=new Scanner(n);
int l;
ArrayList<String> reversed = new ArrayList<String>(); // creating a new String arraylist
while (in.hasNext())
{
l=in.nextInt();
System.out.println(l);
reversed.add(l); // storing the strings into the reversed arraylist
}
in.close();
// for loop to print out the arraylist in reversed order
for (int i = reversed.size() - 1; i >= 0; i--) {
System.out.println(reversed.get(i));
}
}
}
Using Java 8:
try(PrintWriter out =
new PrintWriter(Files.newBufferedWriter(Paths.get("out.txt")))) {
Files.lines(Paths.get("in.txt"))
.collect(Collectors.toCollection(LinkedList::new))
.descendingIterator()
.forEachRemaining(out::println);
}
I am writing a program that reads a text file passed as an argument to the main method and extracts all the unique words from the file and prints them in the console one per line. I am having trouble passing the tokens to a string array while each line is being read from the scanner:
There's a couple things I see that are wrong or could be written in a more efficient manner:
1)tokens is initialized to 100. This an obvious constraint, I thought about using something like a dynamic array like arrayList or vector but ultimately decided to use simple string array and simply expand the array (i.e. create a new array double the size of the original array, by writing some type of conditional statement that will determine if the tokens is filled up with max elements but scanner still has more lines.
2)I am not sure if simply passing input.hasNextLine() as the test statement in the for loop makes sense. I basically want to loop as long as input has reached EOF
3) I want the regex expression in split to catch all punctuation, whitespaces, and digits, I'm not 100% sure if it's written correctly
4) The line in question is tokens[index] = token[index], I'm not sure this correct. I want the tokens from each line being to be added to tokens.
public static void main(String[] arg) throws FileNotFoundException {
File textFile = new File(arg[0]);
String[] tokens = new String[100];
try {
Scanner input = new Scanner(textFile);
for (int index = 0; input.hasNextLine(); index++) {
String[] token = input.nextLine().split("[.,;']+\\d +\\s");
tokens[index] = token[index];
}
for (String token : tokens) {
System.out.println(token);
}
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
There are several errors in the code, I'll try to cover all of them:
change tokens to be an ArrayList, there is no reason not to
you need two iterations: a) lines in the file and b) tokens in the line
the regex is really specific of what you have between tokens (punctuations + one digit + spaces + other space)
public static void main(String[] arg) throws FileNotFoundException {
File textFile = new File(arg[0]);
ArrayList<String> tokens = new ArrayList<String>();
try {
Scanner input = new Scanner(textFile);
while (input.hasNextLine()) {
String[] lineTokens = input.nextLine().split("[,;:\"\\.\\s]+");
for (String token : lineTokens) {
tokens.add(token);
}
}
for (String token : tokens) {
System.out.println(token);
}
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
The regex can be improved but it depends on your data anyway so I can't know all the cases you need to handle.