Reading String from the File - java

What am I doing wrong in the code by reading String.
Suppose the following String is passed as a layout:
String m = "..z\n"+
"...\n"+
"...\n"+
"...\n"+
"z..\n"+
"";
My method should return the same result but it's not returning me anything, it does not pring anything. Please do not suggest using StringBuilder or smth similar. Can smb please help me out with this?
public static Shape makeShape(String layout,char displayChar)
{
Shape result;
int height = 0;
int width = 0;
Scanner data = new Scanner(layout);
char[][] temp;
while(data.hasNextLine())
{
String line = data.nextLine();
height = line.length();
width++;
}
temp = new char[height][width];
Scanner data2 = new Scanner(layout);
while(data.hasNextLine())
{
String line2 = data.nextLine();
if(line2.charAt(0) == '.' && line2.charAt(width) == '.')
throw new FitItException("Empty borders!");
else {
for (int r = 0; r < height; r++)
for (int c = 0; c < width; c++) {
//System.out.println(line2.charAt(c));
if (temp[r][c] == '.') {
temp[r][c] = displayChar;
}
System.out.println(line2.charAt(temp[r][c]));
}
}
}
result = new CreateShape(height, width, displayChar);
return result;
}

Hint: look carefully at these two lines:
Scanner data2 = new Scanner(layout);
while(data.hasNextLine())
Do you see something wrong with ... the ... variable ... names ... ?

Given the code and string above width would be 5 or 6. No line is more than 3 so line2.charAt(width) would throw an exception?

Related

Boolean 2d array text file

