I am having some difficulty declaring an array on the text in a file. In other words, I am trying to store the information on a file into an array as double[] and displaying the array with the enhanced for loop. The file just contains 12 decimal numbers. Any help will be greatly appreciated. Below is a snippet of my code:
// create inFile2 variable
Scanner inFile2 = new Scanner("/Users/timothylee/KeyWestHumid.txt");
// while statment for inFile2
while(inFile2.hasNext()){
// create double reader
double num2 = inFile2.nextDouble();
double[] humidity1 = new double[num2];
// for-each loop for displaying humidity
for(double humidity : humidity1){
// display array for humidity
}
}
The enhanced for loop is only useful for looking at the values in an array/collection already. Java doesn't do pass by reference so your double humidity field is just a copy, not a reference to the array.
You need to do something like
for(int i = 0; i < humidity1.length; i++)
humidity1[i] = inFile2.nextDouble();
Scanner s = new Scanner(new File("C:\\usr\\a.txt"));
double[] darray = new double[12];
int i=0;
while (s.hasNextDouble()) {
darray[i++] = s.nextDouble();
}
for (double d : darray) {
System.out.println(d);
}
I gave it a try now, there are two issues in your code:
First by using Scanner this way:
Scanner s = new Scanner("Bla.txt");
Will return 'Bla.txt' when calling s.nextLine(). To get the file content you need to pass a File object to your scanner like this:
Scanner inFile2 = new Scanner(new File("/Users/timothylee/KeyWestHumid.txt"));
The second issue is on how to fill those values into an array, here is my approach on doing so:
public static void main(String[] args){
try {
//Initiate the scanner to read the files content
Scanner scanner = new Scanner(new File("D:\\temp\\backup_branch\\test.txt"));
//Have something to care about array dimensions (see note about this in the answer!)
List<Double> numbersFromFile = new ArrayList<Double>();
while(scanner.hasNext()){
double num2 = scanner.nextDouble();
//add every number
numbersFromFile.add(num2);
}
//Have it as array
//Object[] vals = numbersFromFile.toArray();
//double d = (double) vals[0];
//System.out.println(d);
//Print it
for(Double d : numbersFromFile){
System.out.println(d);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Note: I seem to have a lack when it comes to generics and primitive types so dont rely on the generic part of this solution. It is more about to show you that you first want to fill your array with data and then use the new for-loop to iterate over an existing array.
Related
There are 26 numbers in the numbers.txt file. Those 26 numbers are supposed to be read to arr but instead I get 26 zeroes in my array.
Scanner scanner = new Scanner(new File("numbers.txt"));
int n = 0;
int i = 0;
while (scanner.hasNextInt()) {
scanner.next();
n++;
} // n is now 26
int[] arr = new int[n];
while (scanner.hasNextInt()) {
for (i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
}
}
System.out.print(Arrays.toString(arr));
zeroes are default value for array. a scanner is "single-use", it's single-pass. you used it once, you have to create another (maybe by earlier having the File object in a variable and then using it to create both Scanners?) or somehow reverse its state. the second loop has zero iterations, it never hasNextInt anymore
MichaĆ is right -- you need to repeat the scanner = new Scanner(...) after your // n is now 26 line.
Or, better, use an ArrayList<Integer>() rather than int[], then you only need a single pass:
public static void main(String[] args) throws Exception {
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(new File("numbers.txt"));
while (scanner.hasNextInt()) {
numbers.add(scanner.nextInt());
}
System.out.print(numbers);
}
I need to read a file of grades and input them into an array. I cant seem to figure it out though. Any suggestions. Thanks for your help :)
The grades.txt file looks like this:
90.0
71.5
87.9
95.0
98.1
Code:
File file1 = new File("grades.txt");
Scanner gradesFile = new Scanner(file1);
String line = gradesFile.nextLine();
//create array
double[] array = new double[12];
//variable to increment
int u = 0;
//loop to put data into array
while(gradesFile.hasNextDouble())
array[u] = gradesFile.nextDouble();
u += 1;
gradesFile.close();
A. As #hnefatl said you need to group statements in the loop,
while(<condition>) {
statement1;
...
statementN;
}
otherwise only next one executes.
while(<condition>) statement1;
...
B. When you did String line = gradesFile.nextLine();
you got full first line from file and Scanner position is at next line if there is any.
So by doing gradesFile.hasNextDouble() after that, Scaner looks for double in next line.
If you'd like to use nextLine() and your doubles are "one-per-line" you need to work with them in a loop as:
Scanner gradesFile = new Scanner(file1);
// create array
double[] array = new double[12];
// variable to increment
int u = 0;
// loop to put data into array
while (gradesFile.hasNextLine()) {
String line = gradesFile.nextLine();
array[u] = Double.parseDouble(line);
u += 1;
}
gradesFile.close();
or if you'd like to use nextDouble() you do not mix it with nextLine()
Scanner gradesFile = new Scanner(file1);
// create array
double[] array = new double[12];
// variable to increment
int u = 0;
// loop to put data into array
while (gradesFile.hasNextDouble()) {
array[u] = gradesFile.nextDouble();
u++;
}
gradesFile.close();
You can simply scan the double value in your file and store in the array as below
Scanner scan;
//Data file
File file = new File(grades.txt");
//Array to store the double read from file
double[] array = new double[10];
int i =0;
try {
scan = new Scanner(file);
//Scan while the file has next double value
while(scan.hasNextDouble())
{
//Save the double value read from text file and store to array
array[i] = scan.nextDouble();
i++;
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
To print what you have stored in your array
for(int y = 0; y < array.length;y++)
{
System.out.println(array[y]);
}
I am trying to read a file in Java and store it into an array. Now the problem is that the file has the following structure. I will give 2 example files below:
input file structure
<number of lines>
<line number> <value>
.
.
.
<line number> <value>
input1.txt
5
1 34
2 19
3 43
4 62
5 36
input2.txt
4
1 10.3430423
2 -34.234923
3 -100.39292
4 22
As you can see the file starts with the number of lines(e.g 4 or 5). In the normal input text I have there are more than 100000 lines.
So my code basically grabs the user input, opens the file, create an array size and an array of that size. Now I am stuck on reading the next line and adding the values to my elements array. The line number should not be added into the array. Now as you can see, my elements array is declared as String. Is it possible to actually read the file, get the type of the value and create an array of that type? I think it could save from converting from string to int or double or floating?
Below is my code:
public static void main(String args[]) throws NumberFormatException, IOException{
String inFile; //Input file name.
int filterSize; //Filter size (odd integer >= 3).
String outFile; //Output file name.
int arraySize;
String[] elements;
int index = 0;
//Scanner to take input file name, filter size and output file name.
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter your keyboard input as follows: <data file name> <filter size(odd int >= 3> <output file name>");
//Assigning values to variables.
inFile = keyboardInput.next();
filterSize = keyboardInput.nextInt();
outFile = keyboardInput.next();
//Reading file into array using BufferReader
BufferedReader fileInput = new BufferedReader(new FileReader(inFile));
arraySize = Integer.parseInt(fileInput.readLine()); //Get Array Size
elements = new String[arraySize];
while(fileInput.readLine() != null){
elements[index] = fileInput.readLine();
index += 1;
}
}
Any help is appreciated. Thanks.
Try doing it like this:
Scanner sc = new Scanner(new File(inFile));
arraySize = sc.nextInt();
elements = new String[arraySize];
while(sc.hasNext())
{
sc.nextInt();
elements[index] = sc.next();
index += 1;
}
You create new Scanner and you can than read integers, booleans and so on, without any converting. Because you don't need line of current number, you just read that number and that is it. You don't need to save it anywhere. Then the next number/string you must save at elements[index]. That's it
Go stream-based:
Files.lines(pathToFile).skip(1) // skip the line counter. Don't trust input
.map(line -> line.replaceFirst("\\d+", "")) // remove digits at the start
.collect(Collectors.toList()); // collect it into a list
You can Store it into an array with .toArray() anyways
But actually you should do that with a try-with-resources:
try (Stream<String> lines = Files.lines(pathToFile).skip(1)) {
elements = lines.map(line -> line.replaceFirst("\\d", "")).collect(Collectors.toList());
} catch (IOException e) {
// sensible handling...
}
Read the number, never use it.
File file = new File("input1.txt");
Scanner in = new Scanner(file);
int lines = in.nextInt();
int []a = new int[lines];
for(int i = 0; i < lines; i++)
{
int fakeNumber = in.nextInt();//read it but never used it
a[i] = in.nextInt();
}
You could also use in#hasNextLine() also.
The real question here is how to get rid line number and get the value besides it.
double[] array = .... // initialize your array
int v = 0;
while(file.readLine() != null){
// your array
array[v++] = Double.parseDouble(file.readLine().split(" ")[1]);
}
I am trying to parse information from a text file in the following format:
WarningGeotask: 0, 1
The first word is a keyword for a certain object to create at the coordinate location given in the numbers that follow it. Here is what my loop looks like currently:
// Open file and scan for a line
File f = new File("Simulation.Configuration");
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
// Parse each line with a temporary scanner
String line = s.nextLine();
Scanner s2 = new Scanner(line);
// Get keywords from the file to match to variable names
String keyword = s2.next();
//...Multiple if statements searching for different keywords...
else if (keyword.equals("WarningGeotask:")) {
int xCoord = s2.nextInt();
int yCoord = s2.nextInt();
WarningGeotask warningGeotask = new WarningGeotask(xCoord, yCoord);
s2.close();
continue;
}
}
However, this code doesn't work properly. In fact, String xCoord = s2.nextInt() throws an error. I can do s2.next() and print out s2.nextInt() which returns 1. But I'm not sure what I'm doing wrong with Scanner to get 0 and 1 set to two different variables. Thanks for the help!
EDIT: The String variables xCoord and yCoord are supposed to be int - my fault.
The thing is that Scanner#nextInt() returns a numerical value (to be exact: a value of type int), which you try to assign to a String variable.
So instead of:
String xCoord = s2.nextInt();
String yCoord = s2.nextInt();
try:
int x = s2.nextInt();
int y = s2.nextInt();
You can do this using split()
when you read the lines, make it as Comma-separated value :
while (s.hasNextLine()) {
String line = s.nextLine().replace(":",",");
String[] data =line.split(",");
//...Multiple if statements searching for different keywords
else if(data[0].equals("WarningGeotask:")){
WarningGeotask warningGeotask = new WarningGeotask(Integer.parseInt(data[1].trim()), Integer.parseInt[data[2].trim());
}
try this
sc.useDelimiter("\\D+");
int n1 = sc.nextInt();
int n2 = sc.nextInt();
So what I'm trying to do is to fill an array of 100 items with 30 names from a file using Scanner = new Scanner(new File("list.txt")). It needs to use a sentinel of "DONE" to end the loop found at the bottom of the file.
How would I do that? array[arraySize] = value(); gives me a type mismatch
public class List
{
public static void main(String[] args) throws FileNotFoundException
{
double array[] = new double[100];
int arraySize = 0;
String value;
String sentinel = "DONE";
Scanner inFile = new Scanner(new File("list.txt"));
value = inFile.next();
while (value != sentinel)
{
array[arraySize] = value();
arraySize++;
value = inFile.next();
}
}
}
D'oh....those mistakes are shameful lol. Thanks all got it to work =]
A few issues, you need to change these lines from:
double array[] = new double[100]; // can't assign string to double
// (since you said "30 names", I assume
// you aren't trying to get numbers from
// the file)
...
while (value != sentinel) // this performs pointer comparison, whereas you want
// string comparison
...
array[arraySize] = value(); // value is a variable, not a function
To:
String array[] = new String[100];
...
while (!value.equals(sentinel))
...
array[arraySize] = value;
Note: Additionally, as good practice, you might want to add some defensive programming checks to augment your while loop terminating condition. (Consider what happens when the input file does not contain a sentinel)