Error: Could not find or load main class AffineCipher - java

I am trying to create an encryption and decryption program but when I run there is an error. I tried to run my program on Intelli J ide, I also tried on Eclipse but also got the same error, where did I go wrong?
package com.sanfoundry.setandstring;
import java.util.Scanner;
public class AffineCipher
{
public static String encryptionMessage(String Msg)
{
String CTxt = "";
int a = 3;
int b = 6;
for (int i = 0; i < Msg.length(); i++)
{
CTxt = CTxt + (char) ((((a * Msg.charAt(i)) + b) % 26));
}
return CTxt;
}
public static String decryptionMessage(String CTxt)
{
String Msg = "";
int a = 3;
int b = 6;
int a_inv = 0;
int flag = 0;
for (int i = 0; i < 26; i++)
{
flag = (a * i) % 26;
if (flag == 1)
{
a_inv = i;
System.out.println(i);
}
}
for (int i = 0; i < CTxt.length(); i++)
{
Msg = Msg + (char) (((a_inv * ((CTxt.charAt(i) - b)) % 26)));
}
return Msg;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the message: ");
String message = sc.next();
System.out.println("Message is :" + message);
System.out.println("Encrypted Message is : "
+ encryptionMessage(message));
System.out.println("Decrypted Message is: "
+ decryptionMessage(message));
sc.close();
}
}

Related

Trouble receiving images from an 8 modem server

