Reading a text file into Java by using a "double" method - java

I have a simple text file with the following content:
4 5 2 7
I would like Java to read this file and create an array with it. However, I want my method that I use to keep its "double" properties. I'm having a hard time getting my array command to figure it out though:
import java.util.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.io.*;
public class ReadFile {
public static void main(String[] args){
gns(Arr);
}
public static double gns(String TxtFile) throws IOException {
Path path = Paths.get("C:\\Users\\me\\files\\inputfiles");
int numLines = (int)Files.lines(path).count();
Scanner fileScanner = new Scanner(new FileReader("TxtFile.txt"));
double Arr = new ArrayList<String>();
return Arr;
}
}
It keeps giving me an array due to the type of the array.

This would do the trick :
double[] arr = Files.lines(Paths.get(PATH))
.flatMap(line -> Arrays.stream(line.split(" ")))
.mapToDouble(Double::parseDouble)
.toArray();
Here we read the file line by line and then split it using " ", parse each number and covert it to an array of double. You can then return arr[] from your method gns(String TxtFile).

Scanner#nextDouble
Give a try to the following one, full example below:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class NextDouble {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("input.txt"));
List<Double> doubles = new ArrayList<Double>();
while (sc.hasNextDouble()) {
doubles.add(sc.nextDouble());
}
System.out.println(doubles); // => [1.0, 3.0, 8.0, 6.0, 5.0]
}
}
input.txt contains the following line:
1 3 8 6 5
You can find more about scanner in the doc

You're trying to set Arr which is of type double to an ArrayList of type String, this is not possible since the types double and ArrayList are different.
If you wanted an arraylist of doubles use
ArrayList<Double> d = new ArrayList<>();

Related

I have a text file containing words and I want to add them to an arraylist but I have a problem

This is the format of my text file:
apricot
garlic
pineapple
attorney
banana
cantaloupe
Cherry
celery
cabbage
cucumber
fig
raspberry
Kiwi
lettuce
lime
mango
melon
grapefruit
Pear
pepper
Apple
radish
grape
The problem I'm having is that the text file contains extra blank lines and I'm not allowed to remove those lines. When I add the words to an arraylist it reads those extra blank lines and I'm wondering how I could remove those extra values.
This is what I've come up with so far:
arrWords = new ArrayList<Word>();
while (myReader.hasNextLine()) {
Word w = new Word(myReader.nextLine().toLowerCase().trim());
arrWords.add(w);
}
The arraylist is of type Word so I'm wondering how I could remove those blank values or somehow read the lines differently. I've tried multiple solutions like replace all or remove but none of them worked.
try this:
while (myReader.hasNextLine()) {
String line = myReader.nextLine().toLowerCase().trim();
if (!line.isEmpty()) {
arrWords.add(new Word(line));
}
}
Alternatively, you could use the stream API.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class WordList {
public static void main(String[] args) throws IOException {
Path path = Paths.get("words.txt");
try (Stream<String> lines = Files.lines(path)) {
List<Word> arrWords = lines.filter(line -> !line.isBlank())
.map(line -> new Word(line.strip().toLowerCase()))
.collect(Collectors.toList());
arrWords.forEach(System.out::println);
}
}
}
class Word {
private String word;
public Word(String word) {
this.word = word;
}
public String toString() {
return word;
}
}
Methods isBlank and strip were added in Java 11.
Above code uses try-with-resources and NIO.2 as well as method references.

how to create a List of int entered on 1 line of the console

The idea is that I want to enter numbers from the console and put them directly into a List. That's my way but it does not work. I have no idea how to fix it. I tried manually importing java.util...., but it still does not work.
And that is the code
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List<Integer> numbers = Arrays.stream(in.nextLine()
.split(" "))
.mapToInt(Integer::parseInt)
.collect(Collectors.toList());
}
}
Just change the last line as it follows:
List<Integer> list = Arrays.stream(in.nextLine()
.split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());

How to reverse an ArrayList from a file?

This is the original question:
Write a program that reads a set of doubles from a file, stores them in an array or ArrayList, and then prints them back out to the console (using System.out.println statements) in REVERSE order.
For example, if the input file input.txt file contains
27.3
45.6
98.3
10.1
The console output will display
10.1
98.3
45.6
27.3
And this is the code I have so far:
package reverse;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class reversed {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
Scanner numFile = new Scanner(new File("input.txt"));
ArrayList<Double> list = new ArrayList<Double>();
while (numFile.hasNextLine()) {
String line = numFile.nextLine();
Scanner sc = new Scanner(line);
sc.useDelimiter(" ");
while(sc.hasNextDouble()) {
list.add(sc.nextDouble());
}
sc.close();
}
numFile.close();
System.out.println(list);
}
}
How would I reverse the ArrayList I created? The code I have works, I just have no idea how to reverse it. And where exactly would I put that code? Thanks!
You don't need to reverse the ArrayList, just iterate it in reverse order. Something like,
for (int i = list.size(); i > 0; i--) {
System.out.println(list.get(i - 1));
}
If you must reverse the List before iteration, you might use Collections.reverse(List) like
Collections.reverse(list);

