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
Related
This code takes two txt files, reads them puts them in 2d arrays and should check if the numbers in the files are magic squares but it keeps returning NumberFormatException error. I'm new to java so if anyone could help me that would be great. I'm pretty sure the problem come from the txt file being string and the 2d array needing to be in int form. But how and where do I make that conversion on my code?
this is what i have:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ms {
public static void main(String[] args) throws FileNotFoundException {
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
int nos[][] = null;
nos = getArray(filename1);
boolean b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
System.out.println("\n");
nos = getArray(filename2);
b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
}
private static int[][] getArray(String filename) throws FileNotFoundException {
String line;
int nos[][] = null;
int size = 0, rows = 0;
Scanner sc = null;
try {
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
if (!sc.nextLine().isEmpty())
size++;
}
sc.close();
nos = new int[size][size];
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
line = sc.nextLine();
if (!line.isEmpty()) {
String arr[] = line.split("\t");
for (int i = 0; i < arr.length; i++) {
nos[rows][i] = Integer.valueOf(arr[i]);
}
rows++;
}
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println(e);
}
return nos;
}
private static void printArray(int[][] nos){
for(int i = 0; i<nos[0].length;i++) {
for (int j = 0; j < nos[0].length; j++){
System.out.printf("%-3d",nos[i][j]);
}
System.out.println();
}
}
private static boolean isMagicSquare(int[][] square) {
boolean bool = true;
int order = square.length;
int[] sumRow = new int[order];
int[] sumCol = new int[order];
int[] sumDiag = new int[2];
Arrays.fill(sumRow, 0);
Arrays.fill(sumCol, 0);
Arrays.fill(sumDiag, 0);
for (int row = 0; row < order; row++){
for (int col = 0; col < order; col++) {
sumRow[row] += square[row][col];
}
}
for (int col = 0; col < order; col++) {
for (int row = 0; row < order; row++) {
sumCol[col] += square[row][col];
}
}
for (int row = 0; row < order; row++) {
sumDiag[0] += square[row][row];
}
for (int row = 0; row < order; row++) {
sumDiag[1] += square[row][order - 1 - row];
}
bool = true;
int sum = sumRow[0];
for (int i = 1; i < order; i++) {
bool = bool && (sum == sumRow[i]);
}
for (int i = 0; i < order; i++) {
bool = bool && (sum == sumCol[i]);
}
for (int i = 0; i < 2; i++) {
bool = bool && (sum == sumDiag[i]);
}
return bool;
}
}
SUGGESTION:
Substitute nos[rows][i] = Integer.valueOf(arr[i]); for a custom method that will tell you WHERE the error is occurring.
EXAMPLE:
public static Integer tryParse(String text, int row, int i) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
System.out.println("ERROR: row=" + row + ", i=" + i + ", text=" + text);
return null;
}
}
CAVEAT: This is for helping you troubleshoot ONLY. You definitely wouldn't want to release this in "production code" ;)
What is the NumberFormatException?
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Offtopic:
A thing that i can notice is that both filesnames have the same name. So you will verify the same file 2 times.
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
I checked your program and you error appears when you put like this on a file:
1. 5 5
2. 5 5
So the error shows beacause you are trying to parse to int the String "5 5". So your code pick the all line and tries to convert to int and " " it's not an int. And there lives the NumberFormatException error.
How do to solve it?
The function that we will work on is the one that you pass from file to an array in
private static int[][] getArray(String filename) throws FileNotFoundException{
The of the function is after we read the file.
As you said, you are leading with a 2d array so to insert all the numbers we need to have loops for each dimension on the array.
So we will start from there.
I will use a while beacause we are dealing with a string and it's easier to verify the text that its left on the line. Will add a new int variable that starts in 0 to pass in every column of a line to use with the while loop. And with this we got this:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
whileIterator++;
}
whileIterator = 0;
}
Next setep, we will divide in 2 behaviors because we will substring the String that has in the line, and will work differently when it's the last number that we are verifying:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need in a line
}else{//All other iterations
whileIterator++;
}
whileIterator = 0;}
To finalize let's add the new logic to insert in nos array. So lets pick all line for example 2 7 6 and we want to add the number 2, so lets do that. You just need to substring(int startIndex, int finalIndex) the line and add to the nos array. After that let remove the number and the space ("2 ") from the line that we are veryfying.
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need
nos[rows][whileIterator] = Integer.parseInt(line.substring(0));//Add to array
line = "";//To not pass the while verification
}else{//All other iterations
nos[rows][whileIterator] = Integer.parseInt(line.substring(0, line.indexOf(" ")));//Add to array
line = line.substring(line.indexOf(" ") + 1);//remove the number we added behind
}
whileIterator++;
}
whileIterator = 0;}
And here you go, that how you add the numbers to an array and don't get the error.
If you need some further explanation just ask. Hope it helps :)
I am trying to separate a text in k-shingles, sadly I cannot use scanner. If the last shingle is too short, I want to fill up with "_". I came this far:
public class Projektarbeit {
public static void main(String[] args) {
testKShingling(7, "ddssggeezzfff");
}
public static void testKShingling(int k, String source) {
//first eliminate whitespace and then fill up with withespaces to match target.length%shingle.length() == 0
String txt = source.replaceAll("\\s", "");
//get shingles
ArrayList<String> shingles = new ArrayList<String>();
int i;
int l = txt.length();
String shingle = "";
if (k == 1) {
for(i = 0; i < l; i++){
shingle = txt.substring(i, i + k);
shingles.add(shingle);
};
}
else {
for(i = 0; i < l; i += k - 1){
try {
shingle = txt.substring(i, i + k);
shingles.add(shingle);
}
catch(Exception e) {
txt = txt.concat("_");
i -= k - 1;
};
};
}
System.out.println(shingles);
}
}
Output: [ddssgge, eezzfff, f______]
It works almost, but in the with the given parameters in the example the last shingle is not necessary (it should be [ddssgge, eezzfff]
Any idea how to do this more beautiful?
To make the code posted work you only need to add break and the end of the catch block:
catch(Exception e) {
txt = txt.concat("_");
i -= k - 1;
break;
};
Having said that I wouldn't use an Exception to control the program. Exception are just that: should be used for run time errors.
Avoid StringIndexOutOfBoundsException by controlling the loop parameters:
public static void main(String[] args) {
testKShingling(3, "ddssggeezzfff");
}
public static void testKShingling(int substringLength, String source) {
//todo validate input
String txt = source.replaceAll("\\s", "");
//get shingles
ArrayList<String> shingles = new ArrayList<>();
int stringLength = txt.length();
if (substringLength == 1) {
for(int index = 0; index < stringLength; index++){
String shingle = txt.substring(index, index + substringLength);
shingles.add(shingle);
};
}
else {
for(int index = 0; index < stringLength -1 ; index += substringLength - 1){
int endIndex = Math.min(index + substringLength, stringLength);
String shingle = txt.substring(index, endIndex);
if(shingle.length() < substringLength){
shingle = extend(shingle, substringLength);
}
shingles.add(shingle);
};
}
System.out.println(shingles);
}
private static String extend(String shingle, int toLength) {
String s = shingle;
for(int index = 0; index < toLength - shingle.length(); index ++){
s = s.concat("_");
}
return s;
}
An alternative implementation of testKShingling:
public static void testKShingling(int substringLength, String source) {
//todo validate input
String txt = source.replaceAll("\\s", "");
ArrayList<String> shingles = new ArrayList<>();
if (substringLength == 1) {
for(char c : txt.toCharArray()){
shingles.add(Character.toString(c));
};
}
else {
while(txt.length() > substringLength) {
String shingle = txt.substring(0, substringLength);
shingles.add(shingle);
txt = txt.substring(substringLength - 1); //remove first substringLength - 1 chars
}
if(txt.length() < substringLength){ //check the length of what's left
txt = extend(txt, substringLength);
}
shingles.add(txt); //add what's left
}
System.out.println(shingles);
}
I'm trying to solve a palindrome problem that the input consists of Strings , if the concatenation of two strings represent a palindrome word(A palindrome is a word which can be read the same way in either direction. For example, the following
words are palindromes: civic, radar, rotor, and madam)
then save it into array to print it latter otherwise print "0"
but I'm having a problem in filling the null index with zeros , here I get Exception
for (int re = 0; re < result.length; re++) {
if (result[re].equals(null)) {
result[re] = "0";
}
}
"Exception in thread "main" java.lang.NullPointerException"
here is my full code
import java.util.Scanner;
public class Palindrome {
public static String reverse(String R2) {
String Reverse = "";
String word_two = R2;
int ln = word_two.length();
for (int i = ln - 1; i >= 0; i--) {
Reverse = Reverse + word_two.charAt(i);
}
return Reverse;
}
public static void main(String[] args) {
Scanner inpoot = new Scanner(System.in);
int stop = 0;
String pal1;
int Case = inpoot.nextInt();
String result[] = new String[Case];
String Final;
int NumberofWords;
for (int i = 0; i < Case; i++) {
NumberofWords = inpoot.nextInt();
String words[] = new String[NumberofWords];
for (int array = 0; array < words.length; array++) {
words[array] = inpoot.next();
}
for (int word1 = 0; word1 < NumberofWords; word1++) {
if (stop > Case) {
break;
}
for (int word2 = 0; word2 < NumberofWords; word2++) {
if (word1 == word2) {
continue;
}
Final = "" + words[word1].charAt(0);
if (words[word2].endsWith(Final)) {
pal1 = words[word1].concat(words[word2]);
} else {
continue;
}
if (pal1.equals(reverse(pal1))) {
result[i] = pal1;
stop++;
break;
} else {
pal1 = "";
}
}
}
}
// HERE IS THE PROBLEM
for (int re = 0; re < result.length; re++) {
if (result[re].equals(null)) {
result[re] = "0";
}
}
for (int x = 0; x < result.length; x++) {
System.out.println("" + result[x]);
}
}
}
A test such as anObject.equals(null) makes no sense. Indeed, if anObject is null, it will throw a NullPointerException (NPE), and if it is not, it will always return false.
To test if a reference is null, just use anObject == null.
If you want to check whether result[re] is null, you cannot use equals. Use the identity comparison:
if (result[re] == null) {
result[re] = "0";
}
Assume there is only one null in an array. I am trying to move it right to the end using a for loop. this is what i tried.
String example[] = new String[5];
example[0] = "a";
example[1] = null;
example[2] = "c";
example[3] = "d";
example[4] = "e";
I want the output to be : a,c,d,e,null. I want to able to move the null to the end regardless of its index using a FOR loop.
This is what i tried
String asd[] = new String[creatureList.length];
for (int i = 0 ; i < creatureList.length; i++) {
if (creatureList[i] != null){
asd[i] = creatureList[i];
}
creatureList = asd;
Just search for the null element and if found, shift all elements 1 position to the left. This code works even if there are more than 1 null elements in the array.
public class Test10 {
public static void main(String[] args) {
String example[] = new String[5];
example[0] = "a";
example[1] = null;
example[2] = "c";
example[3] = "d";
example[4] = "e";
for (int j=0; j<example.length; j++){
if (example[j]==null){
for (int k=j+1; k<example.length; k++){
example[k-1] = example[k];
}
example[example.length-1] = null;
break;
}
}
for (int j=0; j<example.length; j++){
System.out.println(example[j]);
}
}
}
You can just use the principle of bubble sort in here.
Try this
String example[] = new String[5];
example[0] = "a";
example[1] = null;
example[2] = "c";
example[3] = "d";
example[4] = "e";
for(int i=0; i < example.length - 1; ++i) {
if(example[i] == null) {
example[i] = example[i+1];
example[i+1] = null;
}
}
for(String s : example)
System.out.print(s + " ");
If you only need to print the values that way, try this
for(String s : example)
if(s != null)
System.out.print(s + " ");
System.out.print(null + " ");
A possible solution without creating a new Array would be to move the elements.
Example, assuming that example is an Array:
boolean found = false;
for(int i = 0; i < example.length; i++) {
if(found)
example[i-1] = example[i];
if(example[i] == null)
found = true;
if(i == example.length - 1 && found)
example[i] = null;
}
I want to add that this would be a lot easier if you would use Collections (for example an ArrayList), I highly recommend using them instead of Arrays if performance is not a huge factor.
I'd have a different implementation for ArrayLists (as .remove() is handy), but here we are with a bounded array:
for(int n = 0; n < array.length; n++) {
if(null == array[n]) {
// to avoid issues with references, unsure if necessary
String s = array[n + 1];
array[n] = array[s];
array[n + 1] = null;
}
}
Here's a solution that is based on your assumption that there's only one null:
for (int i=1; i<example.length; i++) {
if (example[i-1] == null) {
example[i-1] = example[i];
example[i] = null;
}
}
I think the answers before me were not correct, so here is a code that works and puts all the nulls at the end of a array.
public static void moveNullToTheEnd( Object[] arr )
{
Object[] temp = new Object[arr.length];
int counter = 0;
int nullcounter = arr.length-1;
for(int i= 0; i < arr.length; i++) {
if(arr[i] == null){
temp[nullcounter] = null;
nullcounter--;
}
else {
temp[counter] = arr[i];
counter++;
}
}
arr = temp;
System.out.println(Arrays.toString(arr));
}
public static void main (String[] args)
{
Object [] test = new Object[] {1, 2, null, null, 4};
moveNullToTheEnd(test);
}
I have array
data[][];
convert to string:
string = Arrays.deepToString(data);
string:
[[1, 1394119227787, 59474093, USD/DKK, true, 0.05, 5.391582, 5.00663, 5.39663, null, null], [1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null],
[1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null],
[1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null]]
and How convert this string back to array?
Try my stringToDeep() method to convert back to Array.
import java.util.*;
public class DeepToArray {
public static void main(String[] args) {
int row, col;
row = 2;
col = 3;
String[][] in = new String[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
in[i][j] = i + " " + j;
}
}
String str = Arrays.deepToString(in);
System.out.println(str);
String[][] out = stringToDeep(str);
for (String s2[] : out) {
for (String s3 : s2) {
System.out.print(s3 + " ");
}
System.out.println();
}
}
private static String[][] stringToDeep(String str) {
int row = 0;
int col = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '[') {
row++;
}
}
row--;
for (int i = 0;; i++) {
if (str.charAt(i) == ',') {
col++;
}
if (str.charAt(i) == ']') {
break;
}
}
col++;
String[][] out = new String[row][col];
str = str.replaceAll("\\[", "").replaceAll("\\]", "");
String[] s1 = str.split(", ");
int j = -1;
for (int i = 0; i < s1.length; i++) {
if (i % col == 0) {
j++;
}
out[j][i % col] = s1[i];
//System.out.println(s1[i] + "\t" + j + "\t" + i % col);
}
return out;
}
}
There is no method in the java API that will automatically convert this back to an array. You could write code to do this yourself, but it would be tricky; this format does not escape special characters like the square brackets, or the commas. It might be easier just to use a format which is designed for encoding and decoding arrays, like JSON.
All the answers I found are 2-dimensional only, so here's my solution to reverse deepToString(...) for any number of dimensions:
Usage example:
String arrString = "[[[0.11695497071135137, 0.8830064157596283, 0.3433854446148375, 0.18825445694298526, 1.0441938749175883, 0.8941633746325311], [-0.089908138214512, 0.39821330927870574, 0.1365997500579524, 0.7008902956765364, 0.9897596683277262, 0.2847717055995359], [0.6450670283688857, 0.01516064860567864, -0.07904927386204857, 0.2703900981351612, 0.45402985012492075, 0.30505608337251183], [0.5122943117220898, 0.008726346575469023, 0.7734611917871235, 0.3051772999891666, 0.5237487372571624, 1.1824105144656751]]]";
String[][][] arr = (String[][][]) reverseDeepToString(arrString);
System.out.println(Arrays.deepToString(arr));
This code converts a string (arrString) into an array, and then the function Arrays.deepToString(...) converts it back into the same string.
Function code:
public static Object reverseDeepToString(String str){
int dimensions = 0;
for(int x = 0; x < str.length(); x++)
if(str.charAt(x) == '[')
dimensions++;
else break;
str = str.substring(dimensions, str.length() - dimensions);
return createArrayRecursive(str, dimensions);
}
private static Object createArrayRecursive(String str, int dimension){
if(dimension == 1)
return str.split(", "); // modify the code here if you want to convert the strings to another variable type
String[] s = str.split(getArraySeparator(dimension));
int[] lengths = new int[dimension];
lengths[0] = s.length;
Object arr = Array.newInstance(String.class, lengths); // and here (see comment above)
for(int x = 0; x < s.length; x++)
Array.set(arr, x, createArrayRecursive(s[x], dimension - 1));
return arr;
}
private static String getArraySeparator(int dimension){
String separator = ", ";
for(int x = 1; x < dimension; x++)
separator = ']' + separator + "\\[";
return separator;
}
Array to string and back to array :P
import java.util.Arrays;
import java.util.Random;
public class arrays {
public static void main(String [ ] args)
{
String[][] in = new String [10][4];
String[][] out = new String [10][4];
arrays nr = new arrays();
for(int i =0; i< 4; i++){
for(int j =0; j< 4; j++){
in[i][j] = nr.Rand(5);
}
}
System.out.println(Arrays.deepToString(in));
// tablica ok
// convert array to string
String line = "";
for(int i =0; i< 4; i++){
for(int j =0; j< 4; j++){
line += in[i][j] + "_";
}
line += ":";
}
System.out.println(line);
// line back to array
String[] xline = line.split(":");
int ss = 0;
for (String str : xline) {
out[ss] = (String[]) str.split("_");
System.out.println("string line>>>" + str);
ss++;
}
System.out.println(Arrays.deepToString(out));
}
public String nextSessionId() {
//private SecureRandom random = new SecureRandom();
//return new BigInteger(130, random).toString(32);
return null;
}
public String Rand(int zz){
char[] chars = "987654321abcdefghijklm111nopqrstuvwxyz0123456789".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < zz; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
// System.out.println(output);
return output;
}
}
:D