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))
Related
I am trying to parse a rather special-formatted file by using scanner with delimiter, but I am rather new to regex. The format:
"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER",...
Currently, I am using this delimiter and code below:
static void readNames(String[] names) {
try {
Scanner sc = new Scanner(new File("names.txt")).useDelimiter(",");
int count = 0;
while(sc.hasNext()) {
names[count] = sc.next();
count ++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
However, this gives me quotes around the String which is not what I want.
Then, I tried to the following delimiter:
String delimiter = " "," ";
Which I quickly realised is not recognised as a String due to the amount of quotation marks.
This is edited after I got my answer, but is there any way to do it the way I intended in the second delimiter, by using the "," as the delimiter?
Based upon the data given in your post, I think you can use this pattern ","|"
Following is the kind of code you can write,
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new FileInputStream("filename.txt"));
sc.useDelimiter(Pattern.compile("\",\"|\""));
while(sc.hasNext()) {
System.out.println(sc.next());
}
sc.close();
}
If you just want a java written helpful csv parser. I wrote a pretty nice one recently:
public static Iterable<String[]> parseCSV(final InputStream stream) throws IOException {
return new Iterable<String[]>() {
#Override
public Iterator<String[]> iterator() {
return new Iterator<String[]>() {
static final int UNCALCULATED = 0;
static final int READY = 1;
static final int FINISHED = 2;
int state = UNCALCULATED;
ArrayList<String> value_list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
String[] return_value;
public void end() {
end_part();
return_value = new String[value_list.size()];
value_list.toArray(return_value);
value_list.clear();
}
public void end_part() {
value_list.add(sb.toString());
sb.setLength(0);
}
public void append(int ch) {
sb.append((char) ch);
}
public void calculate() throws IOException {
boolean inquote = false;
while (true) {
int ch = stream.read();
switch (ch) {
default: //regular character.
append(ch);
break;
case -1: //read has reached the end.
if ((sb.length() == 0) && (value_list.isEmpty())) {
state = FINISHED;
} else {
end();
state = READY;
}
return;
case '\r':
case '\n': //end of line.
if (inquote) {
append(ch);
} else {
end();
state = READY;
return;
}
break;
case ',': //comma
if (inquote) {
append(ch);
} else {
end_part();
break;
}
break;
case '"': //quote.
inquote = !inquote;
break;
}
}
}
#Override
public boolean hasNext() {
if (state == UNCALCULATED) {
try {
calculate();
} catch (IOException ex) {
}
}
return state == READY;
}
#Override
public String[] next() {
if (state == UNCALCULATED) {
try {
calculate();
} catch (IOException ex) {
}
}
state = UNCALCULATED;
return return_value;
}
};
}
};
}
You would typically process this quite helpfully like:
for (String[] csv : parseCSV(stream)) {
//<deal with parsed csv data>
}
Generally it wraps a csv stream parser in an iterable so you can use the special java for loops. So you feed it a stream and it'll give you a for loop of arrays of strings, which is typically going to be the best way you'd want that data.
If you rather want understanding, you'll need to better phrase your question with additional information that makes it clear what you think you need and why, because most of your post doesn't make much sense.
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
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.
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();
}
}
}
As I just stated above this program won't compile. In my IDE, TextPad, it gives me 2 errors in the createArray method. It says that both a right bracket and semicolon are expected in my return statement when I indeed have them there. Could someone help me out here?
public class Driver
{
private static int size;
private static String somePromptMessage;
private static boolean validInput;
private static String userData;
public static void main(String[] args) throws IOException
{
validInput = false;
BufferedReader keyboard;
keyboard = new BufferedReader(new InputStreamReader(System.in));
int result;
do
{
somePromptMessage = "Enter an integer";
System.out.println(somePromptMessage);
String userData;
userData = keyboard.readLine();
System.out.println(createArray(10));
try
{
result = Integer.parseInt(userData);
}
catch(NumberFormatException nfe)
{
System.out.println("Value entered is invalid, try again");
}
}
while(!validInput);
{
return result;
}
}
public static void print(int[]x)
{
System.out.println("The array contains" + size + "elements");
for(int i = 0; i<x.length; i++)
{
System.out.println(x[i]);
}
}
private static int[] createArray(int size)
{
return int[size];
}
You're missing the enclosing } for the class, but I'll assume that one is a copy-paste issue.
The actual problem I see is that you want
return new int[size];
instead of
return int[size];
in your createArray function.
I see an extra simi-colon here:
while(!validInput);
{
return result;
}
Update: It was brought to my attention that this is actually a do while so why the extra braces around the return statement?
remove braces after while across return result; as it is do-while:
do
{
somePromptMessage = "Enter an integer";
System.out.println(somePromptMessage);
String userData;
userData = keyboard.readLine();
System.out.println(createArray(10));
try
{
result = Integer.parseInt(userData);
}
catch(NumberFormatException nfe)
{
System.out.println("Value entered is invalid, try again");
}
}
while(!validInput);
return result;