JAVA Integer Trouble - java

I have written a sorting algorithm (bubble) and I have used 10000 unique values i.e.
int BubArray[] = new int[]{#10000 unique unsorted values#};
I was wondering how I would put the integers into a file and call the file instead of the 10000 integers in the code.
Also in which format would they go (with commas, spaces?) I'm not sure.
Any help would be appreciated, thanks.

This is not correct answer, just hint how to use file, but you can modify the code and make it usable according to your need.
try {
String str;
String[] temp;
BufferedReader br = new BufferedReader(new FileReader("your filepath"));
while ((str= br.readLine()) != null) {
temp = str.split(";"); // seperator words bye;
System.out.println(str);
for(int i = 0; i<temp.lenght; i++)
System.out.println(temp[i]);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

Assuming you need some random numbers to test your sort method:
int amount = 1000;
int[] array = new int[amount];
Random rand = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = rand.nextInt();
}

If you want to give input 1000 different unique values Random is not an good idea. Random can give same value more than once.

Put it in a File separated by line breaks and use a Scanner to read line by line, putting them into an array.
An example taken from Scanner documentation page:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
You can easily modify it to get int instead of long using hasNextInt() and nextInt() methods.

Related

Using Scanner to read Strings in Java

I'm trying to read a file called "CityData.txt" that just has a list of city names in it, one on each line. I've been using scanner in the past to read Strings from a file, and am using it to read ints from another file in this same program, however it doesn't seem to be reading anything from the file.
int counter2 = 0;
File strFile = new File("CityData.txt");
Scanner strScanner = new Scanner(strFile);
Scanner strCountScanner = new Scanner(strFile);
while ((strScanner.hasNext() == true)) {
System.out.println(strScanner.nextLine());
counter2++;
}
System.out.println("This is counter2: " + counter2);
String[] array2 = new String[counter2];
while ((strCountScanner.hasNext() == true)) {
for (int i = 0; i < counter2; i++) {
array2[i] = strCountScanner.nextLine();
}
}
Ideally, counter2 will tell me how many cities are in the file, and I'll then populate array2 with them. However, counter2 remains at 0 after the program has been run. I've been fiddling with this for a while, and am hoping that maybe I've just missed something silly.
Thanks
You are trying to add cities to an array?
public static void readText throws FileNotFoundException {
ArrayList lines = new ArrayList();
Scanner scan = new Scanner(new File("CityData.txt"));
while(scan.hasNextLine()){
String line = scan.nextLine();
lines.add(line);
}
}
or a stream in 8
Stream <String> lines = Files.lines(Paths.get("c:\\demo.txt"));
lines.forEach(System.out::println);
lines.close();
Ideally I would avoid two loops and just use an ArrayList for this purpose. This can give you count as well as the flexibility to make the array more dynamic. Also I would enclose Scanner in try with resources block as it closes the resource itself. Here is the code for reference.
File strFile = new File("CityData.txt");
try (Scanner strScanner = new Scanner(strFile)) {
ArrayList<String> arrayList = new ArrayList<>();
while (strScanner.hasNext()) {
arrayList.add(strScanner.nextLine());
}
System.out.println("number of cities is " + arrayList.size());
System.out.println("cities are " + arrayList);
}catch (Exception e){
e.printStackTrace();
}
Since you are reading in string, using hasNextLine() will be more appropriate. You can try the code below, it should work as intended. HTH.
int counter2 = 0;
File strFile = new File("CityData.txt");
Scanner strScanner = new Scanner(strFile);
Scanner strCountScanner = new Scanner(strFile);
while((strScanner.hasNextLine() == true)) {
System.out.println(strScanner.nextLine());
counter2++;
}
System.out.println("This is counter2: " + counter2);
String[] array2 = new String[counter2];
while((strCountScanner.hasNextLine() == true)) {
for (int i = 0; i < counter2; i++) {
array2[i] = strCountScanner.nextLine();
}
}

In Java how to check if the next record in a file is the end?

I want to sequentially read each line of an input unsorted file into consecutive elements of the array until there are no more records in
the file or until the input size is reached, whichever occurs first. but i can't think of a way to check the next line if its the end of the file?
This is my code:
Scanner cin = new Scanner(System.in);
System.out.print("Max number of items: ");
int max = cin.nextInt();
String[] input = new String[max];
try {
BufferedReader br = new BufferedReader(new FileReader("src/ioc.txt"));
for(int i=0; i<max; i++){ //to do:check for empty record
input[i] = br.readLine();
}
}
catch (IOException e){
System.out.print(e.getMessage());
}
for(int i=0; i<input.length; i++){
System.out.println((i+1)+" "+input[i]);
}
the file has 205 lines, if I input 210 as max, the array prints with five null elements like so..
..204 Seychelles
205 Algeria
206 null
207 null
208 null
209 null
210 null
Thanks for your responses in advance!
From the docs:
public String readLine()
Returns: A String containing the contents of the line, not including
any line-termination characters, or null if the end of the stream has
been reached
In other words, you should do
String aux = br.readLine();
if(aux == null)
break;
input.add(aux)
I recomend you use a variable-size array (you can pre-allocated with the requested size if reasonable). Such that you get either the expected size or the actual number of lines, and can check later.
(depending on how long your file is, you might want to look at readAllLines() too.)
Please refer this Number of lines in a file in Java and modify your for loop to take whatever is the least out of the entered max value or the no.of lines in the file.
Use List<String>
List<String> lines = new ArrayList<>(); // Growing array.
try (BufferedReader br = new BufferedReader(new FileReader("src/ioc.txt"))) {
for(;;) {
String line = br.readLine();
if (line == null) {
break;
}
lines.add(line);
}
} catch (IOException e) {
System.out.print(e.getMessage());
} // Closes automatically.
// If lines wanted as array:
String[] input = lines.toArray(new String[lines.size()]);
Using a dynamically growing ArrayList is the normal way to deal with such problem.
P.S.
FileReader will read in the current platform encoding, i.e. a local file, created locally.
You could do a null check in your first for-loop like:
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
System.out.print("Max number of items: ");
int max = cin.nextInt();
BufferedReader br = new BufferedReader(new FileReader("src/ioc.txt"));
List<String> input = new ArrayList<>();
String nextString;
int i;
for (i = 0; i < max && ((nextString = br.readline()) != null); i++) {
input.add(nextString);
}
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + " " + input.get(j));
}
}
Try :
for(int i=0; i<max; i++){ //to do:check for empty record
if(br.readLine()!=null)
input[i] = br.readLine();
else
break;
}
int i=0;
for(; i<max; i++){ //to do:check for empty record
String line=br.readLine();
if(line==null){
break;
}
input[i] = line;
}
//i will contain the count of lines read. indexes 0...(i-1) represent the data.