I need to read a series of # and blank spaces from a text file and print it as a maze.
public static void readMaze() throws FileNotFoundException{
String fileName = "path/maze.txt";
Scanner input = new Scanner(new File(fileName));
int x = 0;
String columns = "";
while (input.hasNextLine()){
x++;
columns = input.nextLine();
}
int col = columns.length();
boolean maze[][] = new boolean[x][col];
}
So I have got the number of rows(x) and the number of columns which the maze will have.
Next step is to create a boolean array with a true value for each "#" and false for each blank space in the file and I am not sure how to do this.
while (input.hasNextLine()){
columns = input.nextLine();
for (int c = 0; c < columns.length();c++){
if (c == '#'){
add true;
}
else{
add false;
}
}
}
So that is the next part, but I am not sure wht I need to put in the for loop, guidance would be appreciated.
The only missing part of your puzzle is this
int row = 0;
while (input.hasNextLine()){
columns = input.nextLine();
for (int c = 0; c < columns.length();c++){
c = columns.charAt(c);
if (c == '#'){
result[row, c] = true;
}
else{
result[row, c] = false; // not even needed, false is the default value ;)
}
row ++;
}
Should be better with something like :
ArrayList<Boolean> returnArray = new ArrayList<Boolean>()
for (int c = 0; c < columns.length();c++){
if (columns[c].equals("#")){
returnArray.add(true);
}
else{
returnArray.add(false);
}
}
return returnArray.hasArray();
int i = 0;
while(input.hasNextLine())
{
row = input.nextLine();
String[] row_temp = row.split("(?!^)");
int row_length = row_temp.length();
for(int j=0; j<row_length; j++){
if(row_temp[j].matches("#")){
maze[i][j] = true;
}
else{
maze[i][j] = false;
}
}
i++;
}

Throw Exception when the String shape is illegal

Im doing something wrong with the Excetpion in my code because when a String layout such as:
..b.
bbb. //<---Illegal
...
.x.
... //<---Illegal
..r
.rr //<---Illegal
.....
.y...
..y..
...y. //<---Illegal
is passed into the method (only one layout can be passed at one time), the method should throw an exception because String layouts for shapes must have at least one filled block in each of 0th row, 0th column, last row, and last column. The following String layouts are legal:
...e
..e.
e...
a...a
.....
.....
a....
My code only handles Exception when it sees the first and last charcters of the first line. Can smb please help me out with this method regarding throwing Exception? Thanks in advance!
public static Shape makeShape(String layout,char displayChar)
{
Shape result;
int height = 0;
int width = 0;
Scanner data = new Scanner(layout);
char[][] temp;
while(data.hasNextLine())
{
String line = data.nextLine();
height = line.length();
width++;
}
temp = new char[height][width];
Scanner data2 = new Scanner(layout);
while(data2.hasNextLine())
{
String line2 = data2.nextLine();
if(line2.charAt(0) == '.' && line2.charAt(width) == '.')
throw new FitItException("Empty borders!");
else {
for (int r = 0; r < height; r++)
for (int c = 0; c < width; c++) {
// System.out.println(line2.charAt(c));
if (temp[r][c] == '.') {
temp[r][c] = displayChar;
}
System.out.println(line2.charAt(temp[r][c]));
}
}
}
result = new CreateShape(height, width, displayChar, layout);
return result;
}
There are a couple of things not clear to me still, so I concentrated on parsing the layout into a two dimensional char array and checking for the constraints you specified. Hopefully that will let you adapt it to your exact needs:
public static char[][] parseShape(String layout, char displayChar) throws Exception {
int height = 0;
Scanner data = new Scanner(layout);
ArrayList<String> lines = new ArrayList<String>();
// parse layout into an array of lines to determine dimensions
while (data.hasNextLine()) {
String line = data.nextLine();
lines.add(line);
height = line.length();
}
int width = lines.size();
char[][] temp = new char[height][width];
Boolean row0 = false;
Boolean col0 = false;
Boolean rowLast = false;
Boolean colLast = false;
// parse array of lines in char array and check for constraints
for (int w = 0; w < width; w++) {
String line = lines.get(w);
for (int h = 0; h < height; h++) {
char c = line.charAt(h);
if (c == displayChar) {
// we are looking at the display characters,
// check if we're in any of rows of columns that matter
if (h == 0)
row0 = true;
if (w == 0)
col0 = true;
if (h == height - 1)
rowLast = true;
if (w == width - 1)
colLast = true;
}
temp[h][w] = c;
}
}
// if any of the constraints are not true, the layout is invalid
if(!row0) {
throw new Exception("no block in Oth row");
}
if(!col0) {
throw new Exception("no block in Oth column");
}
if(!rowLast) {
throw new Exception("no block in last row");
}
if(!colLast) {
throw new Exception("no block in last column");
}
return temp;
}
Basically we have to parse the entire layout and accumulate the constraints that are satisfied rather than checking for non-satisfaction. Only at the end will we know if they are not all satisfied.
A simpler approach might be to use regular expressions.
Your requirements can be expressed as:
at least one line must start with a non-.
at least one line must end with a non-.
the first line must contain at least one non-.
the last line must contain at least one non-.
The patterns for these can be written as:
private static final LINE_STARTS_WITH_NON_DOT =
Pattern.compile("^[^.]", Pattern.MULTILINE);
private static final LINE_ENDS_WITH_NON_DOT =
Pattern.compile("[^.]$", Pattern.MULTILINE);
private static final FIRST_LINE_CONTAINS_NON_DOT =
Pattern.compile("^\\.*[^.]");
private static final LAST_LINE_CONTAINS_NON_DOT =
Pattern.compile("[^.]\\.*$");
To ensure that each pattern matches layout, you can write:
if (!LINE_STARTS_WITH_NON_DOT.matcher(layout).find()
|| !LINE_ENDS_WITH_NON_DOT.matcher(layout).find()
|| !FIRST_LINE_CONTAINS_NON_DOT.matcher(layout).find()
|| !LAST_LINE_CONTAINS_NON_DOT.matcher(layout).find()) {
throw new FitItException("Empty borders!");
}
(Note: the above assumes that layout does not end with a newline. If it does end with a newline, then you'll need to change LINE_ENDS_WITH_NON_DOT to Pattern.compile("[^.]\n") and LAST_LINE_CONTAINS_NON_DOT to Pattern.compile("[^.]\\.*\n$").)

Count all characters in a file including \n etc

I am trying to iterate through a txt file and count all characters. This includes \n new line characters and anything else. I can only read through the file once. I am also recording letter frequency, amount of lines, amount of words, and etc. I can't quite figure out where to count the total amount of characters. (see code below) I know I need to before I use the StringTokenizer. (I have to use this by the way). I have tried multiple ways, but just can't quite figure it out. Any help would be appreciated. Thanks in advance. Note* my variable numChars is only counting alpha characters(a,b,c etc) edit posting class variables to make more sense of the code
private final int NUMCHARS = 26;
private int[] characters = new int[NUMCHARS];
private final int WORDLENGTH = 23;
private int[] wordLengthCount = new int[WORDLENGTH];
private int numChars = 0;
private int numWords = 0;
private int numLines = 0;
private int numTotalChars = 0;
DecimalFormat df = new DecimalFormat("#.##");
public void countLetters(Scanner scan) {
char current;
//int word;
String token1;
while (scan.hasNext()) {
String line = scan.nextLine().toLowerCase();
numLines++;
StringTokenizer token = new StringTokenizer(line,
" , .;:'\"&!?-_\n\t12345678910[]{}()##$%^*/+-");
for (int w = 0; w < token.countTokens(); w++) {
numWords++;
}
while (token.hasMoreTokens()) {
token1 = token.nextToken();
if (token1.length() >= wordLengthCount.length) {
wordLengthCount[wordLengthCount.length - 1]++;
} else {
wordLengthCount[token1.length() - 1]++;
}
}
for (int ch = 0; ch < line.length(); ch++) {
current = line.charAt(ch);
if (current >= 'a' && current <= 'z') {
characters[current - 'a']++;
numChars++;
}
}
}
}
Use string.toCharArray(), something like:
while (scan.hasNext()) {
String line = scan.nextLine();
numberchars += line.toCharArray().length;
// ...
}
An Alternative would be to use directly the string.length:
while (scan.hasNext()) {
String line = scan.nextLine();
numberchars += line.length;
// ...
}
Using the BfferedReader you can do it like this:
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file), charsetName));
int charCount = 0;
while (reader.read() > -1) {
charCount++;
}
I would read by char from file with BufferedReader and use Guava Multiset to count chars
BufferedReader rdr = Files.newBufferedReader(path, charSet);
HashMultiset < Character > ms = HashMultiset.create();
for (int c;
(c = rdr.read()) != -1;) {
ms.add((char) c);
}
for (Multiset.Entry < Character > e: ms.entrySet()) {
char c = e.getElement();
int n = e.getCount();
}

