Can't get replace to work - java

I am making a program that will help me convert DFA to a regular expression using an algorithm we learned at the course.
CODE:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Collections;
import java.util.regex.Pattern;
import java.util.Arrays;
import java.io.*;
public class DFK {
static ArrayList<Path> done = new ArrayList<Path>();
public static void print() {
for(Path i: done) {
System.out.println("NOT REPLACED: "+ i);
if(i.isConverted()) {
System.out.println("WITH REPLACE: "+ i.getConverted()+"\n");
} else
System.out.print("\n");
}
}
public static void develop() {
if(done.get(0).getKP1() > 0) {
DFK.add(new Path(done.get(0).getP(), done.get(0).getQ(), done.get(0).getK()));
DFK.add(new Path(done.get(0).getP(), done.get(0).getKP1(), done.get(0).getK()));
DFK.add(new Path(done.get(0).getKP1(), done.get(0).getKP1(), done.get(0).getK()));
DFK.add(new Path(done.get(0).getKP1(), done.get(0).getQ(), done.get(0).getK()));
}
}
public static void add(Path x) {
boolean exists = (done.indexOf(x)==-1 ? false : true);
if(exists == false) {
done.add(x);
if(x.getKP1() >= 2) {
DFK.add(new Path(x.getP(), x.getQ(), x.getK()));
DFK.add(new Path(x.getP(), x.getKP1(), x.getK()));
DFK.add(new Path(x.getKP1(), x.getKP1(), x.getK()));
DFK.add(new Path(x.getKP1(), x.getQ(), x.getK()));
}
}
}
public static void main(String argv[]) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int p = 0, q = 0, kp1 = 0;
Scanner in = new Scanner(System.in);
System.out.print("p = ");p = in.nextInt();
System.out.print("q = ");q = in.nextInt();
System.out.print("k+1 = ");kp1 = in.nextInt();
System.out.print("\n");
String rkzero[][] = new String[q][q];
for(int i=0; i<q ; i++) {
for(int j=0; j<q ; j++) {
System.out.print(String.format("r(%d,%d,0): ", i+1, j+1));
rkzero[i][j]=input.readLine();
}
}
done.add(new Path(p, q, kp1));
DFK.develop();
Collections.sort(done);
for(int z=0; z<q ; z++) {
for(int j=0; j<q ; j++) {
for(Path i: done)
if(i.getKP1()==1) {
String reg = String.format("r(%d,%d,0)",z+1,j+1); //
i.setConverted(i.toString().replace( reg , rkzero[z][j])); //HERE IS THE PROBLEM I THINK
}
}
}
System.out.print("\n");
DFK.print();
}
}
class Path implements Comparable<Path> {
int p,q,kplus1,k;
String converted = null;
public int getP() {
return p;
}
public int getQ() {
return q;
}
public int getKP1() {
return kplus1;
}
public int getK() {
return k;
}
public Path(int a, int b, int c) {
super();
p = a;
q = b;
kplus1 = c;
k = c-1;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!Path.class.isAssignableFrom(obj.getClass())) {
return false;
}
final Path other = (Path) obj;
if(other.p == this.p && other.q == this.q && other.kplus1 == this.kplus1)
return true;
return false;
}
public int compareTo(Path other) {
return other.kplus1-kplus1;
}
public String toString() {
return String.format("r(%d,%d,%d)=r(%d,%d,%d)+r(%d,%d,%d)r(%d,%d,%d)*r(%d,%d,%d)",p,q,kplus1,p,q,k,p,kplus1,k,kplus1,kplus1,k,kplus1,q,k);
}
public void setConverted(String x) {
converted = new String(x);
}
public String getConverted() {
return converted;
}
public boolean isConverted() {
if(converted == null)
return false;
return true;
}
}
CURRENT OUTPUT:
p = 1
q = 2
k+1 = 2
r(1,1,0): 0
r(1,2,0): 1
r(2,1,0): 1
r(2,2,0): 0
NOT REPLACED: r(1,2,2)=r(1,2,1)+r(1,2,1)r(2,2,1)*r(2,2,1)
NOT REPLACED: r(1,2,1)=r(1,2,0)+r(1,1,0)r(1,1,0)*r(1,2,0)
WITH REPLACE: r(1,2,1)=r(1,2,0)+r(1,1,0)r(1,1,0)*r(1,2,0)
NOT REPLACED: r(2,2,1)=r(2,2,0)+r(2,1,0)r(1,1,0)*r(1,2,0)
WITH REPLACE: r(2,2,1)=0+r(2,1,0)r(1,1,0)*r(1,2,0)
WANTED OUTPUT:
p = 1
q = 2
k+1 = 2
r(1,1,0): 0
r(1,2,0): 1
r(2,1,0): 1
r(2,2,0): 0
NOT REPLACED: r(1,2,2)=r(1,2,1)+r(1,2,1)r(2,2,1)*r(2,2,1)
NOT REPLACED: r(1,2,1)=r(1,2,0)+r(1,1,0)r(1,1,0)*r(1,2,0)
WITH REPLACE: r(1,2,1)=1+00*1
NOT REPLACED: r(2,2,1)=r(2,2,0)+r(2,1,0)r(1,1,0)*r(1,2,0)
WITH REPLACE: r(2,2,1)=0+10*1
As you can see it only replaces r(2,2,0) with 0, and nothing else and I cant find out why. I replicated the problem in a previous question, but it turned out there was a non-ascii comma in my code there which caused the issue, but here I can't find it.
I used grep --color='auto' -P -n "[^\x00-\x7F]" DFK.java and it didn't find any non ascii characters, so I hope it's not the same problem.
The program should iterate over all Paths that have kplus1 = 1 and replace all r(i,j,0) with strings I have previously entered. Keep in mind, it is not finished yet.