Error using ArrayList in Java

I was solving a problem before including it in my code and using List to get strings then work around with them. I got the error: "type List does not take parameters List words = new ArrayList();" after compilation. I searched but the syntax i use is correct, please whats wrong with the code?
import java.util.Scanner;
import java.util.ArrayList;
public class List{
public static void main(String args[]){
List<String> words = new ArrayList<String>();
Scanner input = new Scanner(System.in);
for (int i=0; i < 3; i++)
words.add(input.nextLine());
System.out.println(words);
}
}
This is one of the reasons you should use unique names for your own classes. You are really meaning to use java.util.List, but since you called your class List as well, the real problem is masked. Rename your class and add the import for java.util.List to fix the issue:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class MyClass{
public static void main(String args[]){
List<String> words = new ArrayList<String>();
Scanner input = new Scanner(System.in);
for (int i=0; i < 3; i++)
words.add(input.nextLine());
System.out.println(words);
}
}
Try this:
import java.util.Scanner;
import java.util.ArrayList;
public class List{
public static void main(String args[]){
java.util.List<String> words = new ArrayList<String>();
Scanner input = new Scanner(System.in);
for (int i=0; i < 3; i++)
words.add(input.nextLine());
System.out.println(words);
}
}
Your class is called List. So by default, it is assumed that the List you declared refers to your class.
It would be better to avoid names like List for your classes.

Reading ints from a txt file and storing to an array

I am trying to read integers from a text file and store them into an array. The text file reads:
4
-9
-5
4
8
25
10
0
-1
4
3
-2
-1
10
8
5
8
Yet when I run my code I get [I#41616dd6 in the console window...
public static void main(String[] args) throws IOException
{
FileReader file = new FileReader("Integers.txt");
int[] integers = new int [100];
int i=0;
try {
Scanner input = new Scanner(file);
while(input.hasNext())
{
integers[i] = input.nextInt();
i++;
}
input.close();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(integers);
}
You're printing out the virtual memory address of the array instead of the actual array items:
You can print out the actual array items, one by one, like this:
// This construct is called a for-each loop
for(int item: integers) {
System.out.println(item);
}
#akuhn points out correctly that Java has a built in helper for this:
System.out.println(Arrays.toString(integers));
Note that you'll need to add:
import java.util.Arrays
in your imports for this to work.
Unfortunately, Java’s designers missed to add a proper string representations for arrays.
Instead use
System.out.println(Arrays.toString(integers));
You need to import java.util.Arrays; to make this work.
instead of this
System.out.println(integers);
try this
System.out.println(integers[0] + " : " + integers[1]);
you need to print actual values in integers[] array not array itself
If using an int array is not a restriction, then i would suggest use List. You can use it like this :
List<Integer> integers = new ArrayList<Integer>();
Scanner input = new Scanner(file);
while(input.hasNext()){
integers.add(scanner.nextInt());
}
System.out.println(integers);
Output : [1,2,-1,23]
Whenever you pass any object to System.out.println(), it prints the toString() for that object. If its not overridden, it prints the memory address of that object.
System.out.println(integers);
is trying to print toString() representation of integer array which is nothing but the JVM address of this array.
To print the actual numbers in the array, you either need to iterate through the array or convert the array to java.util.ArrayList.(which has the toString() method implemented.)
This should help you to read Integer from a file and store it in array
import java.util.Scanner;
import java.io.File;
import java.util.ArrayList;
public class filetoarray {
public static ArrayList<Integer> read(File f)
{
ArrayList<Integer> array=new ArrayList<Integer>();
try
{
Scanner sc=new Scanner(f);
while(sc.hasNextLine())
{
array.add(sc.nextLine());
}
}
catch(Exception e)
{
System.out.printf("ERROR : %s", e);
}
return array;
}
public static void main(String[] args) {
File file1=new File("file1.txt");//your file path here
ArrayList<Integer> array1;
array1=read(file1);
System.out.println(array1);
}
}

Categories

Resources