Morse code translator help reading from file

Okay so I know there are other Morse code answers out there, but I have looked at many, but none of them worked. For my assignment I was to read a file, Morse.txt, into parallel arrays. Instead I just made two files, Morse.txt and Alphabet.txt one with code and the other with numbers and alphabet. I am supposed to use a class I made to do the translating part and when called in main it should translate user input. I can't seem to get this working. I've tried so many things from using a toString in the class or getter, but the return is not found when I put in the loop which I think has to be there(if that makes sense)..anyway here is my code for main:
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class redo
{
public static void main(String[]args) throws IOException
{
String line2, file2 = "Morse.txt";
String line, file = "Alphabet.txt";
File openFile = new File(file);
File openFile2 = new File(file2);
Scanner inFile = new Scanner(openFile);
Scanner inFile2 = new Scanner(openFile2);
int index = 36;
char[] charArray = new char[index];
String[] code = new String[index];
for(index = 0; index < 36; index++)
{
while(inFile.hasNext())
{
line = inFile.nextLine();
charArray = line.toCharArray();
//System.out.println(charArray[index]);
}
}
for(index = 0; index < 36; index++)
{
while(inFile2.hasNext())
{
code[index] = inFile2.nextLine();
//System.out.println(code[index]);
}
}
Scanner keyboard = new Scanner(System.in);
String userInput;
System.out.println("Enter something to translate: ");
userInput= keyboard.nextLine();
Translate inputTranslate = new Translate(userInput);
inputTranslate.setInput(userInput);
inputTranslate.setAlph(charArray);
inputTranslate.setCode(code);
inFile.close();
}
}
and here is my class Translate(some things are commented out):
public class Translate
{
String input;
String code[];
char alph[];
public Translate(String input)
{
this.input = input;
}
public void setInput(String input)
{
this.input = input;
}
public void setAlph(char[] alph)
{
this.alph = alph;
}
public void setCode(String[] code)
{
this.code = code;
}
public String getInput()
{
return input;
}
// public String getTranslate()
// {
// for(int i = 0; i < input.length(); i++)
// {
// for(int index = 0; index < alph.length; index++)
// {
// if(input.charAt(i) == alph[index])
// {
// String output = code[index];
// }
// }
// }
// return output;
// }
}
Morse.txt:
.----
..---
...--
....-
.....
-....
--...
---..
----.
.-
-...
-.-.
-..
.
..-.
--.
....
..
.---
-.-
.-..
-.
.--.
--.-
.-.
...
..-
...-
.--
-..-
-.--
--..
Alphabet.txt:
1
2
3
4
5
6
7
8
9
0
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
The problem is your return can't reach "output", you need to declare "output" above the loops and initialise it to output = null;
Even then it'll only send one string. So I did this;
public String getTranslate()
{
String output = null;
String[] translated = new String[input.length()];
for(int i = 0; i < input.length(); i++)
{
for(int index = 0; index < alph.length; index++)
{
if(input.charAt(i) == alph[index])
{
output = code[index];
translated[i] = output;
}
}
}
for (int j = 1; j < translated.length; j++) {
output = translated[0].concat(translated[j]);
}
return output;
}
This basically sticks all the codes together giving you your desired outcome.