The mistake is I was using toString to get the string in which I replace things, and so I replace one string and for the next replacement I use the original string again and thus throwing away the last replacement and so on.
So the solution is to make converted initialize as the same string as toString() inside constructor:
converted = String.format("r(%d,%d,%d)=r(%d,%d,%d)+r(%d,%d,%d)r(%d,%d,%d)*r(%d,%d,%d)",p,q,kplus1,p,q,k,p,kplus1,k,kplus1,kplus1,k,kplus1,q,k);
and then in main use:
i.setConverted( i.getConverted().replace(reg, rkzero[z][j]) );
so I save the intermediate solution in converted.

Related

whenever try to push onto stack gives error in java null pointer exception

In this code as user enters string it is pushed onto stack and if "-" appears then previous string is popped out and when the stack becomes empty then loop execution stops.
Whenever I try to push onto stack null pointer exception is there.
import java.util.Scanner;
import java.util.*;
public class StackArray {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
StackArrayModel stack = new StackArrayModel();
while (true) {
String data = scan.next();
if (data.equals("-")) {
if (stack.isEmpty() == false)
System.out.println(stack.pop());
else
break;
} else {
stack.push(data);
}
}
}
}
// creating resizable array stack
class StackArrayModel {
String[] s;
int n = 0;
public void StackArrayModel() {
s = new String[1];
}
public boolean isEmpty() {
return n == 0;
}
public void push(String item) {
if (n == s.length) {
resize(s.length * 2);
}
s[n++] = item;
}
private void resize(int capacity) {
String[] copy = new String[capacity];
for (int i = 0; i < s.length; i++) {
copy[i] = s[i];
}
s = copy;
}
public String pop() {
if (n > 0 && n == s.length / 4)
resize(s.length / 2);
String item = s[--n];
s[n] = null;
return item;
}
}
The error is in StackArrayModel class. You didn't overwrite the default constructor, because you added a void there.
public void StackArrayModel(){
s = new String[1] ;
}
should be changed to following so it overwrites the default constructor:
public StackArrayModel(){
s = new String[1] ;
}
Once you did that, you've overwritten the default constructor, and your code should work just fine.

StackOverFlowError in java program [duplicate]

