Intro to Java Parrot Program - java

We have an assignment for an intro to java class im taking that requires us to program a parrot.
Essentially we have an output
" What do you want to say?
The User types in his input
" Blah Blah Blah"
And then the parrot is supposed to repeat
"Blah Blah Blah"
I have achieved this.
package parrot;
import java.util.Scanner;
public class Parrot {
public static void main(String[] args) {
System.out.print(" What do you want to say? ");
Scanner input = new Scanner(System.in);
String Parrot = input.nextLine();
System.out.println("Paulie Says: " + Parrot);
}
}
This gives me the exact results I need, but then I read in the lab instructions it wants us to do it in 2 files?
 Add 2 files to the project: Parrot.java and ParrotTest.java
 In Parrot.java do the following:
 Create a public class called Parrot
 Inside the class create a public method called speak. The method speak has one String parameter named word and no return value (i.e. return type void) The method header looks like this: public void speak(String word)
 The parrot repeats anything he is told. We implement this behavior by printing the word passed as an argument
And what I think im being asked to do is call it from another file? Can someone explain to me how to do this as im not exactly sure whats going on?

Yes your program performs the given task, but not in the manner you are asked. Your main method should be executed from inside the ParrotTest.java file. In this file (ParrotTest.java), you will need to create an instance of a class (you can call it Parrot) by calling a constructor.
Inside your Parrot.java you will create a method called 'speak' which accepts String word.
Going back to the main method: Here you will ask for user input, capture the input in a String 'word' and pass it as an argument to the speak method you created. Once your method has this argument, you can print it's content out to the console.

Parrot would have the following
public class Parrot
{
public void speak( String word )
{
System.out.printf("%s", word);
}
}
Parrot Test would have the following
import java.util.Scanner;
public class ParrotTest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("What would you like to say to the parrot?: ");
String words = input.nextLine();
Parrot myParrot = new Parrot();
myParrot.speak(words);
}
}

