I have to write a method that reads the file integers.txt and return an array of integers. I have to convert each line of data from text to an integer.
However, I cannot figure out why I am getting an error when I try to assign the array x to the integers within the file and when I convert the data to integers. I am also getting an error with my return statement.
public static int[] processFile (String filename) throws IOException, FileNotFoundException {
double number;
double average;
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream("integers.txt")));
String line;
while ((line = inputReader.readLine()) != null) {
number = Int.parseInt(line);
int[] x = (number);
inputReader.close();
}
return int[] x;
}
There are multiple issues with your code:
You are using return int[] x; instead of simply return x;
x is only assigned inside the while, so you can't return it outside
x = (number); isn't a correct method for adding a value to the array
The int[] x; is never initialized
You use double number at the top of the method, but then assign it with an int here: number = Int.parseInt(line);
My suggestions is to use this instead, which will give an ArrayList<int> as output.
public static ArrayList<Integer> processFile (String filename) throws IOException, FileNotFoundException
{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream("integers.txt")));
String line;
ArrayList<Integer> list = new ArrayList<>();
while ((line = inputReader.readLine()) != null) {
int number = Int.parseInt(line);
list.add(number);
}
inputReader.close();
return list;
}
If you really need an int[] instead, you'll have to give it a size first like this: int[] x = new int[size_here]; For example:
public static int[] processFile (String filename) throws IOException, FileNotFoundException
{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream("integers.txt")));
String line;
int[] array = new int[100]; // Example size of 100
int index = 0;
while ((line = inputReader.readLine()) != null) {
int number = Int.parseInt(line);
array[index++] = number;
}
inputReader.close();
return array;
}
And if you need an int[] instead, AND don't know the size beforehand, try this instead:
public static int[] processFile (String filename) throws IOException, FileNotFoundException
{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream("integers.txt")));
String line;
ArrayList<Integer> list = new ArrayList<>();
while ((line = inputReader.readLine()) != null) {
int number = Int.parseInt(line);
list.add(number);
}
inputReader.close();
return convertIntegers(list);
}
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}
Firstly it's Integer.parseInt()
number = Int.parseInt(line);
int[] x = (number);
number will contain a single int not an array of ints. so this int[] x = (number); assignment is wrong.
return int[] x; this is also invalid syntax.
There are a few problems here. To answer your question, you can't assign an int to an int array. Next, unless you entered your code incorrectly, you are closing the inputReader inside the while loop that is doing the reading. Also, you are returning int[] x. That is wrong. Return x.
Related
Have a two text file with words list. need save both file in two array.I know how to do it using list and set.. but here I want know how to do it using only arrays.Only array and no predefined functions such as Arrays.sort() or Collections.sort() can be used
no list no ArrayList or no class from Java Collection Frameworks can be used.
public class Main {
public static Set<String> setlist1= new HashSet<>();
public static String[] arrayList=new String[file1count];
public static String[] array2=new String[file2count];
public static int file1count=0;
public static int file2count=0;
public static void main(String[] args) {
try {
/*read the files*/
Scanner rf= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt")));
Scanner rf2= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt")));
String line;
String line2;
while(rf.hasNext()){
line=rf.nextLine();
file1count++;
}
while(rf2.hasNext()){
line2=rf2.nextLine();
file2count++;
}
rf.close();
rf2.close();
}catch(IOException e){
System.out.println(e);
}
}
}
The problem with using arrays is that you don't know in advance what length to allocate.
You basically have two options:
read each file twice
allocate an array of some initial length, and reallocate is as needed (that's what an ArrayList does.)
Second option: let's have a method readFile that reads all the lines from a file and returns an array:
public static String[] readFile(String fileName) throws IOException {
try (Reader reader = new FileReader(fileName);
BufferedReader in = new BufferedReader(reader)) {
String[] lines = new String[10]; // start with 10
int count = 0;
String line;
while ((line = in.readLine()) != null) {
if (count >= lines.length) {
lines = reallocate(lines, count, 2*lines.length);
}
lines[count++] = line;
}
if (count < lines.length) {
// reallocate to the final length;
lines = reallocate(lines, count, count);
}
return lines;
}
}
private static String[] reallocate(String[] lines, int count,
int newLength) {
String[] newArray = new String[newLength];
for (int i = 0; i < count; ++i) {
newArray[i] = lines[i];
}
lines = newArray;
return lines;
}
BufferedReader reader1 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt"));
BufferedReader reader2 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt"));
String line1 = reader1.readLine();
String[] array1 = new String[10000000];
String[] array2 = new String[10000000];
String line2 = reader2.readLine();
boolean areEqual = true;
int lineNum = 1;
while (line1 != null || line2 != null) {
if (line1 == null || line2 == null) {
areEqual = false;
break;
} else if (!line1.equalsIgnoreCase(line2)) {
areEqual = false;
break;
}
if (line1 != null) {
array1[lineNum] = line1;
}
if (line1 != null) {
array2[lineNum] = line2;
}
line1 = reader1.readLine();
line2 = reader2.readLine();
lineNum++;
}
if (areEqual) {
System.out.println("Same content.");
} else {
System.out.println("different content");
}
reader1.close();
reader2.close();
You can simply try above code.
Here I had used only WHILE loop, BufferedReader and FileReader.
In this function, I want to get text in the file then convert it from string to decimal values, by add this text to an array apply some loops and put the result to array of integer. While returning this integer array it gives me an error "cannot find symbol variable integerArray"
int[] inputfile () throws Exception{
BufferedReader br = null;
String sCurrentLine;
String message;
br = new BufferedReader(new FileReader("\input.txt"));
while ((sCurrentLine = br.readLine()) != null) {
message=sCurrentLine.toString();
char[] messageArray=message.toCharArray();
int[] integerArray = new int[messageArray.length];
for(int i=0; i<messageArray.length; i++)
integerArray[i] = (int)messageArray[i];
}
return integerArray;
}
How can I solve it?
Update:
I declared variable integerArray outside the while loop, but it always returns the null value, Is there any possible way to return integerArray as int values? because Arrays.toString(integerArray) returns String representation of that array
int[] inputfile () throws Exception{
BufferedReader br = null;
String sCurrentLine;
String message;
br = new BufferedReader(new FileReader("\\input.txt"));
int[] integerArray = null
while ((sCurrentLine = br.readLine()) != null) {
message=sCurrentLine.toString();
char[] messageArray=message.toCharArray();
int[] integerArray = new int[messageArray.length];
for(int i=0; i<messageArray.length; i++)
integerArray[i] = (int)messageArray[i];
}
return integerArray;
Your integerArray is inside the while loop. Declare it outside the loop and change its value inside it, then it will work.
integerArray is a local variable in the while loop , it's inaccessible outside it. Declare it outside the loop
int[] integerArray =null ;
while ((sCurrentLine = br.readLine()) != null) {
// other code
integerArray = new int[messageArray.length];
// other code
}
int[] integerArray must be declared before the loop, in order for you to be able to return it after the loop.
int[] inputfile () throws Exception{
int[] integerArray = null;
BufferedReader br = null;
String sCurrentLine;
String message;
br = new BufferedReader(new FileReader("\input.txt"));
while ((sCurrentLine = br.readLine()) != null) {
message=sCurrentLine.toString();
char[] messageArray=message.toCharArray();
integerArray = new int[messageArray.length];
for(int i=0; i<messageArray.length; i++)
integerArray[i] = (int)messageArray[i];
}
return integerArray;
}
Making a hangman style of game
I have the random word now. How do I replace the letters of the word with an asterix * so that when the program starts the word is shown as *.
I assume that when someone inputs a letter for the hangman game you get the index of that character in the word and then replace the corresponding *.
public class JavaApplication10 {
public static String[] wordArray = new String[1];
public static String file_dir = "Animals.txt";
public static String selectedWord = "";
public static char[] wordCharacter = new char[1];
Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
wordArray = get_word(file_dir);
selectedWord = select_word(wordArray);
System.out.println(selectedWord);
}
public static String[] get_word(String file_dir) throws IOException {
FileReader fileReader = new FileReader(file_dir);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
public static String select_word(String[] wordArray) {
Random rand = new Random();
int lines = Math.abs(rand.nextInt(wordArray.length)- 1);
return wordArray[lines];
}
}
If you know how many lines are there you could use Random method in java with a specific range to pick out a line at random.
Then you could read the file line-by-line till you reach that random line and print it.
// Open the file
FileInputStream fstream = new FileInputStream("testfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int counter=0;
//While-loop -> Read File Line By Line till the end of file
//And will also terminate when the required line is printed
while ((strLine = br.readLine()) != null && counter!=randomValue){
counter++;
//You need to set randomValue using the Random method as suggested
if(counter==randomValue)
// Print the content on the console
System.out.println (strLine+"\n");
}
//Close the input stream
br.close();
Assuming Java 8:
// Loading ...
Random R = new Random(System.currentTimeMillis());
List<String> animals = Files.readAllLines(Paths.get(path));
// ...
// When using
String randomAnimal = animals.get(R.nextInt(animals.size()));
Answer of your first question :
First you have to get the total number of lines
Then you have to generate a random number between 1 and that total number.
Finally, get the required word
try {
InputStream is = new BufferedInputStream(new FileInputStream("D:\\test.txt"));
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
int noOfLines = count+1;
System.out.println(noOfLines);
Random random = new Random();
int randomInt = random.nextInt(noOfLines);
FileReader fr = new FileReader("D:\\test.txt");
BufferedReader bufferedReader =
new BufferedReader(fr);
String line = null;
int counter =1;
while((line = bufferedReader.readLine()) != null) {
if(counter == randomInt)
{
System.out.println(line); // This the word you want
}
counter++;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally {
//is.close();
}
I'm trying to read a csv file into either an ArrayList or a String [][] array. In this I'm trying to read it into a list and then form the list, using a tokenizer, into an array. The csv file have 7 columns (A - G) and 961 rows (1-961). My for loop for the 2D array keeps returning a null pointer, but I think it should be working..
public class FoodFacts
{
private static BufferedReader textIn;
private static BufferedReader foodFacts;
static int numberOfLines = 0;
static String [][] foodArray;
public static String aFact;
static int NUM_COL = 7;
static int NUM_ROW = 961;
// Make a random number to pull a line
static Random r = new Random();
public static void main(String[] args)
{
try
{
textIn = new BufferedReader(new InputStreamReader(System.in));
foodFacts= new BufferedReader(new FileReader("foodfacts.csv"));
Scanner factFile = new Scanner(foodFacts);
List<String> facts = new ArrayList<String>();
String fact;
System.out.println("Please type in the food you wish to know about.");
String request = textIn.readLine();
while ( factFile.hasNextLine()){
fact = factFile.nextLine();
StringTokenizer st2 = new StringTokenizer(fact, ",");
//facts.add(fact);
numberOfLines++;
while (st2.hasMoreElements()){
for ( int j = 0; j < NUM_COL ; j++) {
for (int i = 0; i < NUM_ROW ; i++){
foodArray [j][i]= st2.nextToken(); //NULL POINTER HERE
System.out.println(foodArray[j][i]);
}
}
}
}
}
catch (IOException e)
{
System.out.println ("Error, problem reading text file!");
e.printStackTrace();
}
}
}
Initialize your foodArray as foodArray = new String[NUM_ROW][NUM_COL]; before using it.
Also, there is no need for inner for loop as you are reading one row at a time.
use numberOfLines as row:
while ( factFile.hasNextLine() && numberOfLines < NUM_ROW){
fact = input.nextLine();
StringTokenizer st2 = new StringTokenizer(fact, ",") ;
//facts.add(fact);
while (st2.hasMoreElements()){
for ( int j = 0; j < NUM_COL ; j++) {
foodArray [numberOfLines][j]= st2.nextToken();
System.out.println(foodArray[numberOfLines][i]);
}
}
numberOfLines++;
}
Alternatively, I think you can use split to get all columns as once e.g.
while ( factFile.hasNextLine() && numberOfLines < NUM_ROW){
fact = input.nextLine();
foodArray [numberOfLines++] = fact.split(",");
}
One question: Is there any specific purpose for declaring all variables as static class variables? Most of them fit as local variable inside the method e.g. numberOfLines?
You can use this String [][] foodArray = csvreadString(filename); method. It actually reads the file twice, but I don't know how to get the csv dimension without reading the data (you need the dimension in order to initialize the array), and this is very fast in comparison to other methods that I tried.
static public class PairInt {
int rows = 0;
int columns = 0;
}
static PairInt getCsvSize(String filename) throws Throwable {
PairInt csvSize = new PairInt();
BufferedReader reader = new BufferedReader(new FileReader(new File(filename)));
String line;
while ((line = reader.readLine()) != null) {
if (csvSize.columns == 0) {
csvSize.columns = line.split(",").length;
}
csvSize.rows++;
}
reader.close();
return csvSize;
}
static String[][] csvreadString(String filename) throws Throwable {
PairInt csvSize = getCsvSize(filename);
String[][] data = new String[csvSize.rows][csvSize.columns];
BufferedReader reader = new BufferedReader(new FileReader(new File(filename)));
for (int i = 0; i < csvSize.rows; i++) {
data[i] = reader.readLine().split(",");
}
return data;
}
I'm running into an issue when converting some code for another project and was hoping for a bit of help. In the 'readFile' method, I am trying to parse a String to integers when I read the file. However, it is giving me the error 'array found, but int required'
import java.util.*;
import java.io.*;
public class JavaApplication1
{
static int [] matrix = new int [10];
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
String fileName = "Integers.txt";
// read the file
readFile(fileName);
// print the matrix
printArray(fileName, matrix);
}
// Read File
public static void readFile(String fileName) throws IOException
{
String line = "";
FileInputStream inputStream = new FileInputStream(fileName);
Scanner scanner = new Scanner(inputStream);
DataInputStream in = new DataInputStream(inputStream);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
int lineCount = 0;
String[] numbers;
while ((line = bf.readLine()) != null)
{
numbers = line.split(" ");
for (int i = 0; i < 10; i++)
{
matrix[lineCount][i] = Integer.parseInt(numbers[i]);
}
lineCount++;
}
bf.close();
}
public static void printToFile(String fileName, String output) throws IOException
{
java.io.File file = new java.io.File(fileName);
try (PrintWriter writer = new PrintWriter(file))
{
writer.print(output);
}
}
public static void printArray(String fileName, int [] array)
{
System.out.println("The matrix is:");
for (int i = 0; i < 10; i++)
{
System.out.println();
}
System.out.println();
}
}
matrix is an array of type int, which means matrix[lineCount] is an int.
You are tryng to do matrix[lineCount][i] which is getting the place i of an int.
That is why you are getting that error.
I guess you wanted matrix to be int[][] matrix = new int[10][10];
matrix[lineCount][i] = Integer.parseInt(numbers[i]);
is wrong.
Should be either
matrix[lineCount]= Integer.parseInt(numbers[i]);
OR
matrix[i]= Integer.parseInt(numbers[i]);