I have a float array which I stored in it some values from user input.
I have 2 methods one that saves the values stored in the array to a text file each value on a line and the second method rereads the values again and stores them in the array. for example, the user input was 1,2,3,4 I save them to a text file and then I read the same txt file now my array should display 8 elements 1,2,3,4,1,2,3,4.
the problem I'm having is that when I store these elements on the txt file it's storing them and adding like 100 zeros under them and when I'm calling the second method to reread these elements from the file it reads the zeros so when I'm displaying the elements in my array it's displaying 0,0,0,0 when it should display 1,2,3,4,1,2,3,4.
what might be causing me this problem?
public void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file dont exist");
e.printStackTrace();
}
}
public void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
You may check why the array is populated properly using additional println statement. In your version each element of array is populated with the same element read from the file. If you remove the inner loop, array will be populated properly.
int i=0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
System.out.println((i) + "::"+numbers[i]);
i++;
}
Zeros are being added because you're saving numbers as float. If you store an integer 3 in a float variable it will be converted to a float equivalent which is 3.0
Also you don't need two loops here,
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
You can instead do following,
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
Following is a fully functional program of what you desire,
import java.util.Scanner;
import java.io.*;
public class Hello {
public static float[] numbers = {1,2,3,4,1,2,3,4};
public static void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file doesn't exist");
e.printStackTrace();
}
}
public static void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
for(int j = 0; j < numbers.length; j++) {
System.out.println(numbers[j]);
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
saveValuesToFile(scanner);
readFromFile(scanner);
}
}
Related
i am trying to read float values from a .txt file to initialize an array but it is throwing a InputMismatchException
Here's the method and the sample values i am trying to read from the file are 4 2 1 4
public class Numbers {
private Float [] numbers;
public int default_size = 10;
String fileName = new String();
public void initValuesFromFile()
{
Scanner scan = new Scanner(System.in);
fileName = scan.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
}
You need to read line from the file and split using space or even better \\s+ and then run a for loop for all items split into an array of strings and parse each number and store them in a List<Float> and this way will work even if you have multiple numbers in further different lines. Here is the code you need to try,
Float[] numbers = new Float[4];
Scanner scan = new Scanner(System.in);
String fileName = scan.next();
scan.close();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
String nums[] = input.trim().split("\\s+");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(nums[i]);
}
break;
}
System.out.println(Arrays.toString(numbers));
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
This prints,
[4.0, 2.0, 1.0, 4.0]
this is a debugger error and runs an infinite loop where shown.
I am trying to load a file and have the gameboard be set to the chars in the text file (which are saved previously by user as shown) but in the debugger problem it sets next nextChar infinitely to □ after the first char has been read. I have had multiple attempts at trying to fix this myself but I cannot find a solution. Any help on how to fix this bug would be greatly appreciated. If any more details are needed give voice and see questions answered hastily.
This is the saving section of code.
/**
* A method to save the current state of the game
*/
public static void saveGame()
{
FileOutputStream outputStream = null;
PrintWriter printWriter = null;
try
{
System.out.println("Please name the save game file.");
outputStream = new FileOutputStream(Genio.getString());
printWriter = new PrintWriter(outputStream);
int i, j =0;
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
printWriter.println(gameBoard[i][j]);
}
}
}
catch (IOException e)
{
System.out.println("Sorry an error occured during saving.");
}
finally
{
if (printWriter != null)
{
printWriter.close();
}
}
}
This is the loading section of code;
/**
* A method to load a game.
*/
public static void loadGame()
{
FileReader fileReader = null;
BufferedReader bufferedReader = null;
char nextChar;
String line;
try
{
System.out.println("Please enter the name of your save file:");
fileReader = new FileReader(Genio.getString());
bufferedReader = new BufferedReader(fileReader);
nextChar = (char)bufferedReader.read();
while ((line = bufferedReader.readLine()) != null)
{
for (int i=0; i<row; i++)
{
for (int j=0; j<col; j++)
{
if (nextChar == '-' || nextChar == 'Y' || nextChar == 'R') //Infinite loop here where nextChar = □
{
gameBoard[i][j] = nextChar;
nextChar = (char)bufferedReader.read();
System.out.print(gameBoard[i][j]);
line = bufferedReader.readLine();
}
else
{
nextChar = (char)bufferedReader.read();
j--;
}
}
System.out.print("\n");
}
line = bufferedReader.readLine();
}
System.out.println("1\t2\t3\t4\t5\t6\t7");
}
catch (IOException e)
{
System.out.println("Sorry an error occured during the loading of the file.");
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch (IOException e)
{
System.out.println("Sorry, an error has occured when closing the file.");
}
}
}
}
Not sure why you are reading a line AND reading characters.
You need to read each line and process each character in that line, for example...
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ReadConnect4 {
private static final String TEST_BOARD = "-------\n"
+ "-------\n"
+ "-------\n"
+ "-------\n"
+ "-Y-----\n"
+ "-Y--R--\n";
private static final int ROWS = 6;
private static final int COLS = 7;
public static void main(String[] args) throws Exception {
ByteArrayInputStream pretendFile = new ByteArrayInputStream(TEST_BOARD.getBytes());
char[][] board = readBoard(pretendFile);
printBoard(board);
}
private static void printBoard(char[][] board) {
for(int k = 0; k < board.length; k++) {
for(int j = 0; j < board[k].length; j++) {
System.out.print(board[k][j]);
}
System.out.println();
}
}
private static char[][] readBoard(InputStream stream) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
int row = 0;
char[][] result = new char[ROWS][COLS];
// Read each line, stop when end of file (line is null)...
while((line = reader.readLine()) != null) {
// For each column...
for(int col = 0; col < 7; col++) {
// Get character from line, store in array
result[row][col] = line.charAt(col);
}
row++;
}
return result;
}
}
OUTPUT:
-------
-------
-------
-------
-Y-----
-Y--R--
To answer your question "why does it read box things", it's probably reading the end-of-stream and returning the character equivalent of "-1"
I want combine the two methods Just some error in my document parser, frequencyCounter and parseFiles thsi code.
I want all of frequencyCounter should be a function that should be executed from within parseFiles, and relevant information don't worry about the file's content should be passed to doSomething so that it knows what to print.
Right now I'm just keep messing up on how to put these two methods together, please give some advices
this is my main class:
public class Yolo {
public static void frodo() throws Exception {
int n; // number of keywords
Scanner sc = new Scanner(System.in);
System.out.println("number of keywords : ");
n = sc.nextInt();
for (int j = 0; j <= n; j++) {
Scanner scan = new Scanner(System.in);
System.out.println("give the testword : ");
String testWord = scan.next();
System.out.println(testWord);
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
// System.out.println(strLine);
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The code below gives you this output:
Professor frequency: 54
engineering frequency: 188
data frequency: 2
mining frequency: 2
research frequency: 9
Though this is only for doc1, you've to add a loop to iterate on all the 5 documents.
public class yolo {
public static void frodo() throws Exception {
String[] keywords = { "Professor" , "engineering" , "data" , "mining" , "research"};
for(int i=0; i< keywords.length; i++){
String testWord = keywords[i];
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
hope this helps!
so here is ALL of my code, which, in summary, standardises two text files then prints out the result.
import java.io.*;
import java.util.*;
public class Plagiarism {
public static void main(String[] args) {
Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
for (int i = 0; i < args.length; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
List<String> foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
System.out.print(foo.get(j));
}
}
}
catch (Exception e) {
System.err.println ("Error reading from file");
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
myList.add(line.replaceAll("[^a-zA-Z0-9]","").toLowerCase().trim());
}
return myList;
}
}
The next bit I want to implement is this: Using the command line, the 3rd argument will be any integer(size of blocks) which the user enters. I have to use this then to store the elements of that array into separate blocks which overlap. EG: The cat sat on the mat, block size 4. Block 1 would be: Thec Block 2: heca Block 3: ecat, and so on, until it reaches the end of the array.
Any ideas?
Thanks in advance guys.
To get the block size use this :
if(args.length != 4)
return;
int blockSize = Integer.valueOf(args[3]);
This an example that could help you
import java.util.*;
public class Test {
public static void main(String[] args) {
String line = "The dog is in the house";
line = line.replace(" ", "");
List<String> list = new ArrayList<String>();
for (int i = 0; i <= line.length() - 4; i++)
list.add(line.substring(i, i + 4));
System.out.println(list);
}
output :
[Thed, hedo, edog, dogi, ogis, gisi, isin, sint, inth, nthe, theh, heho, ehou, hous, ouse]
Is that what you want to do
WE can code it in mulitple ways, here is one example.
Input 3 arguments first 2 are files and 3rd one is the block size:
File1 contain: this is a boy
File2 contain: this is a girl
block size: 4
Expected Output:
this hisi isis sisa isab sabo aboy boyt oyth ythi this hisi isis sisa isag sagi agir girl
Program:
import java.io.;
import java.util.;
public class Plagiarism {
public static void main(String[] args) {
//Plagiarism myPlag = new Plagiarism();
/*args = new String[3];
Scanner s = new Scanner(System.in);
System.out.println("Enter the 1st file path");
args[0] = s.next();
System.out.println("Enter the 2nd file path");
args[1] = s.next();
System.out.println("Enter size of block");
args[2] = s.next();*/
int blockSize = Integer.valueOf(args[2]);
StringBuilder wholeContent = new StringBuilder("");
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
for (int i = 0; i < args.length-1; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
List<String> foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
//System.out.print(foo.get(j));
wholeContent.append(foo.get(j));
}
}
System.out.println("The content of Line is = "+ wholeContent);
System.out.println("The content of line based on the block size = "+ blockSize + " is:");
for(int j=0; j<=(wholeContent.length()-blockSize); j++){
System.out.print(wholeContent.substring(j, j+4));
System.out.print(" ");
}
}
catch (Exception e) {
e.printStackTrace();
System.err.println ("Error reading from file");
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
if(!" ".equals(line))
myList.add(line.replaceAll("[^a-zA-Z0-9]","").toLowerCase().trim());
}
return myList;
}
}
All you are asking to do can be done with string manipulation. First use replaceAll() to remove your spaces, then use a for loop and substring() to create your blocks.
for your for loop you need to modify it so that it reads the two texts, then uses the 3rd argument as the block size so you would change your for loop from:
for(int i = 0; i<args.length;i++)
to:
for(int i = 1; i<3; i++)
this reads the first two arguments but not the third
A simple data file which contains
1908,Souths,Easts,Souths,Cumberland,Y,14,12,4000
1909,Souths,Balmain,Souths,Wests,N
Each line represents a season of premiership and has the following format: year, premiers, runners up, minor premiers, wooden spooners, Grand Final held, winning score,
losing score, crowd
I know how to store a data into an array and use the delimiter, but I am not exactly sure how to store EACH data item by a comma into separate arrays? Some suggestions and what particular code to be used would be nice.
UPDATE:
I just added the code but it still didn't work. Here's the code:
import java.io.*;
import java.util.Scanner;
public class GrandFinal {
public static Scanner file;
public static String[] array = new String[1000];
public static void main(String[] args) throws FileNotFoundException {
File myfile = new File("NRLdata.txt");
file = new Scanner (myfile);
Scanner s = file.useDelimiter(",");
int i = 0;
while (s.hasNext()) {
i++;
array[i] = s.next();
}
for(int j=0; j<array.length; j++) {
if(array[j] == null)
;
else if(array[j].contains("Y"))
System.out.println(array[j] + " ");
}
}
}
Here you go. Use ArrayList. Its dynamic and convenient.
BufferedReader br = null;
ArrayList<String> al = new ArrayList();
String line = "";
try {
br = new BufferedReader(new FileReader("NRLdata.txt"));
while ((line = br.readLine()) != null) {
al.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
What does not work in your case ?
Because your season array is empty. You need to define the length, for ex:
private static String[] season = new String[5];
This is not right because you don't know how many lines you are going to store. Which is why I suggested you to Use ArrayList.
After working around a bit, I have come up with following code:
private static File file;
private static BufferedReader counterReader = null;
private static BufferedReader fileReader = null;
public static void main(String[] args) {
try {
file = new File("C:\\Users\\rohitd\\Desktop\\NRLdata.txt");
counterReader = new BufferedReader(new FileReader(file));
int numberOfLine = 0;
String line = null;
try {
while ((line = counterReader.readLine()) != null) {
numberOfLine++;
}
String[][] storeAnswer = new String[9][numberOfLine];
int counter = 0;
fileReader = new BufferedReader(new FileReader(file));
while ((line = fileReader.readLine()) != null) {
String[] temp = line.split(",");
for (int j = 0; j < temp.length; j++) {
storeAnswer[j][counter] = temp[j];
System.out.println(storeAnswer[j][counter]);
}
counter++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
I have added counterReader and fileReader; which are used for counting number of lines and then reading the actual lines. The storeAnswer 2d array contains the information you need.
I hope the answer is better now.