I have implemented this java app communicating with a remote 8 modem server and when I request for an image from a security camera (error free or not) the outcome is a 1 byte image (basically a small white square). Can you help me find the error?
Here is my code:
import java.io.*;
import java.util.Scanner;
import ithakimodem.Modem;
public class g {
private static Scanner scanner = new Scanner(System.in);
private static String EchoCode = "E3369";
private static String noImageErrorscode = "M2269";
private static String imageErrorsCode = "G6637";
private static String GPS_Code = "P7302";
private static String ACK_Code = "Q2591";
private static String NACK_Code = "R4510";
public static void main(String[] args) throws IOException, InterruptedException {
int timeout = 2000;
int speed = 80000;
Modem modem = new Modem(speed);
modem.setTimeout(timeout);
modem.write("ATD2310ITHAKI\r".getBytes());
getConsole(modem);
modem.write(("test\r").getBytes());
getConsole(modem);
while (true) {
System.out.println("\nChoose one of the options below :");
System.out.print("Option 0: Exit\n" + "Option 1: Echo packages\n" + "Option 2: Image with no errors\n" + "Option 3: Image with errors\n" + "Option 4: Tracks of GPS\n"
+ "Option 5: ARQ\n" );
System.out.print("Insert option : ");
int option = scanner.nextInt();
System.out.println("");
switch (option) {
case 0: {
// Exit
System.out.println("\nExiting...Goodbye stranger");
modem.close();
scanner.close();
return;
}
case 1: {
// Echo
getEcho(modem, EchoCode);
break;
}
case 2: {
// Image with no errors
getImage(modem, noImageErrorscode, "no_error_image.jpg");
break;
}
case 3: {
// Image with errors
getImage(modem, imageErrorsCode, "image_with_errors.jpg");
}
case 4: {
// GPS
getGPS(modem, GPS_Code);
break;
}
case 5: {
// ARQ
getARQ(modem, ACK_Code, NACK_Code);
break;
}
default:
System.out.println("Try again please\n");
}
}
}
public static String getConsole(Modem modem) {
int l;
StringBuilder stringBuilder= new StringBuilder();
String string = null;
while (true) {
try {
l = modem.read();
if (l == -1) {
break;
}
System.out.print((char) l);
stringBuilder.append((char) l);
string = stringBuilder.toString();
} catch (Exception exc) {
break;
}
}
System.out.println("");
return string;
}
private static void getImage(Modem modem, String password, String fileName) throws IOException {
int l;
boolean flag;
FileOutputStream writer = new FileOutputStream(fileName, false);
flag = modem.write((password + "\r").getBytes());
System.out.println("\nReceiving " + fileName + "...");
if (!flag) {
System.out.println("Code error or end of connection");
writer.close();
return;
}
while (true) {
try {
l = modem.read();
writer.write((char) l);
writer.flush();
if (l == -1) {
System.out.println("END");
break;
}
}
catch (Exception exc) {
break;
}
}
writer.close();
}
private static void getGPS(Modem modem, String password) throws IOException {
int rows = 99;
String Rcode = "";
Rcode = password + "R=10200" + rows;
System.out.println("Executing R parameter = " + Rcode + " (XPPPPLL)");
modem.write((Rcode + "\r").getBytes());
String stringConsole = getConsole(modem);
if (stringConsole == null) {
System.out.println("Code error or end of connection");
return;
}
String[] stringRows = stringConsole.split("\r\n");
if (stringRows[0].equals("n.a")) {
System.out.println("Error : Packages not received");
return;
}
System.out.println("**TRACES**\n");
float l1 = 0, l2 = 0;
int difference = 8;
difference *= 100 / 60;
int traceNumber = 7;
String[] traces = new String[traceNumber + 1];
int tracesCounter = 0, flag = 0;
for (int i = 0; i < rows; i++) {
if (stringRows[i].startsWith("$GPGGA")) {
if (flag == 0) {
String str = stringRows[i].split(",")[1];
l1 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
flag = 1;
}
String str = stringRows[i].split(",")[1];
l2 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
if (Math.abs(l2 - l1) >= difference) {
traces[tracesCounter] = stringRows[i];
if (tracesCounter == traceNumber)
break;
tracesCounter++;
l1 = l2;
}
}
}
for (int i = 0; i < traceNumber; i++) {
System.out.println(traces[i]);
}
String w = "", T_cd_fnl = password + "T=";
int p = 1;
System.out.println();
for (int i = 0; i < traceNumber; i++) {
String[] strSplit = traces[i].split(",");
System.out.print("T parameter = ");
String str1 = strSplit[4].substring(1, 3);
String str2 = strSplit[4].substring(3, 5);
String str3= String.valueOf(Integer.parseInt(strSplit[4].substring(6, 10)) * 60 / 100).substring(0, 2);
String str4= strSplit[2].substring(0, 2);
String str5= strSplit[2].substring(2, 4);
String str6= String.valueOf(Integer.parseInt(strSplit[2].substring(5, 9)) * 60 / 100).substring(0, 2);
w = str1 + str2 + str3 + str4 + str5 + str6 + "T";
p = p + 5;
System.out.println(w);
T_cd_fnl = T_cd_fnl + w + "=";
}
T_cd_fnl = T_cd_fnl.substring(0, T_cd_fnl.length() - 2);
System.out.println("\nSending code: " + T_cd_fnl);
getImage(modem, T_cd_fnl, "traces GPS.jpg");
}
private static void getEcho(Modem modem, String strl) throws InterruptedException, IOException {
FileOutputStream echo_time_writer = new FileOutputStream("echoTimes.txt", false);
FileOutputStream echo_counter_writer = new FileOutputStream("echoCounter.txt", false);
int h;
int runtime = 5, packetCounter = 0;
String str = "";
System.out.println("\nRuntime (mins) = " + runtime + "\n");
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receiveTime = 0;
String time = "", ClockTime = "";
echo_time_writer.write("Clock Time\tSystem Time\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
packetCounter++;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
while (true) {
try {
h = modem.read();
System.out.print((char) h);
str += (char) h;
if ( h== -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (str.endsWith("PSTOP")) {
receiveTime = System.currentTimeMillis();
ClockTime = str.substring(18, 26) + "\t";
time = String.valueOf((receiveTime - send_time) + "\r\n");
echo_time_writer.write(ClockTime.getBytes());
echo_time_writer.write(time.getBytes());
echo_time_writer.flush();
str = "";
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
}
echo_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
echo_counter_writer.write(("\r\nPackets Received: " + String.valueOf(packetCounter)).getBytes());
echo_counter_writer.close();
echo_time_writer.close();
}
private static void getARQ(Modem modem, String strl, String nack_code) throws IOException, InterruptedException {
FileOutputStream arq_time_writer = new FileOutputStream("ARQtimes.txt", false);
FileOutputStream arq_counter_writer = new FileOutputStream("ARQcounter.txt", false);
int runtime = 5;
int xor = 1;
int f = 1;
int m;
int packageNumber = 0;
int iterationNumber = 0;
int[] nack_times_counter = new int[15];
int nack_to_package = 0;
String time = "", clock_time = "", s = "";
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receive_time = 0;
System.out.printf("Runtime (mins) = " + runtime + "\n");
arq_time_writer.write("Clock Time\tSystem Time\tPacket Resends\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
if (xor == f) {
packageNumber++;
nack_times_counter[nack_to_package]++;
nack_to_package = 0;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
} else {
iterationNumber++;
nack_to_package++;
modem.write((nack_code + "\r").getBytes());
}
while (true) {
try {
m = modem.read();
System.out.print((char) m);
s += (char) m;
if (m == -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (s.endsWith("PSTOP")) {
receive_time = System.currentTimeMillis();
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
String[] string = s.split("<");
string = string[1].split(">");
f = Integer.parseInt(string[1].substring(1, 4));
xor = string[0].charAt(0) ^ string[0].charAt(1);
for (int i = 2; i < 16; i++) {
xor = xor ^ string[0].charAt(i);
}
if (xor == f) {
System.out.println("Packet ok");
receive_time = System.currentTimeMillis();
time = String.valueOf((receive_time - send_time) + "\t");
clock_time = s.substring(18, 26) + "\t";
arq_time_writer.write(clock_time.getBytes());
arq_time_writer.write(time.getBytes());
arq_time_writer.write((String.valueOf(nack_to_package) + "\r\n").getBytes());
arq_time_writer.flush();
} else {
xor = 0;
}
s = "";
}
arq_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
arq_counter_writer.write("\r\nPackets Received (ACK): ".getBytes());
arq_counter_writer.write(String.valueOf(packageNumber).getBytes());
arq_counter_writer.write("\r\nPackets Resent (NACK): ".getBytes());
arq_counter_writer.write(String.valueOf(iterationNumber).getBytes());
arq_counter_writer.write("\r\nNACK Time Details".getBytes());
for (int i = 0; i < nack_times_counter.length; i++) {
arq_counter_writer.write(("\r\n" + i + ":\t" + nack_times_counter[i]).getBytes());
}
arq_counter_writer.close();
arq_counter_writer.close();
System.out.println("Packets Received: " + packageNumber);
System.out.println("Packets Resent: " + iterationNumber);
System.out.println("\n\nFile arqTimes.txt is created.");
System.out.println("File arqCounter.txt is created.");
}
}
I know the problem is most probably in the getImage() function but I haven't figured it out yet.

Accuracy of Multi Layer Neural Network using Backpropagation around 86% normal?

Recently, I started trying to train a neural network using backpropagation. The network structure is 784-512-10, and I used the Sigmoid activation function. When I tested a single-layer network on the MNIST dataset, I got around 90%. My results are around 86% with this multi-layer network, is this normal? Did I get the backpropagation part wrong?
Here is my code:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class NeuralNetwork{
public static double learningRate = 0.01;
public static int epoch = 15;
public static int ROWS = 28;
public static int COLUMNS = 28;
public static int INPUT = ROWS * COLUMNS;
public static int outNum = 10;
public static int hiddenNum = 512;
public static double[][] weights2 = new double[outNum][hiddenNum];
public static double[] bias2 = new double[outNum];
public static double[][] weights1 = new double[hiddenNum][INPUT];
public static double[] bias1 = new double[outNum];
private static final double TRAININGSIZE = 10;
public static double[][] inputs = new double[outNum][INPUT];
private static final double[][] target = new double[outNum][outNum];
private static final ArrayList<String> filenames = new ArrayList<>();
private static final ArrayList<Integer> yetDone = new ArrayList<>();
public static double[] actual = new double[outNum];
public static Random rand = new SecureRandom();
public static Scanner input = new Scanner(System.in);
public static void main(String[]args) throws Exception {
System.out.println("1. Learn the network");
System.out.println("2. Guess a number");
System.out.println("3. Guess file");
System.out.println("4. Guess All Numbers");
System.out.println("5. Guess image");
switch (input.nextInt()){
case 1:
learn();
break;
case 2:
guess();
break;
case 3:
guessFile();
break;
case 4:
guessAll();
break;
}
}
public static void guessAll() throws IOException, ClassNotFoundException {
System.out.println("Recognizing...");
/*
for(int x = 1; x < 60000; x++){
filenames.add("data/" + String.format("%05d",x) + ".txt");
}
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("network.ser")));
Layers lay = (Layers) ois.readObject();
int correct = 0;
for (String z : filenames) {
double[] a = scan(z,0);
correct += getBestGuess(sigmoid(lay.step(a))) == actual[0] ? 1 : 0;
}
System.out.println("Training: " + correct + " / " + filenames.size() + " correct.");
filenames.clear();
*/
for(int x = 60000; x < 70000; x++){
filenames.add("data/" + String.format("%05d",x) + ".txt");
}
ObjectInputStream oiss = new ObjectInputStream(new BufferedInputStream(new FileInputStream("network1.ser")));
Layers lays1 = (Layers) oiss.readObject();
ObjectInputStream oiss2 = new ObjectInputStream(new BufferedInputStream(new FileInputStream("network2.ser")));
Layers lays2 = (Layers) oiss2.readObject();
int corrects = 0;
for (String z : filenames) {
double[] a = scan(z,0);
corrects += getBestGuess(sigmoid(lays2.step(sigmoid(lays1.step(a))))) == actual[0] ? 1 : 0;
}
System.out.println("Testing: " + corrects + " / " + filenames.size() + " correct.");
System.out.println("Done!");
}
public static void makeList(){
for(int index = 0; index < TRAININGSIZE; index++){
int indices = rand.nextInt(yetDone.size() - 1) + 1;
filenames.add("data/" + String.format("%05d",yetDone.get(indices)) + ".txt");
yetDone.remove(indices);
}
prepareData();
for(int indices = 0; indices < outNum; indices++) {
for(int index = 0; index < outNum; index++){
target[indices][index] = 0;
}
target[indices][(int)actual[indices]] = 1;
}
}
public static void prepareData(){
for(int index = 0; index < outNum; index++){
try {
inputs[index] = scan(filenames.get(index), index);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
public static double[] scan(String filename, int index) throws FileNotFoundException {
Scanner in = new Scanner(new File(filename));
double[] a = new double[INPUT];
for(int i = 0; i < INPUT; i++){
a[i] = in.nextDouble() / 255;
}
actual[index] = in.nextDouble();
return a;
}
public static void guessFile() throws IOException, ClassNotFoundException {
System.out.print("Enter Filename: ");
double[] a = scan(input.next(), 0);
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("network.ser")));
Layers lay = (Layers) ois.readObject();
double[] results = lay.step(a);
System.out.println("This is a " + getBestGuess(sigmoid(results)) + "!");
System.out.println(Arrays.toString(results));
}
public static double guess(double[] a) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("network.ser")));
Layers lay = (Layers) ois.readObject();
double[] results = lay.step(a);
return getBestGuess(sigmoid(results));
}
public static void guess() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("network.ser")));
System.out.println("Input number: ");
Layers lay = (Layers) ois.readObject();
double[] a = new double[INPUT];
for(int index = 0; index < a.length; index++){
a[index] = input.nextInt();
}
double[] results = lay.step(a);
System.out.println("This is a " + getBestGuess(sigmoid(results)) + "!");
System.out.println(Arrays.toString(sigmoid(results)));
}
public static void learn() {
System.out.println("Learning...");
initialise(weights2, outNum, hiddenNum);
initialise(bias2);
initialise(weights1,hiddenNum, INPUT);
initialise(bias1);
Layers lay2 = new Layers(weights2, bias2, outNum, hiddenNum);
Layers lay1 = new Layers(weights1, bias1, hiddenNum, INPUT);
double[] result2 = new double[lay2.outNum];
double[] result1 = new double[lay1.outNum];
double[] a2;
double[] a1;
double cost = 0;
double sumFinal;
for(int x = 0; x < epoch; x++) {
yetDone.clear();
for(int y = 0; y < 60000; y++){
yetDone.add(y);
}
for (int ind = 0; ind < 200; ind++) {
filenames.clear();
makeList();
for (int n = 0; n < lay2.outNum; n++) {
a1 = inputs[n]; //number
result1 = sigmoid(lay1.step(a1));
a2 = result1;
result2 = sigmoid(lay2.step(a2));
for (int i = 0; i < lay2.outNum; i++) {
for (int j = 0; j < lay2.INPUT; j++) {
weights2[i][j] += learningRate * a2[j] * (target[n][i] - result2[i]);
cost += Math.pow((target[n][i] - result2[i]), 2);
}
}
for(int i = 0; i < lay1.outNum; i++){
for(int j = 0; j < lay1.INPUT; j++){
sumFinal = 0;
for(int k = 0; k < lay2.outNum; k++){
// weight * derivSigma(outputHiddenLayer) * 2(out - expected)
sumFinal += result1[k] * (1 - result1[k]) * 2 * (result2[k] - target[n][k]); // * weights2[k][i]
}
weights1[i][j] -= learningRate * a1[j] * sumFinal * result1[i] * (1 - result1[i]);
}
}
}
lay1.update(weights1, bias1);
lay2.update(weights2, bias2);
}
System.out.println("Epoch " + x + ": " + cost);
cost = 0;
}
System.out.println(Arrays.toString(result1));
System.out.println(Arrays.toString(result2));
for(double[] arr : inputs) {
System.out.println("This is a " + getBestGuess(sigmoid(lay2.step(sigmoid(lay1.step(arr))))) + "!");
}
try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("network1.ser")))) {
oos.writeObject(lay1);
} catch (IOException ex) {
ex.printStackTrace();
}
try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("network2.ser")))) {
oos.writeObject(lay2);
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println("Done! Saved to file.");
}
public static double sigmoid(double x){
return 1 / (1 + Math.exp(-x));
}
public static double[] sigmoid(double[] weights){
for(int index = 0; index < weights.length; index++){
weights[index] = sigmoid(weights[index]);
}
return weights;
}
public static void initialise(double[] bias){
Random random = new Random();
for(int index = 0; index < bias.length; index++){
bias[index] = random.nextGaussian();
}
}
public static void initialise(double[][] weights, int outNum, int INPUT){
Random random = new Random();
for(int index = 0; index < outNum; index++){
for(int indice = 0; indice < INPUT; indice++){
weights[index][indice] = random.nextGaussian();
}
}
}
public static int getBestGuess(double[] result){
double k = Integer.MIN_VALUE;
double index = 0;
int current = 0;
for(double a : result){
if(k < a){
k = a;
index = current;
}
current++;
}
return (int)index;
}
}
class Layers implements Serializable {
private static final long serialVersionUID = 8L;
double[][] weights;
double[] bias;
int outNum;
int INPUT;
public Layers(double[][] weights, double[] bias, int outNum, int INPUT){
this.weights = weights;
this.bias = bias;
this.outNum = outNum;
this.INPUT = INPUT;
}
public void update(double[][] weights, double[] bias){
this.weights = weights;
this.bias = bias;
}
public double[] step(double[] aa){
double[] out = new double[outNum];
for (int index = 0; index < outNum; index++) {
for (int indices = 0; indices < INPUT; indices++) {
out[index] += weights[index][indices] * aa[indices];
}
}
return out;
}
}
Thanks in advance!

