Is it possible to save a character which was deleted with the Stringbuffer or delete all character except one on 'i' index
This is my input from a txt file:
3;8;4;5;3;2
3 4 5 1 2 3
9;8;3;2;3;4
9 8 9 7 8 1
I need to sum up each line and see in which one is most of even numbers, so i decided to read a whole line, separate characters with a space then with help of string builder delete all characters except one on 'i' position and finally save in two dimentional array.
Maybe you'll have some better idea how to do it?
My code:
package Operacje_na_plikach;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Zad3 {
/*
Plik tekstowy ‘dane.txt’ ma postać:
3;8;4;5;3;2
3 4 5 1 2 3
9;8;3;2;3;4
9 8 9 7 8 1
Pobierz z pliku tekstowego kolejne wiersze liczb i wypisz na ekranie numer wiersza, w którym występuje najwięcej elementów parzystych.
*/
public static String[][] odczyt(String nazwa)
{
String[][] arr = new String[1][1];
int[] suma = new int[1];
int max = -1;
int wiersz=-1;
String text = null;
try {
FileReader reader = new FileReader(nazwa);
Scanner sc = new Scanner(reader);
while(sc.hasNextLine())
{
arr=Arrays.copyOf(arr,arr.length+1);
text = sc.nextLine().replaceAll(";"," ");
int[] temp= new int[text.length()];
StringBuilder sb = new StringBuilder(text);
for (int i = 0; i <temp.length ; i++) {
temp[i]=sb.delete();
}
for (int i = 0; i < ; i++) {
for (int j = 0; j < ; j++) {
arr[i][j] = text
}
}
}
/* while (sc.hasNextLine())
{
arr=Arrays.copyOf(arr,arr.length+1);
text = sc.nextLine().replaceAll("[;]"," ");
for (int i = 0; i <arr.length ; i++) {
while(text!=null)
{
int temp = Integer.parseInt(text);
}
for (int j = 0; j <arr.length ; j++) {
arr[i][j] = text.nextInt();
if(arr[i][j]%2==0)
{
suma[i]+=arr[i][j];
if(suma[i]>max)
{
max = suma[i];
wiersz=i;
}
}
}
}
}
System.out.println("Najwiecej liczb parzystych jest w wierszu: " + wiersz);
*/
sc.close();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return arr;
}
public static void main(String[] args) {
int[][] arr = odczyt("dane.txt");
}
}
I think you may be over-complicating things. You could stream the lines of the file, parse them, and map them to the sum of the even numbers. You can then go over the array of sums and find the index of the largest element (which can also be done with streams, just for the fun of it):
long[] sums =
Files.lines(Paths.get("dane.txt"))
.mapToLong(s -> Arrays.stream(s.split("[ ;]"))
.mapToInt(Integer::parseInt)
.filter(i -> i % 2 == 0)
.sum())
.toArray();
int lineNum =
IntStream.range(0, sums.length)
.boxed()
.max(Comparator.comparingLong(i -> sums[i]))
.get();
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 :)
Why does this binary search code give wrong output on Eclipse IDE but gets accepted when submitted to Coursera? This is a sample input for which it shows the wrong output.
Sample Input:
5 3 2 4 1 5
3 1 2 7
Output:
-1 -1 -1
Clearly, the element '1' is present is the input array. But the output for that is -1 instead of 3.
import java.io.*;
import java.util.*;
public class BinarySearch {
static int binarySearch(int[] a,int l,int r,int x) {
//write your code here
if(l<=r){
int mid =l + (r - l)/2;
if(x==a[mid])
return mid;
else if(x<a[mid]){
return binarySearch(a,l,mid-1,x);
}
else
return binarySearch(a,mid+1,r,x);
}
return -1;
}
public static void main(String[] args) {
FastScanner scanner = new FastScanner(System.in);
int n = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
int m = scanner.nextInt();
int[] b = new int[m];
for (int i = 0; i < m; i++) {
b[i] = scanner.nextInt();
}
for (int i = 0; i < m; i++) {
//replace with the call to binarySearch when implemented
System.out.print(binarySearch(a,0,n-1,b[i]) + " ");
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
}
Actually, the problem is with your input data and not the code itself. If you search information about binary search you can find: "binary search is a search algorithm that finds the position of a target value within a sorted array". Your input isn't sorted.
You would have to sort the array before running the search which would be a bad idea - searching with other algorithm would take less time than sorting.
If you try to input sorted data, eg.:
5 1 2 3 4 5
3 1 2 7
The result will be 0 1 -1 - just as expected.
OK, I have found the following code somewhere that generate a random txt file. Basically I want random words separated by some whitespace in order to run MapReduce word counting simulations.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
PrintWriter writer = new PrintWriter("bigfile.txt", "UTF-8");
Random random = new Random();
for(int i = 0; i < 23695522; i++)
{
char[] word = new char[random.nextInt(8)+3]; // words of length 3 through 10. (1 and 2 letter words are boring.)
for(int j = 0; j < word.length; j++)
{
word[j] = (char)('a' + random.nextInt(26));
}
writer.print(new String(word) + ' ');
if (i % 10 == 0){
writer.println();
}
}
writer.close();
} catch (IOException e) {
// do something
}
}
}
Now I want to alter this code a bit in order to have as much iterations as needed for the file to have approximately a predefined size. So, every iteration produces about 6.5 characters (due to uniform selection) each of 2 bytes. So, I divide the size of file I want in bytes by (6.5*2), set the result as the number of for loop iteration and get a file much smaller than I expect it to be.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
long count=0;
try{
File file = new File("bigfile.txt");
PrintWriter writer = new PrintWriter(file, "UTF-8");
Random random = new Random();
for(int i = 0; i < 23695522; i++)
{
char[] word = new char[random.nextInt(8)+3]; // words of length 3 through 10. (1 and 2 letter words are boring.)
count+=word.length;
for(int j = 0; j < word.length; j++)
{
word[j] = (char)('a' + random.nextInt(26));
}
writer.print(new String(word) + ' ');
count+=1;
if (i % 10 == 0){
writer.println();
count+=2;
}
}
writer.close();
} catch (IOException e) {
// do something
}
System.out.println(count);
}
}
Try this one. Newline char is 2 byte and the others are 1 byte.
how about counting bytes and loop until you get the right amount of bytes?
int writtenBytes = 0;
do{
String randomWords = ....;
writtenBytes += randomWords.getBytes(StandardCharsets.UTF_8).length;
writer.print(randomWords);
}while(writtenBytes < 123456);
So I'm new to programming and we have to do this lab where we read from a text file that has only one line with numbers. We then have to put those integers into an array. I know how to read the numbers when they are in separate lines but not when they are in one line. I also know how to put numbers into an array, so I don't need help with that.
The only methods we are allowed to use are:
hasMoreTokens()
hasMoreLines()
readDouble()
readInt()
readLine()
readToken()
Is there a way to do such while using only these methods?
Here is the code:
import chn.util.FileInput;
import chn.util.FileOutput;
public class Compact {
public Compact (FileInput inFile, FileOutput outFile){
int[] compactArray = new int [21];
int numZeroes = 0;
int num;
int length = compactArray.length;
for (int i = 0; i < length; i++) { //making the array for the integers in the list
compactArray[i] = 0;
}
while (inFile.hasMoreLines()) {
num = 0;
num = inFile.readInt(); //reads the integers per line
compactArray[num]++;
}
for(int i = 0; i < length; i++) {
if(compactArray[i] == 0) {
length--;
for(int j = i; j < length; j++) {
compactArray[j] = compactArray[j+1];
}
i--; // Decrement i to check the value that was shifted
} else {
numZeroes++;
}
}
// now print the array without 0
for(int i = 0; i < numZeroes; i++) {
outFile.print(" " + compactArray[i]);
}
outFile.close();
}
For some reason it's simply returning a string of zeroes. I was thinking it may have to do with the way I read the code.
Input: numbers_line.txt which has one line:
1 8 3 43 4 56
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class ReadIntFromFile {
public static void main(String []args){
String fileName = "numbers_line.txt";
List<String> numbersArrayList = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
numbersArrayList = Arrays.asList(line.split(" "));
}
} catch (IOException e) {
e.printStackTrace();
}
String[] numbersStringArray = new String[numbersArrayList.size()];
numbersStringArray = numbersArrayList.toArray(numbersStringArray);
int[] numbersIntArray = new int[numbersStringArray.length];
for(int i = 0;i < numbersStringArray.length;i++) {
numbersIntArray[i] = Integer.parseInt(numbersStringArray[i]);
}
for(int x : numbersIntArray)
System.out.println(x);
}
}
Output:
1
8
3
43
4
56
So I have a text file containing ints, doubles, strings that I need to read into a 2D array. there Array should have 6 columns but the rows are not known until you read the entire file. I'm guessing it is some 700 rows This is what I have so far. If I eliminate the array it prints fine but with the array I keep getting errors.
I have searched many questions like this but they usually only work with ints/doubles. Also please don't recommend arrayList as that has not been taught in our course.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class TitanicApp {
public static void main(String[] args) throws FileNotFoundException {
String[][] array=null;
int i=0, j=0;
String fileLine;
String s;
Scanner scannerIn=null;
BufferedReader inputStream=null;
try{
inputStream = new BufferedReader(new FileReader("titanic.txt"));
scannerIn = new Scanner(inputStream);
while ((fileLine = inputStream.readLine()) != null){
for (j=0;j<6;j++){
array [i][j]=scannerIn.next();
System.out.println(array[i][j]);
i++;
}
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
Sample text in file :
1 1 Allen, Miss. Elisabeth Walton female 29 211.3375
1 1 Allison, Master. Hudson Trevor male 0.9167 151.5500
And the output should be :
[ [1, 1, Allen, Miss. Elisabeth Walton, female, 29, 211.3375]
[1, 1, Allison, Master. Hudson Trevor, male, 0.9167, 151.5500]
]
I have a txt file containing the above info (and more lines) and I need to put it into a 2D array. I had to remove more than half of it since there was a limit.
So you want to do it using array only. You can consider below example as reference -
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TitanicApp {
int size = 10;
int colCount = 6;
String[][] array = null;
public static void main(String[] args) {
TitanicApp app = new TitanicApp();
app.startExec();
}
public void startExec() {
array = new String[size][colCount];
String fileLine;
int i=0;
try
{
BufferedReader inputStream = new BufferedReader(new FileReader("C:/titanic.txt"));
while ((fileLine = inputStream.readLine()) != null) {
addTo2DArray(fileLine.split("\\t"), ++i);
}
inputStream.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
// Now you have the desired array : array;
}
public void addTo2DArray(String[] tmpArray, int minCapacity) {
if((minCapacity > size)) {
size = (size * 3)/2 + 1;
String[][] newArray = new String[size][colCount];
for(int i=0; i<array.length; i++) {
for(int j=0; j<array[i].length; j++) {
newArray[i][j]=array[i][j];
}
}
array = newArray;
}
array[minCapacity-1] = tmpArray;
}
}
Another Solution :
String content = new Scanner(new File("/titanic.txt")).useDelimiter("\\Z").next();
String[] rows = content.split("\n");
String[][] finalArray = new String[rows.length][];
for(int i=0; i<rows.length; i++)
{
finalArray[i] = rows[i].split("\\t");
}
//Your desired array is : finalArray;
From what it looks like, you are incrementing both array locations, (i and j), at the same time. If you want the input to go in sequential order in the array increment j until array.size and then increment i. An example would be a nested for loop.
for(int i = 0; i < array.size; i++){
for(int j = 0; j < array.size; j++){
array[i][j] = scanner.next();
System.out.println(array[i][j]);
}
}
or in your case, stop incrementing the values until i and j get to 6 instead of array.size
I think you need declare a size for your String[][], otherwise you will get a NullPointerException. ArrayLists are the only way to dynamically generate the list as you move on as far as my knowledge goes.