This question already has answers here:
What is a StackOverflowError?
(16 answers)
Closed 7 years ago.
I am trying to solve a problem which asks to find the smallest prime palindrome, which comes after a given number which means that if the input is 24, the output would be 101 as it is the smallest number after 24 which is both prime and a palindrome.
Now my code works perfectly for small values but the moment I plug in something like 543212 as input, I end up with a StackOverFlowError on line 20, followed by multiple instances of StackOverFlowErrors on line 24. Here is my code :
package nisarg;
import java.util.Scanner;
public class Chef_prime_palindromes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = input.nextLong();
isPalindrome(num + 1);
}
public static boolean isPrime(long num) {
long i;
for (i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void isPalindrome(long num) {
String word = Long.toString(num);
int i;
for (i = 0; i < word.length() / 2; i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
isPalindrome(num + 1);
}
}
if (i == word.length() / 2) {
if (isPrime(num)) {
System.out.println(num);
System.exit(0);
} else {
isPalindrome(num + 1);
}
}
}
}
All shown exiting solutions use recursion and have the problem that at some point they will reach the point where a StackOverflowException will occur.
A better solution which would also be parallelizable would be to change it into a loop.
It could be something like:
package nisarg;
import java.math.BigInteger;
import java.util.Scanner;
import java.util.concurrent.CopyOnWriteArrayList;
public class Chef_prime_palindromes {
private static final CopyOnWriteArrayList<BigInteger> PRIMESCACHE
= new CopyOnWriteArrayList<>();
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
BigInteger num = new BigInteger(input.nextLine());
initPrimes(num);
for (num = num.add(BigInteger.ONE);
!isPrimePalindrome(num);
num = num.add(BigInteger.ONE));
System.out.println(num.toString());
}
}
private static void initPrimes(BigInteger upTo) {
BigInteger i;
for (i = new BigInteger("2"); i.compareTo(upTo) <= 0 ; i = i.add(BigInteger.ONE)) {
isPrime(i);
}
}
public static boolean isPrimePalindrome(BigInteger num) {
return isPrime(num) && isPalindrome(num);
}
// could be optimized
public static boolean isPrime(BigInteger num) {
for (int idx = PRIMESCACHE.size() - 1; idx >= 0; --idx) {
if (num.mod(PRIMESCACHE.get(idx)).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
if (!PRIMESCACHE.contains(num)) {
PRIMESCACHE.add(num);
}
return true;
}
public static boolean isPalindrome(BigInteger num) {
String word = num.toString();
int i;
for (i = 0; i < word.length() / 2; i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
return false;
}
}
return true;
}
}
A new String object is created in each recursive call and placed onto stack (the place where all variables created in methods are stored until you leave the method), which for a deep enough recursion makes JVM reach the end of allocated stack space.
I changed the locality of the String object by placing it into a separate method, thus reducing its locality and bounding its creation and destruction (freeing of stack space) to one recursive call.
package com.company;
import java.util.Scanner;
public class Chef_prime_palindromes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = input.nextLong();
isPalindrom(num + 1);
}
public static boolean isPrime(long num) {
long i;
for (i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
private static void isPalindrom(long num) {
for (; ; ) {
if (isPalindrome(num)) {
if (isPrime(num)) {
System.out.println(num);
System.exit(0);
} else {
num++;
}
} else {
num++;
}
}
}
public static boolean isPalindrome(long num) {
String string = String.valueOf(num);
return string.equals(new StringBuilder(string).reverse().toString());
}
}
First thing you should be aware of is the fact that your resources are limited. Even if your implementation was precise and all recursive calls were correct, you may still get the error. The error indicates your JVM stack ran out of space. Try to increase the size of your JVM stack ( see here for details).
Another important thing is to look for the distribution of prime and palindrome numbers. Your code runs by testing every num+1 against palindrome property. This is incorrect. You test for palindrome only when the number is prime. This will make the computation much much easier (and reduce recursive calls). I have edited your code accordingly and got the closest palindrome number after 543212 (1003001) . Here it is:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = input.nextLong();
//isPalindrome(num+1);
nextPrimePalindrome(num+1);
}
public static void nextPrimePalindrome(long num)
{
boolean flag=true;
while(flag)
{
if(isPrime(num))
if(isPalindrome(num))
{
System.out.println(num);
flag=false;
}
num++;
}
}
public static boolean isPrime(long num){
long i;
for(i=2;i<num;i++){
if(num%i == 0){
return false;
}
}
return true;
}
public static boolean isPalindrome(long num)
{
String word=Long.toString(num);
for(int i=0;i<word.length()/2;i++)
if(word.charAt(i)!=word.charAt(word.length()-i-1))
return false;
return true;
}
}

How to print the first 10 lines from an enhanced for loop