How can I take the length from the text files in java?

I am new in java. Firstly, I'm sorry for my English. I wrote a code to merge two different txt files in the mergedFile.txt with determined data from the data1.txt and data2.txt. I create 5 different arrays to use them better but I cannot learn the length of words in the textfiles so arrays are using determined parameter. If I want to add another student, this codes don't work. Can you help me?
data1.txt
ID,Name,LastName,Department
12345,John,Samon,Computer Science
14524,David,Souza,Electric and Electronic
.
.
data2.txt
ID,Q1,Q2,Q3,Midterm,Final
12345,100,90,75,89,100
14524,80,70,65,15,90
.
margedFile.txt
ID,Name,Q_Average,Midterm,Final,Department
12345,John,88.3,89,100,Computer Science
14524,David,67.0,100,70,Electric and Electronic
This is ReadData Class
import java.io.FileInputStream;//import java.io library
import java.util.Scanner;//import scanner library
public class ReadData {
public static String[] Read(String filename,String filename2) {
Scanner scan = null;
Scanner scan1 = null;/
FileInputStream input1 = null;
FileInputStream input = null;
String[] result = new String[3];
try {
input = new FileInputStream(filename);
scan = new Scanner(input);
input1 = new FileInputStream(filename2);
scan1 = new Scanner(input1);
String[][] myArray = new String[4][4];
String[][] myArray1 = new String[4][6];
while(scan.hasNext() || scan1.hasNext()) {
for (int i = 0; i < myArray.length; i++) {
String[] split =
scan.nextLine().trim().split(",");
for (int j = 0; j < split.length; j++)
{
myArray[i][j] = split[j];
}
}
for (int i = 0; i < myArray1.length; i++) {
String[] split1 = scan1.nextLine().trim().split(",");
for (int j = 0; j < split1.length; j++) {
myArray1[i][j] = split1[j];
}
}
}
int[][] quiz = new int[3][3];
double[] average = new double[3];
int sum = 0;
double averagee = 0;
for (int i = 0; i < quiz.length; i++) {
for (int j = 0; j < quiz.length; j++) {
quiz[i][j] = Integer.parseInt(myArray1[i+1][j+1]);
sum += quiz[i][j];
}
averagee = sum/quiz.length;
average[i] = averagee;
sum = 0;
}
for (int i = 1; i < myArray1.length; i++) {
for (int j = 1; j < myArray1.length; j++) {
if(myArray[i][0].equalsIgnoreCase(myArray1[j][0])) {
result[i-1] = "\n" + myArray[i][0] + " "+ myArray[i][1] + " " + (average[j-1]) +" "+ myArray1[j][4] +" " + myArray1[j][5] + " "+ myArray[i][3];
//System.out.println(Arrays.deepToString(myArray[i]) + " " + Arrays.deepToString(myArray1[j]));
}
}
}
//System.out.println(Arrays.deepToString(quiz));
//System.out.println(Arrays.toString(average));
}
catch(Exception e) {
System.out.println(e);
}
return result;
}
}
This is WriteData class
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
public class WriteData extends ReadData {
void Write(String filename) {
PrintWriter writer = null;
FileOutputStream output = null;
try {
output = new FileOutputStream(filename);
writer = new PrintWriter(output);
writer.print("ID,Name,Q_Average,Midterm,Final,Department ");
writer.print(Arrays.toString(Read("data1.txt",
"data2.txt")));
writer.flush();
writer.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}

running time error when trying to implent a keyword frequency counter in my parser java

I want to implement my input reading method into my main class, I want use my code to parse. It's been fixed now. thanks.
String x;
int count = -1;=
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
}
}
private List<String[]> termsDocsArray = new ArrayList<String[]>();
private List<String> allTerms = new ArrayList<String>(); //to hold all terms
private List<double[]> tfidfDocsVector = new ArrayList<double[]>();
/**
To start with your code
String text = "Professor, engineering, data, mining, research";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String x;
int count = -1;
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
should be in it's own method like .
private void doSomething(){
//This variable will hold all terms of each document in an array.
String text = "Professor, engineering, data, mining, research";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String x;
int count = -1;
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
}
Secondly in ur given code u have written like
int count = -1;=
which accounts to this error Syntax error on token "=", { expected.It should be
int count = -1;
And since all your code is simply written in class without any method so it is giving you the error saying { expected.
Please make sure you have copied the code correctly.

Reading a text file using Java throws IOException

I have compiled my Java with no error , However, when I want to use the java to read the text , it shows the following error :
java countwords Chp_0001.txt <-- this is my action
Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(BufferedReader.java:122)
at java.io.BufferedReader.read(BufferedReader.java:179)
at countwords.readFile_BSB(assignment.java:164)
at countwords.main(assignment.java:53)
The following is my input of Java :
import java.util.*;
import java.io.*;
class countwords {
public static String [] MWTs ={ "Hong Kong","New York",
"United Kingdom","Basic Law","People's Republic of China",
};
public static void bubble_sort_length(String [] strs){
while (true) {
int swaps = 0;
for (int i = 0 ; i<strs.length -1; i++) {
if (strs[i].length() >= strs[i+1].length())
continue ;
String tmp = strs[i];
strs[i] = strs[i+1];
strs [i+1] = tmp;
swaps++;
}
if (swaps ==0) break ;
}
}
public static void main(String[] args) throws IOException {
String txt=readFile_BSB(args [0]);
bubble_sort_length(MWTs);
txt= underscoreMWTs(txt);
for (int i = 0 ; i < MWTs.length;i++)
System.out.println(i + "-->" + MWTs[i]) ;
System.out.print (txt);
String [] words = txt.split("\\s+");
StringBuilder txt_p = new StringBuilder();
for (String w : words){
txt_p.append(sep_punct(w));
}
words = txt_p.toString().split("\\s+");
Arrays.sort (words);
String w ="";
int cnt =0;
StringBuilder all_lines = new StringBuilder();
for(int i = 0;i < words.length;i++){
if (w.equals(words[i])){
cnt++ ;
} else {
if(!w.equals("")) {
if (w.contains("_")) {
String u = de_underscore (w) ;
if(isMWT (u)) w = u ;
}
all_lines.append (addSpaces(cnt) + " " + w + "\r\n");
}
w=words[i];
cnt=1;
}
}
String [] lines = all_lines.toString().split ("\r\n");
Arrays.sort(lines);
for (int i= lines.length-1;i>= 0 ; i--) {
System.out.println(lines[i]);
}
}
public static boolean isPunct(char c){
return ",.':;\"!)?_#(#".contains(""+c);
}
public static String sep_punct( String w ) {
StringBuilder W= new StringBuilder(w);
String init_puncts = "",end_puncts="";
char c;
while (W.length() > 0) {
c =W.charAt(0);
if (!isPunct(c)) break;
W.deleteCharAt(0);
init_puncts +="" + c + " ";
}
while (W.length() > 0) {
c= W.charAt(W.length () -1);
if (!isPunct(c)) break;
W.deleteCharAt (W.length()-1);
end_puncts += "" +c+"";
}
return "" + init_puncts + W.toString() + end_puncts +"";
}
public static String underscoreMWTs(String txt){
StringBuilder TXT = new StringBuilder(txt);
for(String mwt : MWTs ) {
int pos =0 ;
while ((pos =TXT.indexOf(mwt,pos)) !=-1) {
pos += mwt.length();
}
}
return TXT.toString();
}
public static void space2underscore (StringBuilder sb, int pos, int lgth){
for (int p = pos; p < pos+lgth; p++ ){
if (sb.charAt(p) ==' ')
sb.setCharAt(p,'_');
}
}
public static String de_underscore(String w) {
StringBuilder W = new StringBuilder (w);
for (int i= 0 ; i < W.length(); i++ ) {
if ( W.charAt (i) == '_')
W.setCharAt (i ,' ');
}
return W.toString ();
}
public static boolean isMWT (String w) {
for (String t : MWTs) {
if (w.equals(t)) return true;
}
return false;
}
public static String addSpaces (int cnt) {
String s ="" + cnt;
while (s.length () <10 ) {
s=" " + s;
}
return s;
}
public static String readFile_BSB(String fn) throws IOException{
FileReader fr= new FileReader(fn);
BufferedReader r= new BufferedReader (fr);
StringBuilder s= new StringBuilder();
int c;
while ((c = r.read()) != -1) {
s.append ((char)c);
r.close();
}
return s.toString();
}
}
Please help me with the errors as I am quite hopeless at this point .
Thank You so much !
Check your loop in readFile_BSB():
BAD
while ((c = r.read()) != -1) {
s.append ((char)c);
r.close(); // Close while reading?
}
BETTER
while ((c = r.read()) != -1) {
s.append ((char)c);
}
r.close(); // Close after reading.
Why not good? Reading byte by byte is very slow, in case of Exception your streams are not closed...

Categories