Java Read Each Line Into Separate Array

I have 1,000 lines of data in a text file and I would like each line to be its own float [].
1,1,1,1,1,1
2,2,2,2,2,2
3,3,3,3,3,3
Would result in:
float[0] = {1,1,1,1,1,1}
float[1] = {2,2,2,2,2,2}
float[2] = {3,3,3,3,3,3}
Is this possible? I could only find examples of loading an entire file into an array. I tried hardcoding all the arrays, but exceeded the byte character limit of ~65,000
Try the following:
// this list will store all the created arrays
List<float[]> arrays = new ArrayList<float[]>();
// use a BufferedReader to get the handy readLine() function
BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"));
// this reads in all the lines. If you only want the first thousand, just
// replace these loop conditions with a regular counter variable
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
String[] floatStrings = line.split(",");
float[] floats = new float[floatStrings.length];
for (int i = 0; i < floats.length; ++i) {
floats[i] = Float.parseFloat(floatStrings[i]);
}
arrays.add(floats);
}
Note that I haven't added any exception handling (readLine(), for example, throws IOException).
use a LineIterator to read each line without loading the whole file
for each line, use a regular expression to extract figures like (\d\.)+ and iterator over the matches found with methods like find() and group()
<body>
<pre>
import java.io.FileReader;
public class Check {
public static void main(String[] args) {
readingfile();
}
public static void readingfile() {
try {
FileReader read = new FileReader("D:\\JavaWkspace\\numbers.txt");
int index;
String nums1 = "";
while ((index = read.read()) != -1) {
if (((char) index) != '\n') {
nums1 += String.valueOf((char) index);
}
}
System.out.println("Problem statement: Print out the greatest number on each line:\n" + nums1);
String f = nums1.substring(0, 14);
String s = nums1.substring(15, 29);
String t = nums1.substring(30);
String[] fs = f.split(",");
int size = fs.length;
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = Integer.parseInt(fs[i]);
}
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
}
}
System.out.println("\nGreatest number in the first line is:" + (max));
String[] sstr = s.split(",");
int size2 = sstr.length;
int[] arr2 = new int[size2];
for (int i = 0; i < size2; i++) {
arr2[i] = Integer.parseInt(sstr[i]);
}
int max2 = arr2[0];
for (int i = 0; i < arr2.length; i++) {
if (max2 < arr2[i]) {
max2 = arr2[i];
}
}
System.out.println("\nGreatest number in the second line is:" + (max2));
String[] str3 = t.split(",");
int size3 = str3.length;
int[] arr3 = new int[size3];
for (int i = 0; i < size3; i++) {
arr3[i] = Integer.parseInt(str3[i]);
}
int max3 = arr3[0];
for (int i = 0; i < arr3.length; i++) {
if (max3 < arr3[i]) {
max3 = arr3[i];
}
}
System.out.println("\nGreatest number in the third line is:" + (max3));
read.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
</pre>
</body>
Loop over the line-delimited contents of the file with .split("\n") and then cast each result as float array. Here's how to convert the string into a float for you => http://www.devdaily.com/java/edu/qanda/pjqa00013.shtml

Categories

Resources