what makes it only be able to input 10*10 text files
package game;
import java.io.*;
import java.util.*;
public class Level {
static public void main(String[] args) throws IOException {
File f = new File("Data1.txt");
int[][] m = Map(f);
for (int x = 0; x < m.length; x++) {
for (int y = 0; y < m[x].length; y++) {
System.out.print(m[x][y]);
}
System.out.println();
}
}
public static int[][] Map(File f) throws IOException {
ArrayList line = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(f));
String s = null;
while ((s = br.readLine()) != null) {
line.add(s);
}
int[][] map = new int[line.size()][];
for (int i = 0; i < map.length; i++) {
s = (String) line.get(i);
StringTokenizer st = new StringTokenizer(s, " ");
int[] arr = new int[st.countTokens()];
for (int j = 0; j < arr.length; j++) {
arr[j] = Integer.parseInt(st.nextToken());
}
map[i] = arr;
}
return map;
}
}
if i put in a text file that is
10*10 or less characters it works
otherwise it comes out with a numberformatexception
fixed
package game;
import java.io.*;
import java.util.*;
public class Level {
static public void main(String[] args) throws IOException {
File f = new File("Data1.txt");
int[][] m = Map(f);
for (int x = 0; x < m.length; x++) {
for (int y = 0; y < m[x].length; y++) {
System.out.print(m[x][y]);
}
System.out.println();
}
}
public static int[][] Map(File f) throws IOException {
ArrayList line = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(f));
String s = null;
while ((s = br.readLine()) != null) {
line.add(s);
}
int[][] map = new int[line.size()][];
for (int i = 0; i < map.length; i++) {
s = (String) line.get(i);
char[] m = s.toCharArray();
String[] n = new String[m.length];
for (int t = 0; t<m.length;t++)
{
n[t] = ""+m[t];
}
int[] arr = new int[m.length];
for (int j = 0; j < arr.length; j++) {
arr[j] = Integer.parseInt(n[j]);
}
map[i] = arr;
}
return map;
}
}
Contrary to notes in the comments, your program seems to work with large files, and with long lines, as long as there are enough spaces.
I think your issue is actually that whenever the text file has a token with more than 10 characters it throws a NumberFormatException.
That would be because Integer.MAX_INT is 2147483647, which has 10 characters when written as a String, and Integer.parseInt just can't handle more digits than that.
You're splitting on space and expecting everything to parse as an integer, and some of your numbers are too big for Java's integer data type.
Int's max value is: 2,147,483,647 or 2147483647 without the commas. That's 10 characters. attempting to parse an 11 character string to an int would result in a number that is beyond the Int's max value, hence, the NumberFormatException.
Related
Here is the text file content:
5
3
*&*&*
&*&*&
*&*&*
50
5
*&&&&&&&&*&***************&**********************&
&&********&***************&&**********************
*&&**&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&*********&&***********&***************&*********
*&&&&&******&&*********&&&**************&********&
Here is my code currently:
public class Main {
public static char[][] grid1 = new char[5][50];
public static void readGridData (String fileName, char[][] grid) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
int columnCount = Integer.parseInt(br.readLine());
int rowCount = Integer.parseInt(br.readLine());
System.out.println(columnCount);
System.out.println(rowCount);
for (int i = 0; i < rowCount; i++) {
String line = br.readLine();
for (int j = 0; j < columnCount; j++) {
grid[i][j] = line.charAt(j);
}
}
br.close();
}
/* prints the 2D array given as argument */
public static void printGrid(char[][] grid) {
int rowLength = grid.length;
int columnLength = grid[0].length;
for (int i = 0; i < rowLength; i++) {
for (int j = 0; j < columnLength; j++) {
System.out.print(grid[i][j]);
}
System.out.println();
}
System.out.println();
} // End of printGrid
public static void main(String args[]) throws IOException {
readGridData("simple.txt", grid1);
printGrid(grid1);
}
}
The output is only the first grid, which is 5, 3, and the grid itself. How can I continue to read the whole text file?
Later I will count blob with the array so is there any best way to optimize this?
I cannot use ArrayList for this. Thank you very much for your help!
Declare and initialise your buffer outside of the readGridData method and then pass it a parameter. In that case you'll be able to continue reading.
I'd even use a Scanner instead:
public static char[][] readGridData(Scanner scanner) {
int columnCount = scanner.nextInt();
int rowCount = scanner.nextInt();
System.out.println(columnCount);
System.out.println(rowCount);
char[][] grid = new char[rowCount][columnCount]
for (int i = 0; i < rowCount; i++) {
String line = scanner.nextLine();
for (int j = 0; j < columnCount; j++) {
grid[i][j] = line.charAt(j);
}
}
return grid;
}
and then:
public static void main(String args[]) throws IOException {
try (Scanner scanner = new Scanner("simple.txt")) {
while (scanner.hasNextInt()) {
char[][] grid = readGridData(scanner);
printGrid(grid);
}
}
}
There is a voice recorder which stores student voice as per roll number on which it was heard earlier. When the attendance process is complete, it will provide a list which would consist of the number of distinct voices. The teacher presents the list to you and asks for the roll numbers of students who were not present in class.
I'm trying to find out roll number of absent students in increasing order.
I wrote this case but some test cases are failing. I'm not sure what values would be in list which is provided by teacher.
There are only two inputs:
no of student
result from voice recorder
So can anyone tell what is missing here
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
List<Integer> ll = new ArrayList<>();
List<Integer> input = new ArrayList<>();
for (int i = 1; i <= n; i++) {
ll.add(i);
}
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
input.add(Integer.parseInt(strs[i]));
}
for (int i = 0; i < ll.size(); i++) {
if (input.contains(ll.get(i))) {
continue;
}
else {
System.out.print(ll.get(i));
}
if (i != ll.size() - 1) {
System.out.print(" ");
}
}
}
This works fine and every test case passed.
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int stdCount = Integer.parseInt(br.readLine());
String rollNumbers = br.readLine();
TreeSet<Integer> presentStudents = new TreeSet<Integer>();
String[] rollNoArr = rollNumbers.split(" ");
for(String s : rollNoArr) {
presentStudents.add(Integer.valueOf(s.trim()));
}
for(int i = 1; i <= stdCount; i++) {
if(!presentStudents.contains(i)) {
System.out.print(i);
if(i < stdCount) System.out.print(" ");
}
}
}
Assuming that I'm reading the question correctly, you first input the total number of students in the class. Each student has an assigned number, and you next provide a list of numbers (cooresponding to students present in class) seperated by spaces. Your code was missing a few brackets, which messed things up.
In addition, for this specific case, your logic of:
if (true) {
continue;
}
else{
// Do something
}
Can be made a lot simpler by doing:
if(!true){
// Do something
}
Here is the final code that I touched up:
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
List<Integer> ll = new ArrayList<>();
List<Integer> input = new ArrayList<>();
for (int i = 1; i <= n; i++) {
ll.add(i);
}
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
input.add(Integer.parseInt(strs[i]));
}
for (int i = 0; i < ll.size(); i++) {
if (!input.contains(ll.get(i))) {
System.out.print(ll.get(i));
if (i != ll.size() - 1) {
System.out.print(" ");
}
}
}
}
An input of:
6
1 3 4
Results in an output of:
2 5 6
////working code using Java8
{
public static void main(String[] args) throws IOException {
List<Integer> totalRolls;
String[] inputRollsWithProxyStudentsRoll;
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
totalRolls = IntStream
.rangeClosed(1, Integer.parseInt(br.readLine()))
.boxed()
.collect(Collectors.toList());
inputRollsWithProxyStudentsRoll = br.readLine().trim().split("\\s+");
}
List<Integer> rollsWithProxyStudentsRoll = Arrays
.stream(inputRollsWithProxyStudentsRoll).map(Integer::parseInt)
.collect(Collectors.toList());
IntStream
.range(0, totalRolls.size())
.filter(i -> !rollsWithProxyStudentsRoll.contains(totalRolls.get(i)))
.forEach(i -> {
System.out.print(totalRolls.get(i));
if (i != totalRolls.size() - 1) System.out.print(" ");
});
}
}
import java.io.*
import java.util.*;
class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = sc.nextInt();
for (int i = 1; i <= n; i++) {
for (int j = 0; j < n; j++) {
if (i == array[j]) {
break;
}
if (j == n - 1 && i != array[j]) {
System.out.println(i + " ");
}
}
}
}
}
I am trying to print write the contents from void method to a file but I cant seem to get it to work. I call my method in the main and it prints to the console just fine. I have tried many different approaches but not one worked. Can anyone help/guide me in the right direction?
I have pasted my code below for reference. In my main function I call dijkstra(M, SV - 1) that prints my array to the screen, my goal is to have that same array printed to a file.
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.Scanner;
public class Main_2 {
static int SV = 0; // source vertex
static int N = 0;
static int M[][];
public static int distance[];
static int minDistance(int dist[], Boolean shortestPath[]) {
int min = Integer.MAX_VALUE, minI = -1;
for (int i = 0; i < N; i++)
if (shortestPath[i] == false && dist[i] <= min) {
min = dist[i];
minI = i;
}
return minI;
}
public static void printArr(int dist[], int n) {
// System.out.println("vertex distance");
for (int i = 0; i < N; i++)
System.out.println("[" + dist[i] + "]");
}
public static void dijkstra(int graph[][], int src) {
// The output array. dist[i] will hold
// the shortest distance from src to i
int dist[] = new int[N];
// sptSet[i] will true if vertex i is included in shortest
// path tree or shortest distance from src to i is finalized
Boolean shortestPath[] = new Boolean[N];
// Initialize all distances as INFINITE and stpSet[] as false
for (int i = 0; i < N; i++) {
dist[i] = Integer.MAX_VALUE;
shortestPath[i] = false;
}
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find shortest path for all vertices
for (int i = 0; i < N - 1; i++) {
// Pick the minimum distance vertex from the set of vertices
// not yet processed. u is always equal to src in first
// iteration.
int u = minDistance(dist, shortestPath);
// Mark the picked vertex as processed
shortestPath[u] = true;
// Update dist value of the adjacent vertices of the
// picked vertex.
for (int j = 0; j < N; j++)
// Update dist[v] only if is not in sptSet, there is an
// edge from u to v, and total weight of path from src to
// v through u is smaller than current value of dist[v]
if (!shortestPath[j] && graph[u][j] != 0 && dist[u] != Integer.MAX_VALUE
&& dist[u] + graph[u][j] < dist[j])
dist[j] = dist[u] + graph[u][j];
}
// print the constructed distance array
printArr(dist, N);
}
public static void main(String[] args) {
try {
int i = 0, j = 0; // counters
FileInputStream textFile = new FileInputStream("EXAMPLE(2).txt"); // name of input file must go in here
Scanner scan = new Scanner(textFile);
N = scan.nextInt(); // read in the size
String flush = scan.nextLine(); // gets rid of linefeed
System.out.println(N);
M = new int[N][N]; // instantiates array
// this loop reads in matrix from input file
String line;
while (i < N && (line = scan.nextLine()) != null) {
j = 0;
String delim = " ";
String tokens[] = line.split(delim);
for (String a : tokens) {
M[i][j] = Integer.parseInt(a);
j++;
}
i++;
}
if (i > N)
;
SV = scan.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
printMatrix(M);
System.out.println(SV);
System.out.println();
dijkstra(M, SV - 1);
try {
FileWriter fw = new FileWriter("Shortest_path.txt"); // writes transitive closure to file
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < N; i++) {
// bw.write(dist[i]);
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void printMatrix(int[][] Matrix) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(Matrix[i][j]);
System.out.print(" ");
}
System.out.println();
}
}
}
try (FileWriter fileWriter = new FileWriter("YourFileName.txt");
PrintWriter printWriter = new PrintWriter(fileWriter)) {
for (int i=0; i<N; i++) {
printWriter.printf(Integer.toString(dist[i]));
}
} catch (Exception e) {
System.out.println(e);
}
"A" simple solution, would be to pass the PrintStream you want to use to the method, for example...
public static void printArr(int dist[], int n, PrintStream ps) {
for (int i = 0; i < N; i++) {
ps.println("[" + dist[i] + "]");
}
}
This will then require you to pass a PrintStream instance to the method when ever you call it. Since dijkstra also calls printArr, you will need to pass the instance of the PrintStream to it as well...
public static void dijkstra(int graph[][], int src, PrintStream ps) {
//...
// print the constructed distance array
printArr(dist, N, ps);
}
Then you just create an instance of the PrintStream you want to use and pass it to the methods...
public static void main(String[] args) {
try (FileInputStream textFile = new FileInputStream("EXAMPLE(2).txt")) {
int i = 0, j = 0; // counters
Scanner scan = new Scanner(textFile);
N = scan.nextInt(); // read in the size
String flush = scan.nextLine(); // gets rid of linefeed
System.out.println(N);
M = new int[N][N]; // instantiates array
// this loop reads in matrix from input file
String line;
while (i < N && (line = scan.nextLine()) != null) {
j = 0;
String delim = " ";
String tokens[] = line.split(delim);
for (String a : tokens) {
M[i][j] = Integer.parseInt(a);
j++;
}
i++;
}
if (i > N)
;
SV = scan.nextInt();
try (PrintStream ps = new PrintStream("EXAMPLE(2).txt")) {
printMatrix(M);
System.out.println(SV);
System.out.println();
dijkstra(M, SV - 1, ps);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I restructured your main method slightly, as the output is depended on the success of the input ;). Also see The try-with-resources statement for more details
This means you could do something like...
dijkstra(M, SV - 1, System.out);
and it would once again print the output to the console :)
I want to read and save the content of the file in a 2d array, but I don't know the size of the file, because the program should read different files. So there is the first problem after "new char". I searched for the problem and found that "matrix[x][y]=zeile.charAt(x);"
should be right, but that throws the error "NullPointerException" when I write any number into the first brackets of new char.
Could somebody explain and give some ideas oder solutions? Thank you :)
import java.io.*;
class Unbenannt
{
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("Level4.txt");
BufferedReader br = new BufferedReader(fr);
String zeile = br.readLine();
char [][] matrix = new char [][];
while(zeile != null )
{
int y = 0;
for(int x = 0; x < zeile.length(); x++) {
matrix[x][y] = zeile.charAt(x);
}
y++;
} System.out.print(matrix);
br.close();
}
}
Arrays are stored as blocks in memory in order to achieve O(1) operations, which is why you need to define their size during definition. If you insist on arrays (rather than a dynamic ADT such as List), you'll need to know the dimensions in advance.
What you could do is store the file lines temporarily in a list and find out the maximum line length, i.e.:
List<String> lines = new ArrayList<String>();
String zeile = null;
int max = 0;
while ((zeile = br.readLine()) != null) {
lines.add(zeile);
if (zeile.length() > max)
max = zeile.length();
}
char[][] matrix = new char[lines.length()][max];
// populate the matrix:
for (int i = 0; i < lines.length(); i++) {
String line = lines.get(i);
for (int j = 0; j < line.length(); j++) {
matrix[i][j] = line.charAt(j);
}
}
Note that since char is a primitive, you'll be initialized with the default value 0 (the integer, not the character!) in every cell of the inner array, so for lines which are shorter than the others, you'll have trailing zero characters.
you initialize the matrix (char [][]) but you never initialize any of the inbound arrays. This leads to the NullPointerException.
In addition your 'while' condition looks invalid, seems you only are reading the first line of your file here > your code will never complete and read the first line over and over again
Thank you all! It works! But there is still one problem. I changed lines.length() into lines.size(), because it doesn't work with length. The problem is the output. It shows for example: xxxx xxxx instead of "xxx" and "x x" and "xxx" among each other.
How can I build in a line break?
my programcode is:
import java.io.*;
import java.util.ArrayList;
class Unbenannt
{
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("Level4.txt");
BufferedReader br = new BufferedReader(fr);
ArrayList<String> lines = new ArrayList<String>();
String zeile = null;
int max = 0;
while ((zeile = br.readLine()) != null) {
lines.add(zeile);
if (zeile.length() > max)
max = zeile.length();
}
char [][] matrix = new char[lines.size()][max];
for(int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
for(int j = 0; j < line.length(); j++) {
matrix[i][j] = line.charAt(j);
System.out.print(matrix[i][j]);
}
}
br.close();
}
}
I try to convert a file to an array of integers, do not know where my mistake is that when I print the array empty array throws
I leave my method , thanks you
public int[] ConvertToArray(File xd) throws IOException {
String sCadena;int i=0;
int[]array;
FileReader fr = new FileReader(xd);
BufferedReader bf = new BufferedReader(fr);
int lNumeroLineas = 0;
while ((sCadena = bf.readLine())!=null) {
lNumeroLineas++;
}
array = new int[lNumeroLineas];
while ((sCadena = bf.readLine())!=null) {
lNumeroLineas++;
array[i]=Integer.parseInt(sCadena);
i++;
}
for (int j = 0; j < array.length; j++) {
System.out.println(array[i]);
}
return array;
}
You are already at the end of file after your first while loop completes.
So reading from BufferedReader object bf again after first while loop ends will always give you null(End of file) and second iteration will never run.
Also in the for loop you are printing array[i] however for loop is iterating over j variable
You can do it like this with help of ArrayList:
public int[] ConvertToArray(File xd) throws IOException {
String sCadena;
ArrayList<Integer> array = new ArrayList();
FileReader fr = new FileReader(xd);
BufferedReader bf = new BufferedReader(fr);
int lNumeroLineas = 0;
while ((sCadena = bf.readLine())!=null) {
lNumeroLineas++;
array.add(Integer.parseInt(sCadena.trim())); //always recomended to trim(); to remove trailing whitespaces.
}
for (int j = 0; j < array.size(); j++) {
System.out.println(array.get(j));
}
return covertIntegers(array);
}
Edited: If you want to send int[] instead of ArrayList<Integer> without using any external libraries.
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
You are reading the file with two loops but open only once. Reopen the file reader before the second while and it will work.