reading text from .db file one line at a time

First of, I don't know how a.db file stores it data. If it does it in one line, or over many lines. Probably it does some difference from how to solve the problem.
the problem I'm facing is that I don't know how much data the file contains, only that it will be a date, time, and a description for x number of events in the form given below.
I have to convert the text into strings and put them in an array, but I don't know how to separate the text. When I tried I just ended up with one long string.
Can anybody help me?
01.01.2015|07:00-07:15|get up
01.01.2015|08:00|get to work
01.01.2015|08:00-16:00| work
01.01.2015|16:00-16:30| go home
what I want:
array[0] = "01.01.2015|07:00-07:15|get up"
array[1] = "01.01.2015|08:00|get to work"
array[2] = "01.01.2015|08:00-16:00| work"
array[3] = "01.01.2015|16:00-16:30| go home"
string table[] = new String [100];
void readFile(String fileName){
String read = "";
try {
x = new Scanner (new File(fileName));
}
catch (Exception e) {
}
while (x.hasNext()) {
read += x.nextLine();
}
}
Assuming here that your first code-block is in fact a copy of the file you're trying to read, you can do:
Scanner s = new Scanner(new File("file1.txt"));
List<String> lines = new LinkedList<>();
while (s.hasNextLine())
lines.add(s.nextLine());
If you really want to work with arrays and not lists, you can do
String[] table = lines.toArray(new String[lines.size()]);
after the loop.
If you're fortunate enough to work with Java 8, you can use:
List<String> lines = Files.lines(Paths.get("big.txt"))
.collect(Collectors.toList());
Again, if you really want to work with an array, you can convert the list using lines.toArray.
Since Java 8 you can use Paths.get(String first, String... more), Files.lines(Path path), and Stream.toArray():
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class SOPlayground {
public static void main(String[] args) throws Exception {
Path path = Paths.get("/tmp", "db.txt");
Object[] lines = Files.lines(path).toArray();
System.out.println(lines.length);
System.out.println(lines[0]);
System.out.println(lines[lines.length - 1]);
}
}
Output:
4
01.01.2015|07:00-07:15|get up
01.01.2015|16:00-16:30| go home
Try this solution using arrays:
code
Scanner sc = new Scanner(new File("file.txt"));
int index;
String[] arr = new String[1];
for(index = 0; sc.hasNextLine(); index++) {
arr = Arrays.copyOf(arr, index + 1);
arr[index] = sc.nextLine();
}
for(int i = 0; i<arr.length; i++) {
System.out.print(arr[i] + "\n");
}
I have used arr = Arrays.copyOf(arr, index + 1) to increase the size of the array to add next element.
Output
01.01.2015|07:00-07:15|get up
01.01.2015|08:00|get to work
01.01.2015|08:00-16:00| work
01.01.2015|16:00-16:30| go home
Well, it took me some houres. Thanx to all who lended a hand. This was what I got in the end.
int i=0;
String array [] new String [100]
try {
FileReader textFileReader= new FileReader (fileName);
BufferedReader textReader= new BufferedReader(textFileReader);
boolean continue = true;
while (continue) {
String text = textReader.readLine();
if (text != null){
array[i] = text;
i++;
}else {
continue = false;
}
}
}catch (Exception e) {}