I have a file with over 1000 names it also include the sex and how many people have the name.
example
Sarah F 2000
I am trying to print the first 10 lines that was created from my for loop, but for some reason what i tried is only printing the last line 10 times.
import java.util.*;
import java.io.*;
import java.util.Collections;
public class NameYear
{
private String year;
ArrayList<OneName> oneName = new ArrayList<OneName>();
public NameYear(String year)
{
String line = "";
String Top = "";
Scanner sc = null;
try
{
sc = new Scanner(new File
("/home/mathcs/courses/cs225/koch/names/yob"+year+".txt"));
}
catch (Exception e)
{
System.out.println("Error Year should be between 1880 and 2013 not "+ year);
System.exit(1);
}
while(sc.hasNextLine())
{
// read a line from the input file via sc into line
line = sc.nextLine();
StringTokenizer stk = new StringTokenizer(line, ",");
String name = stk.nextToken();
char sex = stk.nextToken().charAt(0);
int count = Integer.parseInt(stk.nextToken());
OneName list = new OneName(name, sex, count);
oneName.add(list);
}
for (int i = 0 ; i < 10; i++)
{
System.out.println(descending());
}
public String descending()
{
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName)
{
x = b.toString();
}
return x;
OneName file
public class OneName
{
private String Name;
private char Sex;
private int Count;
public OneName(String name, char sex, int count)
{
Name = name;
Sex = sex;
Count = count;
}
public String getName()
{
return Name;
}
public char getSex()
{
return Sex;
}
public int getCount()
{
return Count;
}
public void setName(String name)
{
if (name.length() < 1)
{
throw new NullPointerException("Baby name is missing");
}
Name = name;
}
private char M;
private char F;
public void setSex(char sex)
{
if( sex != M)
{
if(sex != F)
{
throw new IllegalArgumentException("Sex has to be M or F");
}
}
Sex = sex;
}
public void setCount(int count)
{
if(count < 0)
{
throw new IllegalArgumentException("Count cant be negative");
}
Count = count;
}
public String toString()
{
return String.format("%s %c %d", Name, Sex, Count);
}
}
OneNameCount
import java.util.Comparator;
import java.util.Collections;
public class OneNameCountCompare implements Comparator<OneName>
{
public int compare(OneName b1, OneName b2)
{
if(b1.getCount() <b2.getCount())
{
return 1;
}
else
{
return -1;
}
}
}
Main Program
import java.io.*;
import java.util.*;
public class TopNames
{
public static void main(String args[])
{
String line = ""; // string var to hold entire line
if (args.length < 1)
{
System.out.println("\nYou forgot to put a Year on the command line.");
System.exit(1);
};
String inFile = args[0]; // file name off command line
String year = inFile;
NameYear list = new NameYear(year);
}
}
Your descending function returns one string, and always the same string (the last one in the order after sorting the collection). It doesn't matter how often you call it, if the data doesn't change, you'll always get back that same, last, string.
If you want the first 10 after sorting, descending would need to return a List<String> containing those 10:
public List<String> descending()
{
List<String> x = new ArrayList<String>(10);
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName)
{
x.add(b.toString());
if (x.size() == 10) // Or don't use enhanced for, use an index instead
{
break;
}
}
return x;
}
Then when printing it, replace your for (int i = 0 ; i < 10; i++) loop with:
for (String s : descending())
{
System.out.println(s);
}
Your error is here:
for (int i = 0 ; i < 10; i++) {
System.out.println(descending());
}
public String descending() {
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName) {
x = b.toString();
}
return x;
}
First of all in your for loop you are not using the i variable that is your count indicator. This means that the descending() method has no any awareness of i, how he could return something different?
Try to modify descending() in something like this:
public String descending(int i) {
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
OneName b = oneName.get(i);
x = b.toString();
return x;
}

Check repetition of fractions of external file