I don't know if you have to use scanner but this is how i would do it.BTW this code works with Jcreator.
public static void main(String[] args) {
String say = IO.getString("Say something") // This is asking the user to say something
System.out.print(name);
}
If you want it to loop 10 times then
then do this
public static void main(String[] args) {
String say = IO.getString("Say something"); // This is asking the user to say something
int count = 10; // it will loop 10 times
while (count >= 10) {
System.out.print(name);
say = IO.getString("Say something");
count++;
}
By the way if you don't have IO class you can you this. Just copy this code into jcreator and say it where you save all your codes.
/**
* #(#)IO.java
* This file is designed to allow HCRHS students to collect information from the
* user during Computer Science 1 and Computer Science 2.
* #author Mr. Twisler, Mr. Gaylord
* #version 2.01 2014/12/21
* *Updated fix to let \t work for all input/output
* *Added input methods to allow for console input
* *Allowed all get methods to work with all objects
* *Updated format methods to use String.format()
*/
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
public class IO {
// Shows a message in a popup window
public static void showMsg(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
JOptionPane.showMessageDialog(null, text, "HCRHS",
JOptionPane.PLAIN_MESSAGE);
}
/*********************************User Input Methods***************************
* All user input methods get the data type mentioned in their name and return
* a default value if the user enters an incorrect responce.
******************************************************************************/
// Returns String typed by user, default value is ""
public static String getString(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
String ans = JOptionPane.showInputDialog(null, text, "HCRHS",
JOptionPane.QUESTION_MESSAGE);
if(ans == null) {
return "";
}
return ans;
}
public static String nextString() {
Scanner scan = new Scanner(System.in);
String ans = scan.nextLine();
scan.close();
if(ans == null) {
return "";
}
return ans;
}
// Returns int typed by the user, default value is 0
public static int getInt(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
try {
return Integer.parseInt(JOptionPane.showInputDialog(null, text,
"HCRHS", JOptionPane.QUESTION_MESSAGE));
} catch (NumberFormatException e) {
//System.out.println("Not a valid int");
return 0;
}
}
public static int nextInt() {
Scanner scan = new Scanner(System.in);
int ans;
try {
ans = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
//System.out.println("Not a valid int");
ans = 0;
}
scan.close();
return ans;
}
// Returns double typed by the user, default value is 0.0
public static double getDouble(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
try {
return Double.parseDouble(JOptionPane.showInputDialog(null, text,
"HCRHS", JOptionPane.QUESTION_MESSAGE));
} catch (NumberFormatException|NullPointerException e) {
//System.out.println("Not a valid double");
return 0;
}
}
public static double nextDouble() {
Scanner scan = new Scanner(System.in);
double ans;
try {
ans = Double.parseDouble(scan.nextLine());
} catch (NumberFormatException|NullPointerException e) {
//System.out.println("Not a valid double");
ans = 0;
}
scan.close();
return ans;
}
// Returns char typed by the user, default value is ' '
public static char getChar(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
try {
return JOptionPane.showInputDialog(null, text, "HCRHS",
JOptionPane.QUESTION_MESSAGE).charAt(0);
} catch (NullPointerException|StringIndexOutOfBoundsException e) {
//System.out.println("Not a valid char");
return ' ';
}
}
public static char nextChar() {
Scanner scan = new Scanner(System.in);
char ans;
try {
ans = scan.nextLine().charAt(0);
} catch (NullPointerException|StringIndexOutOfBoundsException e) {
//System.out.println("Not a valid char");
ans = ' ';
}
scan.close();
return ans;
}
// Returns boolean typed by the user, default value is false
public static boolean getBoolean(Object obj) {
JTextArea text = new JTextArea(obj.toString());
text.setBorder(null);
text.setOpaque(false);
text.setEditable(false);
//String text = obj.toString().replace("\t", " ");
int n = JOptionPane.showOptionDialog(null, text, "HCRHS",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, new Object[]{"True", "False"}, 1);
return (n == 0);
}
public static boolean nextBoolean() {
Scanner scan = new Scanner(System.in);
String bool = scan.nextLine().toLowerCase();
scan.close();
if (bool.equals("true") || bool.equals("t") || bool.equals("1")) {
return true;
} else {
return false;
}
}
/******************************Formatting Methods******************************
* Format is overloaded to accept Strings/int/double/char/boolean
******************************************************************************/
public static String format(char just, int maxWidth, String s) {
if (just == 'l' || just == 'L') {
return String.format("%-" + maxWidth + "." + maxWidth + "s", s);
} else if (just == 'r' || just == 'R') {
return String.format("%" + maxWidth + "." + maxWidth + "s", s);
} else if (just == 'c' || just == 'C') {
return format('l', maxWidth, format('r',
(((maxWidth - s.length()) / 2) + s.length()), s));
} else {
return s;
}
}
public static String format(char just, int maxWidth, int i) {
return format(just, maxWidth, String.format("%d", i));
}
public static String format(char just, int maxWidth, double d, int dec) {
return format(just, maxWidth, String.format("%,." + dec + "f", d));
}
public static String format(char just, int maxWidth, char c) {
return format(just, maxWidth, String.format("%c", c));
}
public static String format(char just, int maxWidth, boolean b) {
return format(just, maxWidth, String.format("%b", b));
}
/*********************************Fancy Expirmental Methods********************/
public static String choice(String... options) {
String s = (String)JOptionPane.showInputDialog(null,
"Pick one of the following", "HCRHS",
JOptionPane.PLAIN_MESSAGE, null, options, null);
//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
return s;
}
return "";
}
public static String readFile(String fileName) {
String ans ="";
try {
Scanner scanner = new Scanner(new File(fileName));
scanner.useDelimiter(System.getProperty("line.separator"));
while (scanner.hasNext()) {
ans += scanner.next()+"\n";
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return ans;
}
public static void writeFile(String fileName, String data) {
try {
FileWriter fw = new FileWriter(fileName, true);
fw.write(data);
fw.close();
} catch(java.io.IOException e) {
e.printStackTrace();
}
}
}

Related

How can I check with nextLine() if the user input is only a number or also letters?

I´m having a question about my program. I´m trying to figure out, how i can check if the s.nextLine() input form a user is only holding ints form 1 to 49 in it or also letters.
I know that the "eingabe" is a string so I can’t just use an if right?
My problem is, that I´m relative new in programming with java and i have no idea for a solution. :/
Maybe you can help me that would be great!
public static int Scanner() {
Scanner s = new Scanner(System.in);
String eingabe = s.nextLine();
//???
return eingabe;
}
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class MyClass {
public static void main (String[] args) {
try {
int x = Scanner();
if(x >= 1 && x <= 49) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
catch(java.lang.NumberFormatException e) {
System.out.println(e);
}
//Second Method Using Regex.
try {
int x = useRegex();
if(x >= 1 && x <= 49) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
} catch(java.lang.NumberFormatException e) {
System.out.println(e);
}
}
public static int Scanner() {
Scanner s = new Scanner(System.in);
String eingabe = s.nextLine();
return Integer.parseInt(eingabe);
}
public static int useRegex() {
Scanner s2 = new Scanner(System.in);
String eingabe = s2.nextLine();
Pattern p = Pattern.compile("^[\\+-]?\\d+$");
Matcher m = p.matcher(eingabe);
boolean b = m.matches();
if(b) {
return Integer.parseInt(eingabe);
}
else {
throw new java.lang.NumberFormatException();
}
}
}
Here I am using try catch block to handle if the input format is wrong. If it is wrong then the Exception
java.lang.NumberFormatException
will occur and then if it is a valid number then I am checking whether it is between 1 and 49. Integer.parseInt(num) is used to convert a String into number.
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String).
Try catch is used to handle to exceptions without . See here
By using regex also I have mentioned. See this for regex

What is supertype?

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
//star my method lab
public class Method extends JPanel {
//two array lists that I am going to use.
ArrayList<String> english = new ArrayList<>();
ArrayList<String> french = new ArrayList<>();
//bring text file as an array
public void loadEnglishWords() {
//input my file
String filename = "english.txt";
File f = new File(filename);
try {
Scanner s = new Scanner(f);
//scan all array line by line
while (s.hasNextLine()) {
String line = s.nextLine();
english.add(line);
}
} catch (FileNotFoundException e) { //wrong file name makes error massage pop up
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!",JOptionPane.ERROR_MESSAGE);
}
}
//same array job with English to compare
public void loadFrenchWords() {
String filename = "french.txt";
File f = new File(filename);
try {
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
String line = s.nextLine();
french.add(line);
}
} catch (FileNotFoundException e) {
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!",JOptionPane.ERROR_MESSAGE);
}
}
//check each line to parallel my arrays to get to same position
public String lookup(String word){
for (int i = 0; i < english.size();i++) {
if (word.equals(english.get(i))) {
return french.get(i);
}
}
//wrong values in arrays
return "No match found";
}
//infinite loop to run my program until get the result
public void mainLoop() {
while (true) {
//pop-up box to ask English words
String tmp = JOptionPane.showInputDialog("Please Enter an English Word!");
//store the result in variable r
String r = lookup(tmp);
String a;
//
if (r == ("No match found")) {
a = "Write a Right Word!";
} else {
a = "The French word is : " + r + ". Play agian?";
}
//asking want to play more or not
int result;
result = JOptionPane.showConfirmDialog(null,a,"RESULT!",JOptionPane.YES_NO_OPTION);
//doens't want to play then shut down
if (result == JOptionPane.NO_OPTION) {
break;
}
}
}
//make all things run in order
#Override
public void init() {
loadEnglishWords();
loadFrenchWords();
mainLoop();
}
}
//My problem is that everytime I compile this program the error message would be:
"Method.java:88: error: method does not override or implement a method from a supertype
#Override
^
1 error"
//This program is to translate french words to english words using arraylist
I`m using a .txt file for my set of english and french words and have it run through arraylist to translate
//In my program I need to use a JPanel or pop-up box to ask the user to input the word that they wish to translate
//Please note that I am a beginner with Java, please somebody help me and point out on where I got it wrong so I can change it. Thank you so much!
What the error is saying is that in line 88, you are using the #Override to redefine a method named init from parent class JPanel. But because JPanel is what it is (i.e. a part of Java), it does not have init method, you can not redefine it, hence the error. Most likely, you should just remove the #Override, which will mean you want to add a new method instead of redefining it.
Inheritance is a mechanism where you take an existing class and modify it according to your needs. In your case, your class is named Method and it extends (inherits from) JPanel, so JPanel is the supertype of your class.
If you're just beginning, go read and educate yourself on object-oriented concepts. There are many tutorials, including YouTube videos. Happy learning!
Aside from what was previously mentioned, you need to change a few things:
public void init() { should be public static void main(String args[]) {
Then you need to make your methods static, i.e.
public static void loadEnglishWords() {
Also, the arrayLists need to also be static
And one other thing, you should compare with .equals() and not ==
I've re-written your code slightly and now it should work:
static ArrayList<String> english = new ArrayList<>();
static ArrayList<String> french = new ArrayList<>();
//bring text file as an array
public static void loadEnglishWords() {
//input my file
try {
Scanner s = new Scanner(new File("english.txt"));
//scan all array line by line
while (s.hasNextLine()) {
String line = s.next();
english.add(line);
}
} catch (FileNotFoundException e) { //wrong file name makes error massage pop up
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!", JOptionPane.ERROR_MESSAGE);
}
}
//same array job with English to compare
public static void loadFrenchWords() {
try {
Scanner s = new Scanner(new File("french.txt"));
while (s.hasNextLine()) {
String line = s.nextLine();
french.add(line);
}
} catch (FileNotFoundException e) {
String errorMessage = "Wrong!";
JOptionPane.showMessageDialog(null, errorMessage, "Wrong!", JOptionPane.ERROR_MESSAGE);
}
}
//check each line to parallel my arrays to get to same position
public static String lookup(String word) {
for (int i = 0; i < english.size(); i++) {
if (word.equals(english.get(i))) {
return french.get(i);
}
}
//wrong values in arrays
return "No match found";
}
//infinite loop to run my program until get the result
public static void mainLoop() {
while (true) {
//pop-up box to ask English words
String tmp = JOptionPane.showInputDialog("Please Enter an English Word!");
//store the result in variable r
String r = lookup(tmp);
String a;
//
if (r.equals("No match found")) {
a = "Write a Right Word!";
} else {
a = "The French word is : " + r + ". Play agian?";
}
//asking want to play more or not
int result;
result = JOptionPane.showConfirmDialog(null, a, "RESULT!", JOptionPane.YES_NO_OPTION);
//doens't want to play then shut down
if (result == JOptionPane.NO_OPTION) {
break;
}
}
}
//make all things run in order
public static void main(String args[]) {
loadEnglishWords();
loadFrenchWords();
mainLoop();
}
}

Trying to utilize an input.txt file into a output.txt file in Java

I am trying to test my application by printing into an output.txt file. There is an input.txt file that already contains four honor students and at least two with the same GPA of 3.9, and three that are not honors students. The results should be sent to the output.txt file. The output.txt file should contain:
1) All of the students
2) The best student
3) Number of honors students in the list
4) Honors students
The input.txt file that I created contains the following (in order) last names, first names, id, GPA, and year.
The class TestStudents prints the input.txt file. However, I need it to utilize the input.txt file in order to print the above mentioned output.txt file. Thank you very much.
Student class -
public class Student
{
String lastName, firstName, id;
double gpa;
int year;
public Student (String lastName, String firstName, String id,
double gpa, int year)
{
this.lastName = lastName;
this.firstName = firstName;
this.id = id;
this.gpa = gpa;
this.year = year;
}
public String toString()
{
return this.lastName + ", " + this.firstName + ": " + this.id + " "
+ this.gpa + " " + this.year;
}
public double getGPA()
{
return gpa;
}
public boolean isBetter (Student s)
{
return (this.gpa > ((Student)s).getGPA());
}
public boolean isHonors()
{
if (this.gpa >= 3.5)
{
return true;
}
else
{
return false;
}
}
}
CS152 class -
import java.util.*;
import java.io.*;
public class CS152
{
public static final int MAXSIZE = 22;
private static int size = 0;
public static Student[] createList (Scanner scan) throws IOException
{
Student[] list = new Student [MAXSIZE];
return populateList (list, scan);
}
private static Student[] populateList (Student[] list, Scanner scan)
{
Student s;
if (size < MAXSIZE && scan.hasNext())
{
s = new Student (scan.next(), scan.next(), scan.next(),
scan.nextDouble(), scan.nextInt());
list[size] = s;
size++;
System.out.println (s);
return populateList (list, scan);
}
else
{
return list;
}
}
public static int getSize()
{
return size;
}
// Returns String of all students. Variable n is actual size of the list.
// Assume that n is positive. Recursive code.
public static String toString (Student[] list, int n)
{
String s = " ";
if (n == 1)
{
return s += list[0];
}
else
{
s += list[n].toString() + "\n";
s += "\n";
}
return s + toString (list, n - 1);
}
// Returns the best student. Must use method isBetter in the code.
// Variable n is actual size of the list. Assume that n is positive.
public static Student findBestStudent (Student[] list, int n)
{
if (n == 1)
{
return list[0];
}
else if (list[n].isBetter (list[n - 1]))
{
return list[n];
}
else
{
return findBestStudent (list, n - 1);
}
}
// Returns the number of honor students in the list.
// Must call the method isHonors(). Variable n is actual size of the list.
// Assume that n is positive.
public static int countHonors (Student[] list, int n)
{
if (n == 0)
{
return 0;
}
else if (list[n].isHonors())
{
return 1 + countHonors (list, n - 1);
}
else
{
return countHonors (list, n - 1);
}
}
static ArrayList<Student> studentsList = new ArrayList<Student>();
public static ArrayList <Student> honorsStuds (Student[] list, int n)
{
if (n == 0)
{
return studentsList;
}
else
{
boolean currentIsHonors = list[n - 1].isHonors();
if (currentIsHonors)
{
studentsList.add(list[n - 1]);
return honorsStuds (list, n - 1);
}
else
{
return honorsStuds (list, n - 1);
}
}
}
}
TestStudents class -
import java.io.*;
import java.util.*;
public class TestStudents
{
public static void main (String[] args) throws IOException
{
File input = new File ("input.txt");
Scanner scan = new Scanner (input);
Student[] studentArray = CS152.createList (scan);
}
}
I incorporated the FileWriter into the TestStudents class. A list of all students is now displayed. I am still having difficulties trying to call the methods findBestStudent, countHonors, and honorsStuds and implementing them into TestStudents. Here is the revised TestStudents class:
TestStudents class -
import java.io.*;
import java.util.*;
public class TestStudents
{
public static void main (String[] args) throws IOException
{
File input = new File ("input.txt");
Scanner scan = new Scanner (input);
System.out.println ("All students: ");
Student[] studentArray = CS152.createList (scan);
File output = new File ("output.txt");
FileWriter fWriter = new FileWriter (output);
PrintWriter pWriter = new PrintWriter (fWriter);
pWriter.println (input);
pWriter.close();
}
}
To write to a file, you need a FileWriter.
Using a FileWriter and Try-with-resources, usage would look something like this:
try(FileWriter w = new FileWriter(new File("output.txt"))) {
w.append("Some string");
} catch (IOException ex) {
Logger.getLogger(Output.class.getName()).log(Level.SEVERE, null, ex);
}
If you don't use a try-with-resources, make sure to close() the Writer to make sure resources do not leak. In fact, you should also make sure to close your Scanner as well, as leaving it un-closed will leak resources.
In the future, ask one question per post.
To access your Students, you just need to read them from the array.
System.out.println(studentArray[0].getGPA()); // prints the GPA of the first student
for (int i=0; i<CS152.getSize(); i++) {
System.out.println(studentArray[i]); // prints every Student
}
[[Note that this design of having a long array with null elements at the end with CS152.class telling you how many are filled is bad design. I would have the read procedure return a List<Student>, which manages its own length. Given the name of the class is CS152, however, this is probably either given to you by the teacher of CS-152 or done previously, so I'll work with what you have.]]

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.

Java returns impossible random numbers

Here is the code:
import java.lang.*;
import java.io.*;
class string
{
public static void main(String[] args)
{
try
{
boolean go = true;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuffer inp = new StringBuffer(br.readLine());
System.out.println(inp.reverse());
inp.reverse();
int leng = inp.length();
inp.setLength(leng+100);
int x = 0;
StringBuffer res = inp;
William bill = new William();
res=bill.will(x+1, leng, res);
while(x<leng-1 && go)
{
if(inp.charAt(x)==' ' && go)
{
res=bill.will(x+1, leng, res);
go = bill.bob();
}
x=x+1;
}
System.out.println(res);
}
catch (IOException uhoh)
{
System.out.println("You entered something wrong.");
System.exit(1);
}
}
}
class William
{
public boolean go;
public William()
{
this.go=true;
}
public StringBuffer will(int start, int len, StringBuffer input)
{
char cur = input.charAt(start-1);
input.delete(start-1, start-1);
int x = start;
boolean happy=true;
while(x<len && happy)
{
if(x==len-2)
{
this.go=false;
input.insert(cur, x+1);
x=x+2;
happy=false;
}
else if(input.charAt(x)==' ')
{
input.insert(cur, x);
x=x+1;
happy=false;
}
else
{
x=x+1;
}
}
return input;
}
public boolean bob()
{
return this.go;
}
}
It is supposed to return the reverse of the input (it does that without error) and the input in an altered form of pig latin. tI houlds ookl ikel hist ("It should look like this"). But instead, it returns the original StringBuffer with a bunch of random numbers on the end. Two notable patterns in the error include the increase in the numbers as the number of letters increases, as well as overflow errors when short strings are inputted.
You have the arguments to StringBuffer.insert() backwards. It's (offset, char)
try
input.insert(x+1, cur); instead of input.insert(cur, x+1);
(and same for input.insert(cur, x))

Categories