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"));
Related
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 would like to split a line which might look like this:
6:8.0 7:36.0 14:9.0 15:31.0 22:5.0 23:21.0 30:2.0 31:12.0 38:40.0 39:137.0 46:50.0 47:133.0 54:35.0 55:106.0 62:16.0
The first value is x the second y.
Now i would like to have as a result two Lists ListX<Integer> and ListY<Double>.
I have tried doing it char by char. Where you can search for ':' and then go back and front to get the number. But there must be a faster way. Especially regarding on the lenght of the string which can get really big. Do You have any idea?
Thanks
You can try using String.split():
String test = "6:8.0 7:36.0 14:9.0 15:31.0 22:5.0 23:21.0 30:2.0 31:12.0 38:40.0 39:137.0 46:50.0 47:133.0 54:35.0 55:106.0 62:16.0";
String[] splitString1 = test.split(" ");
String[] splitString2 = null;
for(String a : splitString1)
{
splitString2 = a.split(":");
System.out.println(splitString2[0]);
System.out.println(splitString2[1]);
//push splitString2[0] to x
//push splitString2[1] to y
}
Here is the complete code which does what you are thinking to do
import java.util.*;
public class IntegerDoubleExtractor{
public static void main(String []args){
String test = "6:8.0 7:36.0 14:9.0 15:31.0 22:5.0 23:21.0 30:2.0 31:12.0 38:40.0 39:137.0 46:50.0 47:133.0 54:35.0 55:106.0 62:16.0";
List<Integer> x = new ArrayList<Integer>();
List<Double> y = new ArrayList<Double>();
for(String xy : test.split(" ")) {
String xys[] = xy.split(":");
x.add(Integer.parseInt(xys[0]));
y.add(Double.parseDouble(xys[1]));
}
System.out.println(x);
System.out.println(y);
}
}
You can also use a Scanner and you won't need intermediate Strings or arrays in the process:
Scanner scanner = new Scanner(str);
scanner.useDelimiter(Pattern.compile("[:\\s]"));
while (scanner.hasNext()) {
listX.add(scanner.nextInt());
listY.add(scanner.nextDouble());
}
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'm just starting to learn Java and I'm trying to complete this exercise.
I've understood how to extract the information from the txt file (I think) using scanner (we're only supposed to change the method body). However I'm not sure of the correct syntax to transfer the information to an array.
I realise it must be very simple, but I can't seem to figure it out. Could someone please point me in the right direction in terms of syntax and elements needed? Thank you in advance!
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
public class Lab02Task2 {
/**
* Loads the game records from a text file.
* A GameRecord array is constructed to store all the game records.
* The size of the GameRecord array should be the same as the number of non-empty records in the text file.
* The GameRecord array contains no null/empty entries.
*
* #param reader The java.io.Reader object that points to the text file to be read.
* #return A GameRecord array containing all the game records read from the text file.
*/
public GameRecord[] loadGameRecord(java.io.Reader reader) {
// write your code after this line
Scanner input = new Scanner(reader);
for (int i=0; input.hasNextLine(); i++) {
String inputRecord = input.nextLine();
input = new Scanner(inputRecord);
// array?
}
return null; // this line should be modified/removed after finishing the implementation of this method.
}
}
In case you already have a String of the file content, you can say:
String[] words = content.split("\\s");
You can parse your String like this:
private ArrayList<String> parse(BufferedReader input) throws CsvException {
ArrayList<String> data = new ArrayList<>();
final String recordDelimiter = "\\r?\\n|\\r";
final String fieldDelimiter = "\\t";
Scanner scanner = new Scanner(input);
scanner.useDelimiter(recordDelimiter);
while( scanner.hasNext() ) {
String line = scanner.next();
data.add(line);
}
return data;
}
The input text will be scanned line by line.
You can use an ArrayList<String>, like this:
Scanner s = new Scanner(new File(//Here the path of your file));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext())
{
list.add(s.nextLine());
}
And if you want to get the value of some item of the ArrayList you just have to make reference with get function, like this:
list.get(//Here the position of the value in the ArrayList);
So, if you want to get all the values of the ArrayList you can use a loop to do it:
for (int i = 0; i < list.size(); i++)
{
System.out.println(list.get(i));
}
And finally close your Scanner:
s.close();
I expect it will be helpful for you!
Assuming your one row in file contains one game only
for (int i=0; input.hasNextLine(); i++) {
String inputRecord = input.nextLine();
input = new Scanner(inputRecord);
String line=input.nextLine();
arr[i]=line;
}
return arr;
I do not know how to take the integer and ignore the strings from the file using scanner. This is what I have so far. I need to know how to read the file token by token. Yes, this is a homework problem. Thank you so much.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ClientMergeAndSort{
public static void main(String[] args){
int length = 13;
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
input = new Scanner(file);
while (!input.hasNextInt()) {
input.next();
}
int[] arraylist = new int[length];
for(int i =0; i < length; i++){
length++;
arraylist[i] = input.nextInt();
System.out.print(arraylist[i] + " ");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Take a look at the API for what you're doing.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()
Specifically, Scanner.hasNextInt().
"Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input."
So, your code:
while (!input.hasNextInt()) {
input.next();
}
That's going to look and see if input hasNextInt().
So if the next token - one character - is an int, it's false, and skips that loop.
If the next token isn't an int, it goes into the loop... and iterates to the next character.
That's going to either:
- find the first number in the input, and stop.
- go to the end of the input, not find any numbers, and probably hits an IllegalStateException when you try to keep going.
Write down in words what you want to do here.
Use the API docs to figure out how the hell to tell the computer that. :) Get one bit at a time right; this has several different parts, and the first one doesn't work yet.
Example: just get it to read a file, and display each line first. That lets you do debugging; it lets you build one thing at a time, and once you know that thing works, you build one more part on it.
Read the file first. Then display it as you read it, so you know it works.
Then worry about if it has numbers or not.
A easy way to do this is read all the data from file in a way that you prefer (line by line for example) and if you need to take tokens, you can use split function (String.split see Java doc) or StringTokenizer for each line of String that you are reading using a loop, in order to create tokens with a specific delimiter (a space for example) so now you have the tokens and you can do something that you need with them, hope you can resolve, if you have question you can ask.
Have a nice programming.
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) throws IOException {
String newStr=new String(readAllBytes(get("data.txt")));
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(newStr);
while (m.find()) {
System.out.println("- "+m.group());
}
}
}
This code fill read the file and then using the regular expression you can get only Integer values.
Note: This code works in Java 8
I Think This will work for you requirement.
Before reading the data from the file initially,try to write some content to the file by using scanner and filewriter then try to execute the below code snippet.
File file = new File(your filepath);
List<Integer> list = new ArrayList<Integer>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String str =null;
while(true) {
str = bufferedReader.readLine();
if(str!=null) {
System.out.println(str);
char[] chars = str.toCharArray();
String finalInt = "";
for(int i=0;i<chars.length;i++) {
if(Character.isDigit(chars[i])) {
finalInt=finalInt+chars[i];
}
}
list.add(Integer.parseInt(finalInt));
System.out.println(list.size());
System.out.println(list);
} else {
break;
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
The final println statement will display all the integer in your file line by line.
Thanks