Keep Socket Server open for multiple uses? - java

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.

Related

Can't get replace to work

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.

Hangman game errors

Here is my program so far:
import java.util.Arrays;
public class HangmanWord {
private String[] possibleWords = {"laptop", "college", "programing"};
private String word;
private char[] progress;
private int wrongCount = 0;
public HangmanWord() {
int randomPossibleWord = (int) (Math.random() * possibleWords.length-1);
String word = possibleWords[randomPossibleWord];
char[] progress = new char[word.length()];
Arrays.fill(progress,'-');
}
public void display() {
System.out.print(progress);
System.out.println();
}
public boolean guess(char c) {
boolean matchFound = false;
for (int i = 0; i < word.length(); i++ ) {
if (word.charAt(i) == c ) {
progress[i] = c;
matchFound = true;
}
}
return false;
}
public boolean isSolved() {
for (int i = 0; i < progress.length; i++ ) {
if(progress[i] == '-'){
return false;
}
}
return true;
}
public int getWrongCount() {
return wrongCount;
}
public String getWord() {
return word;
}
}
public class Hangman {
public static void main(String[] args) {
int MAX_INCORRECT = 5;
System.out.println("Welcome to Hangman.");
HangmanWord wordObj = new HangmanWord();
System.out.print("Here is your word: ");
wordObj.display();
}
}
My output should look something like this:
Welcome to Hangman.
Here is your word: ------
However, I am getting the following errors:
Welcome to Hangman.
Here is your word: Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Writer.java:127)
at java.io.PrintStream.write(PrintStream.java:503)
at java.io.PrintStream.print(PrintStream.java:653)
at HangmanWord.display(HangmanWord.java:16)
at Hangman.main(Hangman.java:9)
You are redefining the variable word and progress in your constructor. You should simply use them without declaring them as a new variables because they're already defined. Currently you are defining them locally, the constructor works but uses those local defined variables and not your object's word and progress variables, therefore when you leave scope and call display() it will use your object's progress array which was never actually initialized.
Change it to the following so you aren't redefining the variables word and progress like so
public HangmanWord() {
int randomPossibleWord = (int) (Math.random() * possibleWords.length-1);
word = possibleWords[randomPossibleWord];
progress = new char[word.length()];
Arrays.fill(progress,'-');
}

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;
}

Intro to Java Parrot Program

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();
}
}
}

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