How can I return an array out of try-catch block in java?

I created a 2D array from reading a file and I want to return this array. However I use try-catch block because of reading file. At this point I can't return this array from this function.Also when I try to write the elements of this array in try-catch block, it works but out of block it doesn't. What should I do to get the array?
My code is as below:
public static double[][] readFile(String fileName) {
final double[][]data = new double[178][13];
int x=0, y=0;
try{
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while((line = reader.readLine())!= null){
String[]values=line.split(",");
for(String str:values){
double str_double=Double.parseDouble(str);
data[x][y]=str_double;
System.out.print(data[x][y]+" ");
}
System.out.println();
}
reader.close();
}
catch(Exception e){}
return data;
}
Finally, with helps of everyone I found a solution. One of my mistake is defining y. Beacuse each line has 14 elements but I assigned it to 13. Also I changed assignment method of array. Maybe anyone needs, so I post it to here my solution:
public static double[][] readFile(String fileName) {
double[][]data=new double[178][14];
int x=0, y;
try{
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
String[]values;
while((line = reader.readLine())!= null){
values=line.split(",");
for(y=0; y<values.length; y++){
data[x][y]=Double.parseDouble(values[y]);
}
x++;
}
reader.close();
}
catch(Exception e){System.out.println("Aborting due to error: " + e);}
return data;
}
The original code assigns only one value at the array, i.e. the element data[0][0], since x and y never change from 0.
Assuming that x is the line and y is the column (element in the line), the following should work:
public static double[][] readFile(String fileName) {
final double[][]data = new double[178][13];
int x, y;
try{
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
x = 0; // Reset the line counter
while((line = reader.readLine()) != null) { // Read a new line
y=0; // Reset the column counter, since this is a new line
String[]values=line.split(",");
for(String str:values){
double str_double=Double.parseDouble(str);
data[x][y]=str_double;
System.out.print(data[x][y]+" ");
++y; // Advance to the next column
}
++x; // Advance to the next line
System.out.println();
}
reader.close();
} catch (Exception e) {
System.out.println("Aborting due to error: " + e);
}
return data;
}
The above assumes, of course, that no errors occur as a result of calling readLine() or parseDouble(). If any such error happens, or an ArrayIndexOutOfBoundsException occurs, the returned array will only contain the elements read thus far.
Here is an improved version, again maintaining as much of the original code as possible:
public static double[][] readFile(String fileName) {
ArrayList<double[]> numbers = new ArrayList<double[]>();
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) { // Read a new line
int y=0; // Reset the column counter, since this is a new line
String[] values = line.split(",");
if (values.length > 0) {
double[] elements = new double[values.length];
for (String str:values) {
double str_double;
try {
str_double = Double.parseDouble(str);
elements[y] = str_double;
System.out.print(elements[y] + " ");
++y; // Advance to the next column
} catch (Exception e) {
continue; // Not a double, ignore
}
}
numbers.add(elements);
} else {
numbers.add(new double[0]); // No numbers read from the line
}
System.out.println();
}
reader.close();
} catch (Exception e) {
System.out.println("Aborting due to error: " + e);
}
return numbers.toArray(new double[0][0]);
}
Neither of the two versions is tested, but they should both be close to a working solution.
The second approach is more generic and should be preferred, although, to avoid boxing/unboxing between double and Double, it assumes that, if any element read as a string is not a valid double, the corresponding position in the elements array will be filled by the next valid double, if any. So, if, for example, there are 10 elements in a line and only 8 of them are valid in total, then the first 8 positions of the array will contain the values of these elements and the last 2 positions will contain 0 (set during the initialization of the elements array).
There is no specific need for declaring the variable as a final variable.
You need not declare it as private as well.
simple
double[][]data = new double[178][13];
variable declaration is incorrect

