i have a text file and i want to read the integers and doubles. I dont know how many values i have to read. The first value in the line is always the integer and the second is always the double. I want to save the value of the first line seperately.
200
11010 0.004
500 0.02
637 0.018
How to create 2 arrays and save the values, so i can use them later? I am not allowed to create a new class. I tried to use Point but cant store doubles.
Scanner scanner = new Scanner(new File(args[0]));
int cores= scanner.nextInt();
System.out.print(cores);
while (scanner.hasNext()) {
int x = scanner.nextInt();
double y = scanner.nextDouble();
System.out.printf("x");}
I' ve tried the code above but throws out Exception
You can use simple file handling approach to read the file line by line, For the first line you can use a flag to mark the line and sent the file to remote location you want to save the data. Then for all later lines you can split the string on the basis of " " (space). Post which once you have stripped the elements of the resulting array you can typecast and append the element at first index to integer array. And the second element (typecast before append) to the double array. This shall work absolutely fine with any length of file.
A demo code for the same is as following:
public class ReadLineByLine
{
public static void main(String args[])
{
try
{
FileInputStream fis=new FileInputStream("Demo.txt");
Scanner sc=new Scanner(fis);
String tempLineData = "";
int flag = 0;
String[] elements;
List<Integer> ints = new ArrayList<Integer>(
List<Float> floats = new ArrayList<Float>(
while(sc.hasNextLine())
{
if(flag == 0){
// Place the operation with the first line here
flag++;
}
tempLineData=sc.nextLine();
elements = tempLineData.split(" ");
ints.add((int)elements[0].trim());
floats.add((float)elements[1].trim());
}
sc.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Related
I need to pull integers from a text file and sum them up. I came up with this but I keep getting an error. What am I missing? I need to use a scanner class.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class txtClass {
public static void main(String[] args) throws FileNotFoundException {
File txtFile = new File(//text file path//);
Scanner scan = new Scanner(txtFile);
int length = 0;
while(scan.hasNextLine()) {
scan.nextLine();
length++;
}
int array[] = new int [length];
array[length++] = scan.nextInt();
System.out.println(array.toString());
int h = 0;
for (int i = 0; i<array.length; i++)
{
h +=array[i];
}
scan.close();
System.out.print(h);
}
}
As suggested, a lot of the code is not really needed. But presumably the 'error' you get is array index out of bounds. Here:
int array[] = new int [length];
array[length++] = scan.nextInt();
So you allocate an array and immediately access off the end of the array. Let's assume length is 42. Therefore, the allocated array elements have indexes 0 to 41. You try and assign something to array[42]. I'm not sure what you're trying to do with that line.
The alternative guess (which we would not need to guess had you mentioned the actual error message) is that your counting lines leaves the scanner positioned at end of file. so the scan.nextInt() call in the assignment gets you an I/O error.
In any case, the core of the solution is something like
int sum = 0;
while (scan.hasNextInt())
sum += scan.nextInt();
No array is needed.
You wrote in your question
I keep getting an error
That would be NoSuchElementException which is thrown by this line of your code:
array[length++] = scan.nextInt();
This is because you have already scanned the entire file and therefore there is no next int.
Remember that in order for people to help you with errors thrown by your code, you need to post the actual exception and the stack trace as well as your code.
You don't need to save all the numbers in the file in an array in order to get the sum of all the numbers. However if you also want to save all the numbers but you don't know in advance how many there are, you can use a List.
Here is a minimal example of how to read the file – which I assume contains only numbers separated by whitespace – and calculate the total. Of-course you need to replace text file path with the actual path to the text file.
File txtFile = new File("text file path");
try (Scanner scan = new Scanner(txtFile)) {
int total = 0;
while (scan.hasNextInt()) {
total += scan.nextInt();
}
System.out.println("Total: " + total);
}
catch (FileNotFoundException xFileNotFound) {
xFileNotFound.printStackTrace();
}
Note that the above code uses try-with-resources.
Basically I am asking for the filename with a method called CS160Input (provided by my instructor) to ask for the filename. The text document has a bunch of entries each on their own lines, and I am trying to assign each number to a place in an array, but I am failing to actually write to the array. I know it is finding the file, because when i print out the counter, it tells me the correct amount of lines in the file. But when I try to print out a place in the array, I tried index 3 as you can see in my code, and it gives me 0 regardless of what I try. I tried creating an array of strings first and I ended up getting null for each index value as well.
public static void caclulate() throws FileNotFoundException {
String fileName = CS160Input.readString("Please enter the name of the file: ");
Scanner sc = new Scanner (new File (fileName));
int value, counter = 0;
int array[] = null;
while (sc.hasNextLine()) {
sc.nextLine();
counter++;
}
Scanner scanner = new Scanner(new File(fileName));
int[] calcArray = new int [counter];
int i = 0;
while(scanner.hasNextInt()){
calcArray[i++] = scanner.nextInt();
}
System.out.println(calcArray[3]);
System.out.println(counter);
}
Thanks to #Gendarme pointing out that hasNextInt() could be spitting out false if there were values in between, it made me take a closer look and I realized that in a previous program the numbers being written to the text file were doubles with 2 decimal places. Once I changed to hasNextDouble(), the program worked as intended.
TL;DR-- how to get a java.util.NoSuchElementException to return a null instead of error and crash the program.
I was writing a program that is supposed to read a series of ints from a text file. In the program the amount of ints will vary each time I run it. I have written a piece of code that will read ints and I want to know how to make the java.util.NoSuchElementException not crash my program and instead return a null.
The code I have writen is as follows
public static void main(String[] args) throws IOException{
Scanner Input = new Scanner(new File("newestcode.txt"));
Integer[] digits = new Integer[100];
int h = 0;
while(true){
digits[h] = Input.nextInt();
h++;
System.out.println(digits[h]);
}
}
in case you are curious, the program I am to be writing is a sort of decryption engine for a bad encryption engine I wrote the other day
try {
digits[h] = Input.nextInt();
h++;
System.out.println(digits[h]);
}catch (NoSuchElementException e){
break;
}
First of all, if you're not sure about amount of ints in your file, don't try to store them into fixed-size array. Use ArrayList instead.
Also don't use endless loop while(true) but consider using Input.hasNext() to check if there still is something to read from file.
And one more. You're trying to print value after increment. This means that you're adding element on 0 position but trying to read it from 1 position. Make increment on the end of the loop.
Scanner Input = new Scanner(new File("newestcode.txt"));
List<Integer> digits = new ArrayList<>();
int h = 0;
while(Input.hasNetxt()){
digits.add(h, Input.nextInt());
System.out.println(digits.get(h));
h++;
}
You should use the input.hasNext() method to check whether the input has any more 'int' before using it.
In order to support any length of int elements, you cannot set the array to a fixed length of 100, you need to use an ArrayList to add elements dynamically.
Scanner input = new Scanner(new File("./newestcode.txt"));
List<Integer> digits = new ArrayList<>();
int h = 0;
while (input.hasNext()) {
digits.add(h, input.nextInt());
System.out.println(digits.get(h));
h++;
}
Note: You need to print digits[h] before increasing the h.
I am working on a class assignment where we can only use arrays and no Collection classes to read a text file and fill an array with information from the text file. the file ArrayData.txt is the information bellow.
The file is formatted in this way:
3 //First line states how many sets are in the file
2 //Next line:there are x numbers in the set
10.22 567.98 //Next Line states the doubles that are in the set
//The pattern continues from there
1 // x numbers in the next set
20.55 // Double in the set
3
20.55 2.34 100.97
My issue is filling the initial array with an array, then filling the second array with the doubles.
Essentially, I want it to look like this:
initArray[0]=> smallArray[2]={10.22,5.67.98}
initArray[1]=> smallArray[1]={20.55}
initArray[2]=> smallArray[3]={20.55,2.34,100.97}
Here is what I have so far:
public static double[] largeArray;
public static double[] insideArray;
public static void main(String[] args) {
String fileInputName = "ArrayData.txt";
Scanner sc = null;
try {
sc = new Scanner(new BufferedReader(new FileReader(fileInputName)));
while (sc.hasNextLine()) {
int i = sc.nextInt();
largeArray= new double[i];
for(int x=0; x<i;x++)
{
int z = sc.nextInt();
insideArray= new double[z];
for(int y=0; y<z; y++)
{
insideArray[z]=sc.nextDouble();
}
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
if (sc != null)
sc.close();
}
}
First off, does this logic even make sense? Secondly, I keep getting an array out of bounds error, so I know something is right, I'm just not sure where.
Remove the while. You want the body to execute only once. Line breaks at the end of the file may cause it to run again and then there will be no nextInt(). If you want to support empty files, make it an if.
Secondly, insideArray[z] = ... should be insideArray[y] = ...
Finally, largeArray should be an array of arrays double[][] (a so called jagged array) and you want to assign insideArray to the according place after filling it.
In my class we're using methods to calculate data from a text file. If I had a file that looked exactly like this:
Bob
25
Molly
30
Dylan
10
Mike
65
Is there anyway to pull this data from a file and then send it to a method to calculate, and then return that calculation to display on main? I'm confused as to how Java would be able to skip each line and calculate the numbers instead of the persons name. I was thinking about using inputFile.nextDouble(); and inputFile.nextLine();. But how would I be able to set a String read the lines in the text file if I'm supposed to readthose text file lines variables as doubles? Sorry for all of the questions, I've been stuck on this for a long time and it's driving me crazy >.
You should just alternately use nextLine() and nextInt()
Scanner sc=new Scanner(new File(/* Path to the file*/));
int i=0;
while(sc.hasNext())
{
if(i==0)
{
name=sc.nextLine();
}
else
{
number=sc.nextInt();
}
i=1-i;
}
I recommend you to use an ArrayList to read the full file:
Scanner s = new Scanner(new File(//Here the path of your file));
int number;
String name;
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext())
{
list.add(s.nextLine());
}
Now you have all the lines of your file (as a String) so now you can operate with the full data that it's inside.
Further, the numbers are in the even lines so you can use a loop to through all the lines and check if the line that you are using now it's even or not.
for(int i = 0; i < list.size(); i++)
{
if(i%2 == 0)
{
number = Integer.parseInt(list.get(i));
//You can use the references to your methods with this number
}
else
{
name = list.get(i);
}
}
With the % you will get the rest of the division (I'm using a property of pairs numbers). With Integer.parseInt you will parse your String to int.
So now you will be able to use this numbers to operate or whatever you want.
EDIT: Here you have an example without using ArrayList. In this case I'm going to use nextLine() and nextInt() functions:
Scanner s = new Scanner(new File(//Here the path of your file));
int count = 0;
int number;
int name;
while(s.hasNext())
{
if(i%2 == 0)
{
number = s.nextInt();
s.nextLine();
//You can use the references to your methods with this number
}
else
{
name = s.nextLine();
}
count = count + 1;
}
If you have doubts about why I'm using s.nextLine() after number without storing any value you can look my answer to this question: Why isn't the scanner input working?
I expect it will be helpful for you!