I'm creating a program that has a requirement of three classes. The program reads an external text file filled with fractions, and is to return how many times each fraction is repeated. 4/2 has to be reduced to 2/1 and is +1 for the 2/1 count. I believe I am almost done, but I cannot figure out what I need to put into my compareAndIncrement() method in my FractionCounter class. It is suppose to be used to see if the newFraction passed into the function is the same as the Fraction being stored, and if so increments the counter by one and returns true (otherwise, returns false). Below are the codes for my classes.
FractionCounter
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FractionCounter {
private Fraction theFraction;
private int counter = 0;
public FractionCounter(Fraction theFraction ){
}
public boolean compareAndIncrement(Fraction newFraction){
return false;
}
public String toString(){
return "";
}
public static void main(String[] args){
ObjectList num = new ObjectList();
ObjectList den = new ObjectList();
Scanner fractionFile = null;
try{
fractionFile = new Scanner(new FileInputStream("fractions.txt"));
}
catch (FileNotFoundException e){
System.out.println("File not found.");
System.exit(0);
}
while (fractionFile.hasNextLine()){
String[] part = (fractionFile.nextLine().split("/"));
num.add(Integer.parseInt(part[0]));
den.add(Integer.parseInt(part[1]));
}
}
}
Fraction
public class Fraction {
private int numerator;
private int denominator;
public Fraction() {
}
public Fraction(int num, int den) {
setNumerator(num);
setDenominator(den);
}
public void setNumerator(int num) { //sets numerator
numerator = num;
}
public int getNumerator() { //gets numerator
return numerator;
}
public void setDenominator(int den) { //sets denominator
if(den == 0) {
System.out.println("Error: Denominator = 0");
System.exit(0);
} else {
denominator = den;
}
}
public int getDenominator() { //gets denominator
return denominator;
}
public boolean equals(Fraction that) {
return ((double)this.numerator/this.denominator) == ((double)that.numerator/that.denominator);
}
}
ObjectList
public class ObjectList {
private int[] fraction = new int[100];
private int numElements = 0;
public void add(int n){
fraction[numElements] = n;
numElements++;
}
public String toString(){
String retVal = "";
for (int i = 0; i < numElements; i++){
retVal += fraction[i] + ",";
}
return retVal;
}
public int indexOf(int[] input, int target) {
//returns the index of the inputed value
if(contains(input,target) == true){
for(int i = 0;i <= target;i++) {
if(input[i] == target) {
return i;
}
}
}
return -1;
}
public boolean contains(int[] input, int target) {
//is the target in the inputed array?
for(int i=0;i<input.length; i++) {
if(input[i] == target) {
return true;
}
}
return false;
}
}
Any hints or tips for what I need to do to my method would be much appreciated. I can't figure out a way to do it without using numElements and fraction variables from my ObjectList class. Thank you
I would make a Map to make the counter :
private static final Map<Fraction, Integer> counter = new HashMap<Fraction, Integer>();
and for each Fraction element read for the file I would do :
if(counter.containsKey(fraction)){
Integer count = counter.get(fraction);
count++;
counter.put(fraction, count);
} else {
counter.put(fraction, 1);
}
Moreover, I would make a static parse fonction in the Fraction class which return a Fraction instance from the line you just read. And a toString function to print it easely.

Keep Socket Server open for multiple uses?

