package foundations;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class gnfmd {
public static void main(String[] args) throws IOException
{
int[] array = new int[40];
int i = 0;
File file = new File("hello.txt");
if (file.exists())
{
Scanner hello = new Scanner(file);
System.out.println("file found");
while (hello.hasNext() && i < args.length)
{
array [i] = hello.nextInt();
i++;
}
hello.close();
for (int l : array)
{
System.out.println(array[l]);
}
}
else
{
System.out.println("file not found");
}
}
}
I came across this problem during the java course. the exercise requires to extract all the integers from a .txt file and print them using arrays but it kept printing zeros even when I copy it from the model answer. can anyone please tell me where I have mistaken
You are printing System.out.println(array[l]);. You should be printing System.out.println(l);, because l already holds a different integer from array on each iteration of the for (int l : array) loop. So on the first iteration, l will hold the value of array[0], on the second iteration it will hold array[1], etc. That and the fact that you only initialize the first args.length positions of the array are the reasons why it prints zeros, since the default values for all positions of an array of int are zeros, and you aren't assigning any other value to most, if not all, of those positions.
Example:
public class MyClass {
public static void main(String args[]) {
int[] array = {1,25,46,97};
for (int i : array) {
System.out.println(i);
}
}
}
Output:
1
25
46
97
Related
I'm working on an assignment which is to read in only integers from a text file (that contains strings and doubles as well) and put them into an array, sort that array, then print each element within it.
I'm getting a NoSuchElementException in my console here's a screenshot NoSuchElementException
I believe the issue comes from fileInput.next(); in my while loop maybe because I've reached the end of the .txt file but I'm not sure how to fix this - any help is much appreciated.
Also here's the .txt file .txt file along w/ my code below:
package Main;
import java.io.*;
import java.util.*;
public class FilterSort {
public static int[] doubleArrayAndCopy(int[] arr) {
//use the length method to get the size of arr
int SIZE = arr.length;
//create a temp array that is double the size of arr
int [] tempArr = new int[2*SIZE];
//store the elements of the arr into temp array using for-loop
for (int i = 0; i < SIZE; i++){
tempArr[i] = arr[i];
}
return tempArr;
// return the temp array
}
public static void main(String[] args){
int[] data = new int[8];
int index = 0;
try {
// create a Scanner and open a file called "data.txt"
//initialize index = 0
Scanner fileInput = new Scanner(new File("src/main/data.txt"));
// while there are lines in the file
// read the line from the file (get tokens)
// check if the token is integer or not.
while (fileInput.hasNextLine()) {
if(fileInput.hasNextInt()){
data[index] = fileInput.nextInt();
index++;
}
else{
fileInput.next();
}
if (index >= data.length){
data = doubleArrayAndCopy(data);
}
}
/* A note : For checking integers : You can use hasNextInt() method of Scanner. If it will be Integer(true), then you can use that token by using nextInt() method of Scanner to read it, if false, then use next() method of Scanner and throw away this token*/
// store the integer token into the answers array
// increment the index
// use the length method of arrays to check if the index is equal or greater
// than the length of array, if it is true, call here doubleArrayAndCopy.
if(index==0){
System.out.println("There is no data in file");
}
else
{
// Sort the array
Arrays.sort(data);
System.out.println("Elements of array sorted in ascending order: ");
// and Print the elements using loop
for (int i = 0; i < data.length; i++)
System.out.println(data[i]);
}
}
catch(FileNotFoundException e){
System.out.println("Error: Data file not found");
}
}
}
I've tried catching the error and throwing it but that doesn't seem to solve the problem, to be honest I'm lost on what else to do.
I'm working on an assignment which is to read in only integers from a
text file (that contains strings and doubles as well) and put them
into an array, sort that array, then print each element within it.
I solved this program in a different way, where I read all the lines in the text file and try to parse each element (separated by space) into integer.
import java.io.*;
import java.util.*;
public class FilterSort {
public static void main(String[] args) {
int[] data = new int[100];
int index = 0;
try {
// create a Scanner and open a file called "data.txt"
//initialize index = 0
Scanner fileInput = new Scanner(new File("data.txt"));
// while there are lines in the file
// read the line from the file (get tokens)
// check if the token is integer or not.
while (fileInput.hasNextLine()) {
String temporary = fileInput.nextLine();
// split the entire line using space delimiter
String[] temporary_array = temporary.split(" ");
for (String s : temporary_array) {
// Use Integer.parseInt to parse an integer
try {
int number = Integer.parseInt(s);
data[index] = number;
index++;
} catch (NumberFormatException e) {
// This is not an integer, do nothing
}
}
}
if (index == 0) {
System.out.println("There is no data in file");
} else {
// Copy the number out from the data array to output array
int[] output = new int[index];
System.arraycopy(data, 0, output, 0, index);
// Sort the output array
Arrays.sort(output);
System.out.println("Elements of array sorted in ascending order: ");
// and Print the elements using loop
for (int i = 0; i < index; i++) {
System.out.println(output[i]);
}
}
} catch (FileNotFoundException e) {
System.out.println("Error: Data file not found");
}
}
}
Output using your text file:
Elements of array sorted in ascending order:
-8
-3
0
1
1
2
2
3
3
4
4
4
9
22
44
90
92
98
99
99
99
100
162
However, this solution has its own limitation (i.e. When the number of integer is greater than 100 or unknown), but can be solved using more sophisticated technique (i.e. ArrayList).
Good luck in your assignment.
I have to read in two texts files that look something like this....
FileOne: 10 1 2 3 4 5 67 75 47 18
FileTwo: 5 65 74 57 68 28 38
The first number represents the count of how many of these integers I should use to populate my array.
I need to read the first line of the file then use that number to populate the two arrays with however many elements specified.
I have figured out how to read in both text files and concatenate them together, however I can't figure out how to only get the first number from the file and use it to determine how many numbers I should use after that.
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class ReadData {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please enter the first file name: ");
String input = s.nextLine();
System.out.println("Please enter the second file name: ");
String input2 = s.nextLine();
int[] data = readFiles(input);
int[] data2 = readFiles(input2);
//System.out.println(Arrays.toString(data));
//System.out.println(Arrays.toString(data2));
System.out.println(Arrays.toString(concat(data, data2)));
}
public static int[] readFiles(String file) {
try {
File f = new File(file);
Scanner s = new Scanner(f);
int counter = 0;
while(s.hasNextInt()) {
counter++;
s.nextInt();
}
int[] arr = new int[counter];
Scanner s1 = new Scanner(f);
for(int i = 0; i < arr.length; i++)
arr[i] = s1.nextInt();
return arr;
}
catch(Exception e) {
return null;
}
}
static int[] concat(int[]... arrays) {
int length = 0;
for (int[] array : arrays) {
length += array.length;
}
int[] result = new int[length];
int pos = 0;
for (int[] array : arrays) {
for (int element : array) {
result[pos] = element;
pos++;
}
}
return result;
}
}
For starters, I'd suggest reading the entire line as a single string, then parse it using a parser which will use space as a delimiter. You will get a DS containing all of your numbers in a more elegant solution.
(Java parsing simple solution : http://pages.cs.wisc.edu/~hasti/cs302/examples/Parsing/parseString.html)
Once you have the DS containing the numbers, you can iterate on it at your pleasure, remembering that the first value determines the amount of future iterations on the DS.
Assuming you use java 8, I'd suggest using the stream functionalities in order to do so : http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
Comment if you require any furthor elaborations and good luck.
Alright, so I'm supposed to work with this as the beginning of my code:
public static int addOdds(int[] input){}
That would return the sum.
I have the add odds part finished with pre loaded arrays.
That was simple enough, but what is flustering my person is how to get this to take an array as input from user.
I know of Scanner from java.utils, but I'm not sure how to get it to run with my code to make it take an array (if it can).
I considered using:
public string void main(String [] args){}
And call Scanner with it, and use Integer.parseint(), but I don't think that could parse an array.
Then call the input the array from scanner to be handed off to the addOdds method.
An example would be {2,3,7,8,4,1} would be what the code must take as input.
Thanks in advance, I'm a bit stumped.
If it helps, here is an example query; inputTwo isn't relevant to the question:
public class Proj2Tester {
public static void main(String[] args){
int[] inputOne = {4,8,9,12,7};
int[] inputTwo = {41,38,19,112,705};
System.out.println("Problem 1 is correct on test input = " + (16 == Problem1.addOdds(inputOne)));
System.out.println("Problem 2 is correct on test input = " + (686== Problem2.getRange(inputTwo)));
}
Following T.J.'s advice I tried the following:
public class Problem1 {
public static void main(String args[]){
System.out.println("Your array is: "+input);
}
}
public static int addOdds(int[] input){
int[] input = new int[args.length]; //Begin T.J.'s segment
int n = 0;
for (String arg : args) {
input[n++] = Integer.parseInt(arg);
int sum =0; //Initializing sum as 0;
for(int i =0; i < inputOne.length; i++){
if(inputOne[i] % 2 !=0){
;
sum = sum + inputOne[i];
break;
}
if(inputOne[i] % 2 == 0){
i++;
break;
}
}
return sum; // placeholder for my answer, not zero should be returned
}
At least two options:
Have the user specify the array entries as individual command line arguments, e.g.:
java YourClass 2 3 7 8 4 1
...and then parse the entries in args into an int array:
int[] input = new int[args.length];
int n = 0;
for (String arg : args) {
input[n++] = Integer.parseInt(arg);
}
Have the user specify the array as a single command-line argument with commas:
java YourClass "2,3,7,8,4,1"
...and then split args[0] on comma and parse the entries in the resulting string array into an int array.
#1 seems simpler to me, as you start out with a string array.
You might want to consider splitting one String on a comma? See here : How to split a string in Java
Sorry if everyone sees me post a lot of silly questions today (just a preface). However this is the final for a summer class and my teacher stopped caring/explaining how to do things for my first coding class.
For this project I have to print a list of integers from a .dat file into a program in reverse order with a max of 40 possible values in the array (Did all that) The problem I am encountering is that he said the program should also be flexible enough to deal with less than 40 values. However given my current code I always encounter an error saying "nosuchelementexception". Any help would be greatly appreciate. Below is a copy of what I have:
import java.io.*; //Imports any file operation (ie Reading or Writing)
import java.util.Scanner; //Imports scanner class
public class program3
{
public static void main(String [] ars) throws IOException
{
double [] Values; // creating array called value
Values = new double [40]; // establishing array with 40 cells
int k; // creating counter integer
Scanner InputFile = new Scanner( new FileReader("temp.dat")); // input file you wish to open.
for (k = 0 ; k < Values.length ; k++)
Values[k] = InputFile.nextDouble();
for (k = Values.length - 1 ; k >= 0 ; k--)
System.out.println("Cell " + k + " contains the value " + Values[k]);
InputFile.close();
}
}
The problem you are having is that the length attribute of an array refers to the declared length, not the amount of data in it.
When you try to use the length (in this case 40) to control the loop you use for reading data, you will get an error if there are fewer elements to read.
What you want to do is read more input only while there exists more input to get:
int k = 0;
while (inputFile.hasNextDouble()) {
Values[k++] = inputFile.nextDouble();
}
Also, consider using an ArrayList instead of an array. The ArrayList class allows you to store a dynamic amount of data, so you don't have to worry about pre-allocating storage space:
ArrayList<Double> values = new ArrayList<>();
while (inputFile.hasNextDouble()) {
values.add(inputFile.nextDouble());
}
You can use a while loop and a counter
import java.io.*; // Imports any file operation (ie Reading or Writing)
import java.util.Scanner; // Imports scanner class
public class program3
{
public static void main(String [] ars) throws IOException
{
double [] Values; // creating array called Values
Values = new double [40]; // establishing array has 40 cells
int counter = 0; // creating counter integer
Scanner inputFile = new Scanner( new FileReader("temp.dat")); //input file you with to open.
while(inputFile.hasNextDouble()){
Values[counter] = InputFile.nextDouble();
counter++;
}
for (i = counter - 1 ; i >= 0 ; i--)
System.out.println("Cell " + i + " contains the value " + Values[i]);
InputFile.close();
}
}
If you do not have to use an Array, use an ArrayList<Double>. This allows you to call values.add(value) to add to the list. The length is variable and you can use your same code (just replace values[i] with values.get(i))
However, if you do have to use arrays, created a method that adds to the array. Start with a 0 length array, and when an element is added, create a new array of length+1, then copy the old elements in, and add the new element at the end.
There are many other ways to go about this, but these two allow you to use your existing working code.
Array approach:
values = new double[0];
public void add(double x){
double[] temp = new double[values.length +1];
for(int i =0; i< values.lenght; i++){
temp[i] = values[i];
}
temp[temp.length-1] = x;
values = temp;
}
you should use an arrayList instead so you don't have to initially set the size of the array. This would make it so that you never have empty elements in the array.
Another option would be to initialize the array with placeholder values like -1, and then only perform the switch if the value is not -1.
Add a counter that keeps track of how many item you put into the array and use that to determine where to stop when you go to print them out.
Is there 40 elements in your .dat file. If there isnt your code probably gave the exception.
for (k = 0 ; k < Values.length ; k++)
Values[k] = InputFile.nextDouble();
If your .dat file doesn't contain 40 elemennts then value[39] can't be filled in.
An Array has a fixed size after initialising it, so you may want to use dynamic datastructure or instead use a while loop as posted below. I personally would recommend an ArrayList in this case.
You should also use the method
Scanner.hasNext() or in your particular case Scanner.hasNextDouble() Docs
to get any new elements.
So your program would then look like this:
import java.io.*; //Imports any file operation (ie Reading or Writing)
import java.util.Scanner; //Imports scanner class
import java.util.ArrayList;
public class program3
{
public static void main(String [] ars) throws IOException
{
ArrayList<Double> doubles = new ArrayList<Double>();
Scanner inputFile = new Scanner( new FileReader("temp.dat"));
while (inputFile.hasNextDouble()) {
doubles.add(inputFile.nextDouble());
}
inputFile.close();
for (Double value : doubles) {
System.out.println(value);
}
}
}
Java has convenient methods in it's Collections class to allow sorting. You may want to check this out if you haven't already.
I admire your grit getting on Stack Overflow.
To reward you here's your answer.
The first for loop you have iterates over your new, empty array. That would be find except you are RETRIEVING information from the Scanner object, InputFile.
So you should in fact be iterating over that object! Not your array. No shame though. Classic mistake.
Here's my version of your code:
import java.io.FileReader;
import java.io.IOException; //Imports any file operation (ie Reading or Writing)
import java.util.Scanner; //Imports scanner class
public class program3
{
public static void main( String [] ars ) throws IOException
{
double [] Values; // creating array called value
Values = new double [40]; // establishing array has 20 cells
int k; // creating counter integer
//input file you with to open.
Scanner InputFile = new Scanner( new FileReader( "temp.dat" ) );
for ( k = 0; InputFile.hasNextDouble(); k ++ )
Values[k] = InputFile.nextDouble();
for ( k = Values.length - 1; k >= 0; k-- )
System.out.println( "Cell " + k + " contains the value " + Values[k] );
InputFile.close();
}
}
Hope this helps!
I cannot figure out what is wrong with this.
I have to read in a file (the file has numbers) and store the numbers into an array.
Here is the file:
http://dl.dropboxusercontent.com/u/31878359/courses/15/scores1.txt
I understand the first number is a zero and I cannot change the numbers or the order of the numbers in the file.
File
0
10
20
30
40
50
60
70
80
90
Here is my code:
import java.util.*;
import java.io.*;
public class Check {
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("scores1.txt"));
process(input);
}
public static void process(Scanner input) {
int[] numbers = new int [input.nextInt()];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
}
Arrays.sort(numbers);
System.out.print("numbers: "+Arrays.toString(numbers));
}
}
This is the output:
numbers: []
I'm assuming it's a problem with declaring the array.
The problem is that, your first value of file is 0. So array size is 0. Change your first value so that, you can get rest of values into array.
The first value in the file is 0.
int[] numbers = new int [input.nextInt()]; // this input.nextInt() gets the first line
You're making an array of size 0
Since there are 10 numbers in the file. initialize with size 10;
int[] numbers = new int [10];
public static void process(Scanner input) {
List<Integer> number = new ArrayList<Integer>();
while(input.hasNext()) {
number.add(input.nextInt());//i hope all ints are there in the file
}
int[] numbers = number.toArray(new int[number.size])
//then do sort and all
}
hope this will help
My suggestion would be use ArrayList
public static void process(Scanner input) {
List list = new ArrayList();
while(input.hasNextInt()){
list.add(input.nextInt());
}
Collections.sort(list);
System.out.print("numbers: " + list);
}