In this programmer i found Prime numbers in first 100.Numbers are in INT format and totally number of them is in DOUBLE format.I want to read that file and i did it for only INT numbers but i dont know hot to do it for DOUBLE number.
Here is the code:
package int1;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.channels.FileChannel;
public class int_upis {
public static void main(String[] args) {
File a = new File("C:\\Users\\Jovan\\Desktop\\Pisem.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(a);
} catch (Exception e) {
}
FileChannel ch = fos.getChannel();
ByteBuffer bff = ByteBuffer.allocate(100);
IntBuffer ibf = bff.asIntBuffer(); // Int type
DoubleBuffer db = bff.asDoubleBuffer(); // Double type
double p = 0;
for (int i = 1; i <= 100; i++) {
int t = 0;
for (int j = 1; j <= i; j++) {
if (i % j == 0) {
t = t + 1;
}
}
if (t < 3) {
p = p + 1; // number of Prime numbers
System.out.println(i);
ibf.put(i);
bff.position(4 * ibf.position());
bff.flip();
try {
ch.write(bff);
bff.clear();
ibf.clear();
} catch (IOException e) {
}
}
}
try {
db.put(p); //At the end of the txt-file i put double format of number (Number of Prime numbers)
bff.position(8*db.position());
bff.flip();
ch.write(bff);
System.out.println("File is writen with: " + ch.size());
ch.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now I tried to read this file:
public class int_ispis {
public static void main(String[] args) throws IOException {
File a = new File("C:\\Users\\Jovan\\Desktop\\Pisem.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(a);
} catch (Exception e) {
}
FileChannel ch = fis.getChannel();
ByteBuffer bff = ByteBuffer.allocate(6 * 4);
This is one line of Prime Number put in a 6-row array (this line below):
int[] niz = new int[6];
System.out.println("Pre flipa: " + bff.position() + " " + bff.limit());
System.out.println("++++++++++++++++++++++++++++++++++++");
while (ch.read(bff) != -1) {
bff.flip();
System.out.println();
System.out.println("Posle flipa: " + bff.position() + " " + bff.limit());
IntBuffer ib = bff.asIntBuffer();
System.out.println("IB: " + ib.position() + " " + ib.limit());
int read = ib.remaining();
System.out.println(read);
When it come to the end of file it puts Double Number as Integer and writes wrong number(How to separate Integer form Double number?)
ib.get(niz, 0, ib.remaining());
for (int i = 0; i < read; i++) {
System.out.print(niz[i] + " ");
}
System.out.println();
System.out.println("=================================");
ib.clear();
bff.clear();
}
}
}
A binary file does not have any "separators".
You need to know the structure of the file content and use this knowledge.
In this programmer i found Prime numbers in first 100.Numbers are in INT format and totally number of them is in DOUBLE format.
This means that there is only one long value in the file and this is in the last 8 bytes. So you simply have to check if the current position is fileLenght - 8 and then read these last 8 bytes as a long value.
Related
how to get a maximum value of two peaks of an array and take them away using for loops? any ideas?
was thinking to use 2 for loops to find the values in the array. i am using an acceloremeter and displaying the result within a graph but now i need to find the 2 peaks and take them away to determine the outcome and display it.
SM.unregisterListener(this);
File path = getApplicationContext().getExternalFilesDir(null);
File file = new File(path, "my_file-name.txt");
// String filename = "my_file";
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(file); //openFileOutput(file, Context.MODE_APPEND);
for (double d : array) {
String s = Double.toString(d) + ",";
outputStream.write(s.getBytes());
}
String newline = "/n";
outputStream.write(newline.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
this code values are stored within a file so i can then display it within a graph
Here is how you can find two peaks in one loop:
File file = new File(path, "my_file-name.txt");
// String filename = "my_file";
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(file); //openFileOutput(file, Context.MODE_APPEND);
double peak1, peak2;
if(array.length >= 2) {
peak1 = array[0];
peak2 = array[1];
} else { // not enough elements
return;
}
for (double d : array) {
// peak2 is greater, leave it;
// save new value to peak1 ?
if(peak1 < peak2 && d > peak1) {
peak1 = d;
} else if(d > peak2) { // peak1 is greater or d is less
peak2 = d;
}
String s = Double.toString(d) + ",";
outputStream.write(s.getBytes());
}
String newline = "/n";
outputStream.write(newline.getBytes());
outputStream.close();
System.out.println("Peaks: " + peak1 + " ; " + peak2);
} catch (Exception e) {
System.out.println("Error: " + e);
//e.printStackTrace();
}
See code sample here.
private void stopSensor() {
SM.unregisterListener(this);
File path = getApplicationContext().getExternalFilesDir(null);
File file = new File(path, "my_file-name.txt");
// String filename = "my_file";
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(file); //openFileOutput(file, Context.MODE_APPEND);
for (double d : array) {
String s = Double.toString(d) + ",";
outputStream.write(s.getBytes());
}
String newline = "/n";
outputStream.write(newline.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
double peak1, peak2;
int peaklocation1, peaklocation2;
if (array.length >= 2) {
peak1 = array[0];
peak2 = array[1];
peaklocation1 = 0;
peaklocation2 = 1;
} else { // not enough elements
return;
}
for (int i = 0; i < array.length; i++) {
double d = array[i];
// peak2 is greater, leave it;
// save new value to peak1 ?
if (peak1 < peak2 && d > peak1) {
peak1 = d;
peaklocation1 = i;
} else if (d > peak2) { // peak1 is greater or d is less
peak2 = d;
peaklocation2 = i;
}
}
int size = peaklocation1;
size = peaklocation1 - peaklocation2 ;
resultText.setText("Result:" + peaklocation1 );
resultText2.setText("Result:" + peaklocation2);
} catch (Exception e) {
// System.out.println("Error: " + e);
//e.printStackTrace();
}
My code
Here I take a name from a user and save it to a file, my purpose is to give that name an index (Out) and save it into a file, so that each time I run the code, I will still have the same name and index(not new values). So how can I do that?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class h_main {
public static void main(String[] args) {
contact[] table = new contact[3]; //Create an object of contact class
int tablesize = 3;
// Input from user
//**Inserting from user**//
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a name: ");
String names = reader.nextLine();
// Save the inserted name inside a table array with an index Out(from the hash function)
int Out = calc_hash(names, tablesize);
table[Out] = new contact();
table[Out].Name = names;
System.out.println(Out);
// Writing
for (int i = 0; i < table.length; i++) {
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("text.txt");
writer = new BufferedWriter(fWriter);
writer.write(table[i].Name);
writer.write(table[i].phone);
writer.newLine();
writer.close();
}
// System.err.println("Your input of " + table[i].Name.length + " characters was saved.");
catch (Exception e) {
System.out.println("Error!");
}
// Reading
// The name of the file to open.
String fileName = "text.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader("text.txt");
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
System.out.println("Name: " + line);
}
// Always close files.
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
"text.txt" + "'");
} catch (IOException ex) {
System.out.println(
"Error reading file '" +
"text.txt" + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
//**Generate hash function**//
public static int calc_hash(String names, int table_size) {
int i, l = names.length();
int hash = 0;
for (i = 0; i < l; i++) {
hash += Character.getNumericValue(names.charAt(i));
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
if (hash > 0) return hash % table_size;
else return -hash % table_size;
}
}
Class contact
public class contact {
String Name ;
int phone ;
}
Have the file not exist when you run the program for the first time. After you do, use the existence of the file to determine whether the program has been run before or not. Your code could look like this:
import java.nio.file.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
// It's recommended to follow Java naming and style conventions:
// Class names always begin with an uppercase letter
Contact[] table = new Contact[3];
String fileName = "text.txt";
Path file = Paths.get(fileName);
// Check for persistence file:
if(Files.exists(file)) {
// If all you need to do is print each line, try this:
try {
Files.lines(file).forEach(l -> System.out.println("Name: " + l));
} catch(IOException e) {
System.err.println("Error reading data file!");
}
} else {
// Take data input
Scanner scanner = new Scanner(System.in);
// ...
// When program is terminated, save everything:
try(BufferedWriter writer = Files.newBufferedWriter(file)) {
// use writer to write data...
} catch(IOException e) {
System.err.println("Error writing data file!");
}
}
}
}
i am trying to find standard deviation(σ = √[(Σ(x - MEAN))2 ÷ n]) of single extracted column of csv file.csv file contain around 45000 instance and 17 attribute saperated with ';'.
for finding standard deviation it need MEAN value in every iteration of while loop for substact with Xi. so i think MEAN need before while loop iteration for find standard deviation.but i dont know how to do this or is there any way to do this. am getting stuck here. then i had puted code for replace old Xi with new Xi. and then write(generate) new csv file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.FileWriter;
import java.io.*;
import static java.lang.Math.sqrt;
public class Main {
public static void main(String[] args) throws IOException {
String filename = "ly.csv";
File file = new File(filename);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("bank-full_updated.csv"));
}
catch (IOException e) {
}
try {
double Tuple,avg;
double temp;
Tuple = 0;
double stddev=0;
Scanner inputStream = new Scanner(file);
inputStream.next();
while (inputStream.hasNext()) {
String data1 = inputStream.next();
String[] values = data1.split(";");
double Xi = Double.parseDouble(values[1]);
//now finding standard deviation
temp1 += (Xi-MEAN);
// temp2=(temp1*temp1);
// temp3=(temp2/count);
// standard deviation=Math.sqrt(temp3);
Xi=standard deviation * Xi
//now replace new Xi to original values1
values[1] = String.valueOf(Xi);
// iterate through the values and build a string out of them for write a new file
StringBuilder sb = new StringBuilder();
String newData = sb.toString();
for (int i = 0; i < values.length; i++) {
sb.append(values[i]);
if (i < values.length - 1) {
sb.append(";");
}
}
// get the new string
System.out.println(sb.toString());
writer.write(sb.toString()+"\n");
}
writer.close();
inputStream.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
It is possible to calculate the standard deviation in a single pass. Professor Donald Knuth has an algorithm that does it using the Kahan summation. Here is the paper: http://researcher.ibm.com/files/us-ytian/stability.pdf
Here is another way but it suffers from rounding errors:
double std_dev2(double a[], int n) {
if(n == 0)
return 0.0;
double sum = 0;
double sq_sum = 0;
for(int i = 0; i < n; ++i) {
sum += a[i];
sq_sum += a[i] * a[i];
}
double mean = sum / n;
double variance = sq_sum / n - mean * mean;
return sqrt(variance);
}
I'm trying to write a series of 10000 random integers to a text file using a byte stream, however once I open the text file up it has a collection of random characters which seemingly have little to do with the integer values I want to be shown. I'm new to this form of stream, I'm guessing that the integer values are being taken as byte values, but I can't think of a way to get round this.
My current attempt...
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
public class Question1ByteStream {
public static void main(String[] args) throws IOException {
FileOutputStream out = new FileOutputStream("ByteStream.txt");
try {
for(int i = 0; i < 10000; i ++){
Integer randomNumber = randInt(0, 100000);
int by = randomNumber.byteValue();
out.write(by);
}
}finally{
if (out != null) {
out.close();
}
}
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
Apologies if this lacks clarity.
It's because the numbers that you write are not written as strings into the txt but as raw byte value.
Try the following code:
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("./output.txt"));
writer.write(yourRandomNumberOfTypeInteger.toString());
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
Or, if referring to your original code, write the Integer directly:
try {
for(int i = 0; i < 10000; i ++){
Integer randomNumber = randInt(0, 100000);
out.write(randomNumber.toString());
}
}finally{
if (out != null) {
out.close();
}
}
dont do like below(writing in the form of byte characters)
for(int i = 0; i < 10000; i ++){
Integer randomNumber = randInt(0, 100000);
int by = randomNumber.byteValue();
out.write(by);
}
write it in the form of string as it is a text file
for(int i = 0; i < 10000; i ++){
Integer randomNumber = randInt(0, 100000);
out.write(randomNumber);
}
automatically toString() method will be called for Integer Object randomNumber
and it will be written to file.
I've submitted many solutions written in Java for this problem on ACM-ICPC Live archive. I followed, strictly all the instructions of writing Java solutions. I even installed JDK 6 on my IDE but I always get Runtime error, any idea what is throwing exception here 'cos I think I handled all exceptions.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
class Main {
BufferedReader read;
BufferedWriter write;
Integer D, N;
String U, S;
ArrayList<String> cryptex;
public static void main(String[] args) {
new Main().solve();
}
private void solve() {
read = new BufferedReader(new InputStreamReader(System.in));
write = new BufferedWriter(new OutputStreamWriter(System.out));
process();
try {
read.close();
write.flush();
write.close();
} catch (IOException ex) {
return;
}
}
private void process() {
try {
D = Integer.parseInt(read.readLine().trim());
} catch (IOException ex) {
return;
}
for (int i = 0; i < D; i++) {
try {
String[] params = read.readLine().trim().split("\\s+");
if (params.length != 3) {
return;
}
N = Integer.parseInt(params[0]);
U = params[1];
S = params[2];
cryptex = new ArrayList<String>(N);
for (int j = 0; j < N; j++) {
cryptex.add(read.readLine().trim());
}
try {
write.write(U + " " + solveCase());
} catch (Exception ex) {
return;
}
write.newLine();
read.readLine();
} catch (IOException ex) {
return;
}
}
}
private String solveCase() throws Exception {
Integer n = null, f = null, add = null;
for (int i = 0; i < N; i++) {
if (S.charAt(i) != '_') {
n = cryptex.get(i).indexOf(S.charAt(i));
f = cryptex.get(i).indexOf(U.charAt(i));
add = n - f;
break;
}
}
if (n == null || f == null || add == null) {
throw new Exception("Incorrect test case exception.");
}
char[] ret = S.toCharArray();
for (int i = 0; i < N; i++) {
f = cryptex.get(i).indexOf(U.charAt(i));
n = (add + f + 26) % 26;
ret[i] = cryptex.get(i).charAt(n);
}
return new String(ret);
}
}
Any idea on what I might be doing wrong?
In your process method, you call
D = Integer.parseInt(read.readLine().trim());
This is not optimal. Use a scanner.
Your line should look more like this:
Scanner sc = new Scanner(System.in);
//...
try {
D = sc.nextInt(); // Number of test cases
N = sc.nextInt(); // Rings
U = sc.next(); // Unlocking word
}
//...
Also, note that there will likely be more than one test case, so process() or some other method will need to be inside a for loop.