Unexpected output filling an array with characters read from a text file - java

I'm trying to read a text file called input.in an array of characters representing a map. The file contains two integers N and numLifes, and the corresponding matrix. N represents the dimension of a square matrix (NxN).
I want that if N is less than 10, assign to the variable N, the value of 10 and fill the matrix 'mVill' with a '#', and then read the map file and integrate it with the matrix filled with '#'. Heres the code:
import java.io.*;
import java.io.FileReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class hola {
public static void main(String[] args) {
char mVill[][] = null;
int N, i,j, numLifes;
String line=null;
StringTokenizer tk;
char caract;
FileInputStream fstream = null;
try {
fstream = new FileInputStream("C:/input.in");
} catch (FileNotFoundException e) {
System.exit(-1);
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
try {
if ((line = br.readLine()) == null) {
System.out.print("Error empty file...");
System.exit(0);
}
} catch (IOException e) {
}
tk = new StringTokenizer(line);
N = Integer.parseInt(tk.nextToken());
numLifes = Integer.parseInt(tk.nextToken());
int nAux=N;
if (N<10){
N=10;
mVill = new char[N][N];
for (char[] row: mVill)
Arrays.fill(row, '#');
for (i=0; i <nAux; i++) {
for (j=0;j<nAux;j++){
try{
caract = (char) br.read();
mVill[i][j]=caract;
}catch (Exception e){
System.out.println("Error in read file");
}
}
}
}else{
mVill = new char[N][N];
for (i = 0; i < N; i++) {
try {
mVill[i] = br.readLine().toCharArray();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
System.out.println(N+" "+numLifes);
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
System.out.print(mVill[i][j]);
}
System.out.println();
}
}//end main
}//end class
For this input:
7 3
F..*..F
.##.##.
.#...#.
*..P..*
.#...#.
.##.##.
F..*..F
the output is (which is wrong):
F..*..F###
.##.####
#.
.#.###
..#.
*###
..P..*
###
.#...####
.
.##.###
##########
##########
##########
The output should I expect to receive it:
F..*..F###
.##.##.###
.#...#.###
*..P..*###
.#...#.###
.##.##.###
F..*..F###
##########
##########
##########
What am I doing wrong? I do not see any error in reading the file.

Following Steve's answer, the quick and dirty way to correct it would be to do this when you are reading your characters:
caract = (char) br.read();
while (caract == '\n' || caract == '\r') {
caract = (char) br.read();
}
mVill[i][j]=caract;
So the linefeed and carriage return characters would be skipped.

I think you're not taking the carriage-return / linefeed characters into account when reading the input. I would probably use a different technique, where you read a line at a time rather than a single character.
Try testing the character to see if it is a cr/lf and skip it if so.

Related

Increase all characters by 1 (JAVA)

So I need help with increasing all characters in a file. Whole file is able to read and get all the info form the user but when it comes to actual increasing all characters from (this case) a file it just outputs a blank file.
Goal of this program is to read in a users file get all the text from the file and increase or decrease the letters by one. So A is now a B or B is now a C or via versa B is now a A or C is now a B. When it goes to export/close the file it just is blank.
Here is that portion of the code:
while (fileIn.hasNext())
{
letter.add(fileIn.next());
for (int i = letter.size() - 1; i >= 0; i--)
{
ch = letter.get(i).charAt(0);
ch--;
fileout1.println(ch);
}
//Makes a new line at end of line
System.out.println();
}
Whole code is as follows:
import java.util.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.util.ArrayList;
public class Assignment9
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
Scanner fileIn;
File f;
char ch = 65;
String fileName = "";
boolean userA = false;
String usersChoice = "";
ArrayList<String> letter = new ArrayList<String>();
try
{
System.out.println("Please enter the file name that you would like encrypted/decrypted: ");
fileName = in.nextLine();
//Builds the file and attaches the Scanner
f = new File (fileName);
fileIn = new Scanner (f);
PrintWriter fileout1 = new PrintWriter ("decrypt.txt");
PrintWriter fileout2 = new PrintWriter ("encrypt.txt");
System.out.println("Would you like to Decrypt or Encrypt the file?");
usersChoice = in.nextLine();
userA = true;
//Loop through the file and translate the characters
if (usersChoice.equalsIgnoreCase("Decrypt"))
{
while (fileIn.hasNext())
{
letter.add(fileIn.next());
for (int i = letter.size() - 1; i >= 0; i--)
{
ch = letter.get(i).charAt(0);
ch--;
fileout1.println(ch);
}
//Makes a new line at end of line
System.out.println();
}
//Decrease every letter by 1 (runs backwords)
System.out.println("Decrypt.txt has been created.");
fileout1.close();
}
//encrypts the file by increasing by 1
if (usersChoice.equalsIgnoreCase("encrypt"))
{
while (fileIn.hasNext())
{
letter.add(fileIn.next());
}
//Decrease every letter by 1 (runs backwords)
for (int i = letter.size() -1; i >= 0; i--)
{
System.out.println(letter);
ch --;
}
System.out.println("Encrypted.txt has been created.");
fileout2.close();;
}
} //end of try
catch (FileNotFoundException e)
{
System.out.println("Sorry invalid file, please try again");
fileName = in.nextLine();
}
} // end of main
} //end of program
You can do something like as below,
FileReader fr = null;
FileWriter fw = null;
int c;
try {
fr = new FileReader("C:\\Zia\\test.txt");
fw = new FileWriter("C:\\Zia\\Result.txt");
while ((c = fr.read()) != -1) {
if(c!=32)
fw.write((char)--c);
else
fw.write((char)c);
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
My test.txt file contains the below content,
Hello How are you doing.
and result.txt contains the below result after decreasing the char by one.
Gdkkn Gnv `qd xnt cnhmf-
you may interchange the file name for both the file for Reader and writer and increase the char by 1 to verify the decryption.

Java replace characters in a TextFile - Alice In Wonderland

I'm trying to make a compressor for TextFiles and I get stuck at replacing characters.
This is my code:
compress.setOnAction(event ->
{
String line;
try(BufferedReader reader = new BufferedReader(new FileReader(newFile)))
{
while ((line = reader.readLine()) != null)
{
int length = line.length();
String newLine = "";
for (int i = 1; i < length; i++)
{
int c = line.charAt(i);
if (c == line.charAt(i - 1))
{
}
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
});
So what I want to do is: I want to find all the words where two characters are equal, if they are aside (Like 'Took'). When the if statement is true, I want to replace the first letter of the two equals characters, so it would look like: 'T2ok'.
I've tried a lot of things and I get an ArrayOutOfbounds, StringOutOfbounds, and so on, all the time...
Hope someone has a great answer :-)
Regards
Create a method that compress one String as follows:
Loop throu every character using a while loop. Count the duplicates in another nested while loop that increments the current index while duplicates are found and skips them from being written to output. Additionally this counts their occurence.
public String compress(String input){
int length = input.length(); // length of input
int ix = 0; // actual index in input
char c; // actual read character
int ccounter; // occurrence counter of actual character
StringBuilder output = // the output
new StringBuilder(length);
// loop over every character in input
while(ix < length){
// read character at actual index then inc index
c = input.charAt(ix++);
// we count one occurrence of this character here
ccounter = 1;
// while not reached end of line and next character
// is the same as previously read
while(ix < length && input.charAt(ix) == c){
// inc index means skip this character
ix++;
// and inc character occurence counter
ccounter++;
}
// if more than one character occurence is counted
if(ccounter > 1){
// print the character count
output.append(ccounter);
}
// print the actual character
output.append(c);
}
// return the full compressed output
return output.toString();
}
Now you can use this method to create a file input to output stream using java8 techniques.
// create input stream that reads line by line, create output writer
try (Stream<String> input = Files.lines(Paths.get("input.txt"));
PrintWriter output = new PrintWriter("output.txt", "UTF-8")){
// compress each input stream line, and print to output
input.map(s -> compress(s)).forEachOrdered(output::println);
} catch (IOException e) {
e.printStackTrace();
}
If you really want to. You can remove the input file and rename the output file afterwards with
Files.move(Paths.get("output.txt"), Paths.get("input.txt"),StandardCopyOption.REPLACE_EXISTING);
I think this is the most efficient way to do what you want.
try this:
StringBuilder sb = new StringBuilder();
String line;
try(BufferedReader reader = new BufferedReader(new FileReader(newFile)))
{
while ((line = reader.readLine()) != null)
{
if (!line.isEmpty()) {
//clear states
boolean matchedPreviously = false;
char last = line.charAt(0);
sb.setLength(0);
sb.append(last);
for (int i = 1; i < line.length(); i++) {
char c = line.charAt(i);
if (!matchedPreviously && c == last) {
sb.setLength(sb.length()-1);
sb.append(2);
matchedPreviously = true;
} else matchedPreviously = false;
sb.append(last = c);
}
System.out.println(sb.toString());
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
This solution uses only a single loop, but can only find occurrences of length 2

Read in number file and calculate average in java

I have a txtfile called "averages" that looks like:
1 4 5 3 -1
2 8 9 3 2 -1
4 8 15 16 23 42 -1
3 -1
I want to be able to read in each line and calculate the average of each line whenever a "-1" is reached. I have written the code to read in the file and print it to the command line, I'm just having trouble finding the averages of each line. Any help would be greatly appreciated. Thanks!
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
BufferedReader reader = null;
try {
String currentLine;
reader = new BufferedReader(new FileReader("averages.txt"));
while ((currentLine = reader.readLine()) != null) {
System.out.println(currentLine);
}
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (reader != null)reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
You could do it by doing the following:
split the currentLine using split method:
String[] nums = currnetLine.split("\\s+");
loop over the nums and parse each elements to int then add it to a
sum variable
int sum = 0;
for (int i = 0; i < nums.length; i++) {
int num = Integer.parseInt(nums[i]);
if(num != -1) {
sum += num;
}
}
Finally calculate the average.
sum/(nums.length - 1);// -1 because you need to execlude the -1 at the end of your line
I'd try something like this:
int sum = 0;
String[] values = currentLine.split(" ");
for (String value : values) {
int n = Integer.parseInt(value);
if (n < 0) {
break;
}
sum += n;
}
int count = values.length - 1;
// calculate average from sum and count
In Java 7+, the Scanner object is available and has a variety of useful functions to use.
1.) First read in the line
Scanner scanner = new Scanner("1 51 2 52");
2.) From your code above, if you have a space delimiter, it is easy to work with
scanner.useDelimiter(" ");
3.) If scanner.hasNext() then scanner.next() for the next string.
Iterate the list using Integer.parseInt("1") to get the value, sum, then average.
Please try this:
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
BufferedReader reader = null;
try {
String currentLine;
reader = new BufferedReader(new FileReader("averages.txt"));
while ((currentLine = reader.readLine()) != null) {
System.out.println(currentLine);
StringTokenizer st=new StringTokenizer(currentLine," ");
int count=st.countTokens();
int array[]=new int[count-1];
int i=0;
while(st.hasMoreTokens()&&i!=count-1)
{
array[i]=Integer.valueOf(st.nextToken());
i=i+1;
}
int sum=0;
for(int x=0;x<array.length;x++)
{
sum=sum+array[x];
}
float average=(float)sum/array.length;
System.out.println("The average of this line is: "+average);
}
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (reader != null)reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
My logic is that you read a line at a time and separate them by spaces. Then you convert those separated string into Integer. Last step is add them up and do some math to get the average.
Hope this helps. Thanks!

How to find smallest value(from values given in a txt file) using BufferedReader in java

I have been given this question for practice and am kind of stuck on how to complete it. It basically asks us to create a program which uses a BufferedReader object to read values(55, 96, 88, 32) given in a txt file (say "s.txt") and then return the smallest value of the given values.
So far I have got two parts of the program but i'm not sure how to join them together.
import java.io.*;
class CalculateMin
{
public static void main(String[] args)
{
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
int numberOfLines = 5;
String[] textInfo = new String[numberOfLines];
for (int i = 0; i < numberOfLines; i++) {
textInfo[i] = br.readLine();
}
br.close();
} catch (IOException ie) {
}
}
}
and then I have the loop which I made but i'm not sure how to implement it into the program above. Eugh I know i'm complicating things.
int[] numArray;
numArray = new int[Integer.parseInt(br.readLine())];
int smallestSoFar = numArray[0];
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] < smallestSoFar) {
smallestSoFar = numArray[i];
}
}
Appreciate your help
Try this code, it iterates through the entire file comparing number from each line with the previously read lowest number-
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
String line;
int lowestNumber = Integer.MAX_VALUE;
int number;
while ((line = br.readLine()) != null) {
try {
number = Integer.parseInt(line);
lowestNumber = number < lowestNumber ? number : lowestNumber;
} catch (NumberFormatException ex) {
// print the error saying that the line does not contain a number
}
}
br.close();
System.out.println("Lowest number is " + lowestNumber);
} catch (IOException ie) {
// print the exception
}
}

reading line and splitting to char array

I can't understand why my program not functioning. It compiles but nothing is printed. I have a 5 character word in file. I need to read line from that file and then split it into char array, which I then want print out.Thanks!
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
public class test {
public static void main(String[] args)
{
BufferedReader line = null;
char[] array = new char[7];
try{
line = new BufferedReader(new FileReader(args[0]));
String currentLine;
while((currentLine = line.readLine()) != null)
{
array = currentLine.toCharArray();
}
for(int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
}
}//try
catch(IOException exception)
{
System.err.println(exception);
}//catch
finally
{
try
{
if(line != null)
line.close();
}//try
catch(IOException exception)
{
System.err.println("error!" + exception);
}//catch
}//finally
} // main
} // test
Your while loop skips every line except the last one so it could be possible that your last line is empty. To display every line you could have:
while ((currentLine = line.readLine()) != null) {
array = currentLine.toCharArray();
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println();
}
Or if you just have the 1 line, You could simply use:
String currentLine = line.readLine();
...
Your program prints only last line
You have to Print in loop.
while (....!=null)
{
array = currentLine.toCharArray();
for(int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
}
}
If above was not a problem than check your file permission.
Check your system may be program is not able to read from file due to permission on file.

Categories

Resources