There's a while loop in Client class where I ask user to make some calculations.The problem appears when I try to make more than one calculation. It stucks on making the calculation from Server class.
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
private static final int PORT = 1234;
public static void main(String[] arg) {
try {
Scanner userInputScanner = new Scanner(System.in);
Calculator c = new Calculator(0,0,"+");
CalculatorProtocol s = new CalculatorProtocol();
String testString = null;
String answer = null;
Socket socketConnection = new Socket(InetAddress.getLocalHost(),PORT);
ObjectOutputStream clientOutputStream = new
ObjectOutputStream(socketConnection.getOutputStream());
ObjectInputStream clientInputStream = new
ObjectInputStream(socketConnection.getInputStream());
do{
System.out.println("Give the 1st integer:");
testString = userInputScanner.next();
while (!s.isInteger(testString)) {
System.out.println("Wrong input data." + "Give the 1st integer:");
testString = userInputScanner.next();
}
c.setFirstNumber(Integer.parseInt(testString));
System.out.println("Give the 2nd integer:");
testString = userInputScanner.next();
while (!s.isInteger(testString)) {
System.out.println("Wrong input data." + "Give the 2nd integer:");
testString = userInputScanner.next();
}
c.setSecondNumber(Integer.parseInt(testString));
userInputScanner.nextLine(); // Gia na mi ginei lathos
System.out.println("Give the operator (+,-,*,/):");
testString = userInputScanner.nextLine();
while(!s.isOperator(testString)) {
System.out.println("Wrong input data."
+ "Give the operator(+,-,*,/):");
testString = userInputScanner.next();
}
c.setOperation(testString);
System.out.println("First integer:" +c.getFirstNumber());
System.out.println("Second integer:" +c.getSecondNumber());
System.out.println("Operator:"+c.getOperation());
clientOutputStream.writeObject(c);
c = (Calculator)clientInputStream.readObject();
System.out.println("Result="+c.getResult());
System.out.println("Want more?");
answer = userInputScanner.nextLine();
}while(s.wantMore(answer));
clientOutputStream.close();
clientInputStream.close();
}catch (Exception e) {System.out.println(e); }
}
}
Server Class
import java.io.*;
import java.net.*;
public class Server {
private static final int PORT = 1234;
public static void main(String[] arg) {
Calculator c = null;
CalculatorProtocol s = new CalculatorProtocol();
String answer = null;
try {
ServerSocket socketConnection = new ServerSocket(PORT);
System.out.println("Server Waiting");
while(true) {
Socket pipe = socketConnection.accept();
ObjectInputStream serverInputStream = new
ObjectInputStream(pipe.getInputStream());
ObjectOutputStream serverOutputStream = new
ObjectOutputStream(pipe.getOutputStream());
c = (Calculator)serverInputStream.readObject();
while (true) {
c.setResult(s.Calculate(c.getFirstNumber(), c.getSecondNumber()
, c.getOperation() ));
serverOutputStream.writeObject(c);
}
}
} catch(Exception e) {System.out.println(e);
}
}
}
Class for the protocol
public class CalculatorProtocol {
private int a , b ;
private String d;
public static boolean isInteger(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c <= '/' || c >= ':') {
return false;
}
}
return true;
}
public boolean isOperator(String op){
if(!(op.equals("+") || op.equals("-") || op.equals("*") || op.equals("/")))
return false;
else
d = op;
return true;
}
public int Calculate(int n1 , int n2 , String o) {
a = n1;
b = n2;
d = o;
int result = 0;
if (d.equals("+"))
result = a + b;
else if (d.equals("-"))
result = a - b;
else if (d.equals("*"))
result = a * b;
else
result = a/b;
return result;
}
public boolean wantMore(String m){
if (m.equals("Yes"))
return true;
else
return false;
}
}
import java.io.*;
import java.util.*;
public class Calculator implements Serializable {
private int num1,num2,result;
private String calc;
Calculator class for calculator objects.
Calculator (int a, int b, String p) {
num1 = a;
num2 = b;
calc = p;
result = 0;
}
public int getFirstNumber() {
return num1 ;
}
public int getSecondNumber() {
return num2 ;
}
public void setFirstNumber(int num) {
num1 = num;
}
public void setSecondNumber(int num) {
num2 = num;
}
public String getOperation() {
return calc ;
}
public void setOperation(String op) {
calc = op;
}
public void setResult(int d) {
result = d;
}
public int getResult() {
return result;
}
}
Without sifting through all of your posted code, I will diagnose your question. It seems like you want to add more than one client to do a calculation. It gets stuck here.
while(true) {
Socket pipe = socketConnection.accept();
ObjectInputStream serverInputStream = new ObjectInputStream(pipe.getInputStream());
ObjectOutputStream serverOutputStream = new ObjectOutputStream(pipe.getOutputStream());
c = (Calculator)serverInputStream.readObject(); //this is only done once
while (true) { // you need logic to break out of this loop.
c.setResult(s.Calculate(c.getFirstNumber(), c.getSecondNumber(), c.getOperation() ));
serverOutputStream.writeObject(c); //this is done multiple times
}
Assuming you only want to handle one client at a time, what you want to do is take calculations from that client until it no longer wants to send them. And then assuming you will take in one object and then write one object and rinse and repeat, what you need to do change is the following.
ObjectInputStream serverInputStream = new ObjectInputStream(pipe.getInputStream());
ObjectOutputStream serverOutputStream = new ObjectOutputStream(pipe.getOutputStream());
while (true) {
c = (Calculator)serverInputStream.readObject();
c.setResult(s.Calculate(c.getFirstNumber(), c.getSecondNumber(),c.getOperation() ));
serverOutputStream.writeObject(c);
}
You need to add some logic to break out of that loop based on a client leaving though, or will cycle forever.
The Server is writing c over and over while in the loop waiting for client input.
Upon the next calculation, the client isn't getting an updated version of c. To get a fresh copy of an updated object you need to call serverOutputStream.reset()
ObjectStreams add a reference for each object that has been written to it. You will need to call reset which removes all references of previously written objects. Enabling you to send an edited copy.
The main concern is how you are sending the object in the loop from the server. You are constantly sending it in a forever true loop in rapid succession.

Categories