Java: Read up to x chars from a file into array

I want to read a text file and store its contents in an array where each element of the array holds up to 500 characters from the file (i.e. keep reading 500 characters at a time until there are no more characters to read).
I'm having trouble doing this because I'm having trouble understanding the difference between all of the different ways to do IO in Java and I can't find any that performs the task I want.
And will I need to use an array list since I don't initially know how many items are in the array?
It would be hard to avoid using ArrayList or something similar. If you know the file is ASCII, you could do
int partSize = 500;
File f = new File("file.txt");
String[] parts = new String[(f.length() + partSize - 1) / partSize];
But if the file uses a variable-width encoding like UTF-8, this won't work. This code will do the job.
static String[] readFileInParts(String fname) throws IOException {
int partSize = 500;
FileReader fr = new FileReader(fname);
List<String> parts = new ArrayList<String>();
char[] buf = new char[partSize];
int pos = 0;
for (;;) {
int nRead = fr.read(buf, pos, partSize - pos);
if (nRead == -1) {
if (pos > 0)
parts.add(new String(buf, 0, pos));
break;
}
pos += nRead;
if (pos == partSize) {
parts.add(new String(buf));
pos = 0;
}
}
return parts.toArray(new String[parts.size()]);
}
Note that FileReader uses the platform default encoding. To specify a specific encoding, replace it with new InputStreamReader(new FileInputStream(fname), charSet). It bit ugly, but that's the best way to do it.
An ArrayList will definitely be more suitable as you don't know how many elements you're going to have.
There are many ways to read a file, but as you want to keep the count of characters to get 500 of them, you could use the read() method of the Reader object that will read character by character. Once you collected the 500 characters you need (in a String I guess), just add it to your ArrayList (all of that in a loop of course).
The Reader object needs to be initialized with an object that extends Reader, like an InputStreamReader (this one take an implementation of an InputStream as parameter, a FileInputStream when working with a file as input).
Not sure if this will work, but you might want to try something like this (Caution: untested code):
private void doStuff() {
ArrayList<String> stringList = new ArrayList<String>();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("file.txt"));
String str;
int count = 0;
while ((str = in.readLine()) != null) {
String temp = "";
for (int i = 0; i <= str.length(); i++) {
temp += str.charAt(i);
count++;
if(count>500) {
stringList.add(temp);
temp = "";
count = 0;
}
}
if(count>500) {
stringList.add(temp);
temp = "";
count = 0;
}
}
} catch (IOException e) {
// handle
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories