Trashes when trying to see convertion - java

I've got a problem with this simple class. When I'm trying to convert input String by the Caesar cipher I'm getting another String than thought. What is wrong? And do I implement correctly serialization and deserialization for only String CONTENT? Why output is: [C#58a1a199 rather than DEFGcaf ..? Error when running test is like this: FAILED: ARRAYS FIRST DIFFERED AT ELEMENT[0]; EXPECTED <68> BUT WAS <14>. Why it can't pass this test if we have correct transformation?
HERE IS MY CLASS:
public class TajnyDokument implements Serializable {
public String content;
public transient int howMuchToMove = 3;
private transient String sign;
public transient char[]cypher;
public TajnyDokument(String zawartosc, String podpis) throws IOException {
this.content = zawartosc;
this.sign = podpis;
}
private void writeObject(ObjectOutputStream os) throws IOException
{
szyfruj(content);
os.writeChars(this.content);
//os.writeChars(this.sign);
// os.writeUTF(content);
os.defaultWriteObject();
}
private void readObject ( ObjectInputStream is ) throws IOException , ClassNotFoundException {
content = String.valueOf(is.readChar());
sign = String.valueOf(is.readChar());
is . defaultReadObject ( ) ;
}
public void szyfruj(String dana) throws IOException
{
System.out.println(content);
cypher = dana.toCharArray();
char tmp[] = new char[cypher.length];
char c;
for(int i = 0; i < cypher.length; i++)
{
c = cypher[i];
if((c >'Z' || c < 'A') && (c < 'a' || c > 'z'))
{
throw new IOException();
}
else
{
if(c == 'X')
{
int ilezostalo = (int)'Z' - (int)'X';
tmp[i] = (char)((int)'A' + (howMuchToMove - ilezostalo-1));
System.out.println(tmp[i]);
}
else if(c == 'Y')
{
int ilezostalo = (int)'Z' - (int)'Y';
tmp[i] = (char)((int)'A' + (howMuchToMove - ilezostalo-1));
System.out.println(tmp[i]);
}
else if(c == 'Z')
{
tmp[i] = (char)((int)'A' + (howMuchToMove-1));
System.out.println(tmp[i]);
}
else if(c == 'x')
{
int ilezostalo = (int)'z' - (int)'x';
tmp[i] = (char)((int)'a' + (howMuchToMove - ilezostalo-1));
System.out.println(tmp[i]);
}
else if(c == 'y')
{
int ilezostalo = (int)'z' - (int)'y';
tmp[i] = (char)((int)'a' + (howMuchToMove - ilezostalo-1));
System.out.println(tmp[i]);
}
else if(c == 'z')
{
tmp[i] = (char)((int)'a' + (howMuchToMove-1));
System.out.println(tmp[i]);
}
else
{
tmp[i] = (char)((int)c + howMuchToMove);
System.out.println(tmp[i]);
}
}
}
content = tmp.toString();
if(tmp.toString().equals("DEFGcaf"))
{
this.content = "DEFGcaf";
}
// super.write(tmp)
System.out.println(content);
System.out.println(content);
System.out.println(content);
}
public String getPodpis() {
return sign;
}
public String getZawartosc() {
return content;
}
public static void main(String[] arg) throws IOException
{
TajnyDokument tajny = new TajnyDokument("ABCDzxc", "Piotr Kaczyński");
tajny.szyfruj(tajny.content);
String wynik = tajny.content;
System.out.println(wynik);
}
}
TEST CLASS FOR MY CODE:
public class Punkt2Test {
private ByteArrayOutputStream buffer;
private ObjectOutputStream testOutputStream;
private TajnyDokument testObject;
public Punkt2Test() {
}
#Before
public void setUp() throws IOException {
buffer = new ByteArrayOutputStream();
testOutputStream = new ObjectOutputStream(buffer);
testObject = new TajnyDokument("ABCDzxc", "Piotr Kaczyński");
}
#Test
public void zapisPoprawny() throws IOException, ClassNotFoundException {
testOutputStream.writeObject(testObject);
testOutputStream.flush();
ByteArrayInputStream is = new ByteArrayInputStream(buffer.toByteArray());
byte[] expectedResult = new byte[]{'D', 'E', 'F', 'G', 'c', 'a', 'f'};
byte[] result = new byte[7];
is.skip(101);
is.read(result, 0, 7);
for(int i=0; i<result.length; i++) {
System.out.println(i + " " + (char)result[i] + " " + result[i]);
// System.out.println(result[i]);
}
assertArrayEquals(expectedResult, result);
}
}

You are converting your character array to a string in the wrong fashion. Try:
content = new String(tmp);
Your original code was calling .toString() on an array, which simply calls the Object.toString() implementation. Hence you got something like [C#609a5d54:
[ indicates an array type
C indicates the char type
# separates type from hashcode
609a5d54 was the hashcode (different each time the code runs)
See Object.toString() and Class.getName() for furthed details.

Array are treated as object in java. In your case tmp is array of characters. so when you call toString method on that object it returns you hashcode of that array object.
So Instead writing like
tmp.toString();
write
content = new String(tmp);

Related

When does the toUpperCase() method create a new object?

public class Child{
public static void main(String[] args){
String x = new String("ABC");
String y = x.toUpperCase();
System.out.println(x == y);
}
}
Output: true
So does toUpperCase() always create a new object?
toUpperCase() calls toUpperCase(Locale.getDefault()), which creates a new String object only if it has to. If the input String is already in upper case, it returns the input String.
This seems to be an implementation detail, though. I didn't find it mentioned in the Javadoc.
Here's an implementation:
public String toUpperCase(Locale locale) {
if (locale == null) {
throw new NullPointerException();
}
int firstLower;
final int len = value.length;
/* Now check if there are any characters that need to be changed. */
scan: {
for (firstLower = 0 ; firstLower < len; ) {
int c = (int)value[firstLower];
int srcCount;
if ((c >= Character.MIN_HIGH_SURROGATE)
&& (c <= Character.MAX_HIGH_SURROGATE)) {
c = codePointAt(firstLower);
srcCount = Character.charCount(c);
} else {
srcCount = 1;
}
int upperCaseChar = Character.toUpperCaseEx(c);
if ((upperCaseChar == Character.ERROR)
|| (c != upperCaseChar)) {
break scan;
}
firstLower += srcCount;
}
return this; // <-- the original String is returned
}
....
}

I can't open the jar file of the project

I have a project that I need to have its jar file , but it doesn't open , can anyone help me please, I need it as soon as possible for my university . And here is the whole code :
package huffmanproject;
import java.util.ArrayList;
import java.util.PriorityQueue;
public class huffmanproject {
public static class HuffNode implements Comparable<HuffNode> {
public int value;
public int weight;
public HuffNode leftTree;
public HuffNode rightTree;
public HuffNode parent;
public HuffNode() {
parent = null;
}
public HuffNode( int v, int w, HuffNode lTree, HuffNode rTree, HuffNode par ) {
value = v;
weight = w;
leftTree = lTree;
rightTree = rTree;
parent = par;
}
#Override
public int compareTo(HuffNode rhs) {
return weight - rhs.weight;
}
#Override
public String toString() {
String str = "";
str += this.value;
return str;
}
}
public static class HuffTree {
private int size = 0;
private HuffNode root = new HuffNode();
private PriorityQueue<HuffNode> huffQueue = new PriorityQueue();
public ArrayList<String> pathTable = new ArrayList();
public ArrayList<Character> valueTable = new ArrayList();
public HuffTree(int[] freq, char[] code) {
this.size = freq.length;
if (freq.length != code.length) {
throw new UnsupportedOperationException("Error: Character and code length mismatch.");
}
for (int i = 0; i < this.size; i++) {
huffQueue.offer(new HuffNode(code[i], freq[i], null, null, null));
}
createTree();
createTable(this.root, "");
}
private void createTree() {
while (huffQueue.size() > 1) {
HuffNode tempL = huffQueue.poll();
HuffNode tempR = huffQueue.poll();
HuffNode parent = new HuffNode(0, tempL.weight+tempR.weight, tempL, tempR, null);
tempL.parent = parent;
tempR.parent = parent;
huffQueue.offer(parent);
this.size++;
}
this.root = huffQueue.peek();
}
private void createTable(HuffNode curr, String str) {
if (curr == null) return;
if (curr.leftTree == null && curr.rightTree == null) {
char tempChar;
if (curr.value == 32)
tempChar = ' ';
if (curr.value == 10)
tempChar = 'n';
else
tempChar = (char)curr.value;
this.valueTable.add(tempChar);
this.pathTable.add(str);
}
str += "0";
createTable(curr.leftTree, str);
str = str.substring(0, str.length()-1);
str += "1";
createTable(curr.rightTree, str);
}
String tacks = "";
public void getTree(HuffNode curr) {
if (curr == null) return;
if (curr.leftTree == null && curr.rightTree == null) {
switch (curr.value) {
case 32:
System.out.println(tacks + curr.weight + ": sp");
break;
case 10:
System.out.println(tacks + curr.weight + ": nl");
break;
default:
System.out.println(tacks + curr.weight + ": " + (char)curr.value);
break;
}
}
else
System.out.println(tacks + curr.weight);
tacks += "- ";
getTree(curr.leftTree);
getTree(curr.rightTree);
tacks = tacks.substring(0, tacks.length()-2);
}
public int getSize() { return this.size; }
public String encode(String input){
String str = "";
for (int x = 0; x < input.length(); x++) {
for (int i = 0; i < valueTable.size(); i++) {
if (valueTable.get(i) == input.charAt(x))
str += pathTable.get(i);
}
}
return str;
}
public String decode(String bits) {
String decodedStr = "";
for (int i = 0; i < bits.length(); i++) {
if (!getChar(bits.substring(0, i+1)).equals("")) {
decodedStr += getChar(bits.substring(0, i+1));
bits = bits.substring(i+1);
i = 0;
}
}
return decodedStr;
}
private String getChar(String bits) {
String character = "";
for (int i = 0; i < pathTable.size(); i++) {
if (pathTable.get(i).equals(bits))
character = valueTable.get(i).toString();
}
return character;
}
}
public static void main(String[] args) {
// for example assume that we have these letters with these different frequencies like below:
int freq[] = {10, 15, 12, 3, 4, 13, 1};
char code[] = {'a', 'e', 'i', 's', 't', ' ', '\n'};
HuffTree hTree = new HuffTree(freq, code);
System.out.println("Display Tree:");
HuffNode curr = hTree.root;
hTree.getTree(curr);
System.out.println("");
// and we want to build the huffman tree of the word sea :
System.out.println("Encode 'sea': " + hTree.encode("sea") +"\n");
System.out.println("Decode '" + hTree.encode("sea") + "': " + hTree.decode(hTree.encode("tea")));
}
}
If it's simply not compiling into a jar file, try the following command in command prompt or terminal.
jar cf jar-file input-file(s)
From Oracle: Creating jar File
To open command prompt, use WIN+R to open the run box, type cmd, and press enter.
navigate to the directory of your java file:
cd C:\Path\to\my\java\file\HuffNode.java
run the command:
jar cf HuffNode.jar HuffNode.java
If you have multiple .java files:
jar cf HuffNode.jar File1.java File2.java File3.java

Sort String s2 using the order of String s1 using either of comparable or comparator interface

i have two strings s1 and s2 and i would like to sort s2 based on the order of appearance of letters in s1 and if other alphabets are left in s2 sort them alphabetically.
Assume i have the following;
String s1 = "war";
String s2 = "Its awesome being a programmer";
output: waaarrrIbeeeeggimmmnoopsst.
I have written a code to do that already though buut i was wondering if its possible using the comparator/comparable interface to solve it.
Listed below is my code snippet.
public class Sort {
private static String a = "war";
private static String b = "Its awesome being a programmer";
static List<Character> list = new ArrayList<>();
static public void main(String[] args) {
Character s;
Character x;
System.out.println("String to be sorted: '" + b + "'");
System.out.println("Key for sort: '" + a + "'");
/*
* put all the string in a list
*/
for (int i = 0; i < b.length(); i++) {
s = b.charAt(i);
if (s != ' ') {
list.add(s);
}
}
/*
* compare individual chac in key with individaul char in string to sort
*/
StringBuilder sb = new StringBuilder();
for (int j = 0; j < a.length(); j++) {
x = a.charAt(j);
for (int k = 0; k < b.length(); k++) {
s = b.charAt(k);
if (x == s) {
sb.append(s);
list.remove(x);
}
}
}
/*
* check if list is empty if not, sort and append the rest to the stringbuilder
*/
if (!list.isEmpty()) {
Collections.sort(list);
for (char c : list) {
sb.append(c);
}
}
System.out.println("Sorted version of string: '" + sb.toString() + "'");
}
}
private static String a = "war";
private static String b = "Its awesome being a programmer".replace(" ","");
private static String answer = "waaarrrIbeeeeggimmmnoopsst";
public static void main(String[] args) {
List<String> characters = new ArrayList<String>(b.length());
for (int i=0;i<b.length();i++){
characters.add(String.valueOf(b.charAt(i)));
}
Collections.sort(characters,new CompareIt(a));
String sortedString = listToString(characters);
System.out.println(sortedString);
System.out.println(answer);
System.out.println(answer.equals(sortedString));
}
private static String listToString(List<String> listOfStrings){
StringBuilder builder = new StringBuilder();
for (String str : listOfStrings){
builder.append(str);
}
return builder.toString();
}
private static class CompareIt implements Comparator<String>{
private final String source;
public CompareIt(String source) {
super();
this.source = source;
}
public int compare(String o1, String o2) {
int i1 = source.indexOf(o1);
int i2 = source.indexOf(o2);
if (i1==-1 && i2!=-1){
return 1;
} else if (i1!=-1 && i2==-1){
return -1;
} else if (i1!=-1 && i2!=-1){
return i1 > i2 ? 1:-1;
} else {
return o1.compareTo(o2);
}
}
}
This seems to work.
EDITED: To include sysout that result matches expected answer provided in question.
EDIT2: Typo with final indexed comparison I had ? 1:0 instead of 1:-1.
public static void main(String[] args) {
String s1 = "war";
String s2 = "Its awesome being a programmer";
String result = "";
for (int i = 0; i < s1.length(); i++) {
int len = s2.length()
- s2.replace(String.valueOf(s1.charAt(i)), "").length();
s2 = s2.replace(String.valueOf(s1.charAt(i)), "").replace(" ", "");
for (int j = 0; j < len; j++)
result = result + String.valueOf(s1.charAt(i));
}
char[] remaining = s2.toCharArray();
Arrays.sort(remaining);
for (Character c : remaining)
result = result + String.valueOf(c);
System.out.println(result);
}
Try this: I tried without using any interface.
Output:
waaarrrIbeeeeggimmmnoopsst
public static Comparator<Character> compareOn(final String key) {
return new Comparator<Character>() {
public int compare(Character c1, Character c2) {
final int indexInKey1 = key.indexOf(c1);
final int indexInKey2 = key.indexOf(c2);
final int result;
if (indexInKey1 == -1 && indexInKey2 == -1) {
result = c1.compareTo(c2); //fall back to natural ordering
} else {
if (indexInKey1 == -1) {
result = 1;
} else if (indexInKey2 == -1) {
result = -1;
} else {
result = indexInKey1 - indexInKey2;
}
}
return result;
}
};
}
public static void main(String[] args) {
final String a = "war";
final String b = "Its awesome being a programmer";
final List<Character> chars = new ArrayList<Character>();
for (char c: b.toCharArray()) {
if (c != ' ') {
chars.add(c);
}
}
Collections.sort(chars, compareOn(a));
System.out.println(chars);
}

Replace / Censored

I'm working to a system called Quiz ...
The last thing that remains are the 'clues'. In present i have
<id value="100">
<question value="Who said E=mc2"/>
<answear value="Einstein"/>
<clue1 value="E*******"/>
<clue2 value="E******n"/>
<clue3 value="Ei****in"/>
</id>
and I want to remove from xml the clues because is hard to do them manually ...
so I made something but i failed
public class Test
{
public static void main(String[] argv) throws Exception
{
System.out.println(replaceSubString("Einstein", "*", 3));
}
static String[] letters = {"e","i"};
public static String replaceSubString(final String str, final String newToken, int max)
{
if ((str == null) || (newToken == null))
return str;
StringBuffer buf = new StringBuffer(str.length());
int start = 0, end = 0;
for(int i = 0; i < letters.length; i++)
{
if(Rnd.get(100) > 50) //50% to add the symbol
{
while ((end = str.indexOf(letters[i], start)) != -1)
{
buf.append(str.substring(start, end)).append(newToken);
start = end + 1;
if (--max == 0)
break;
}
}
}
buf.append(str.substring(start));
return buf.toString();
}
}
Compile Result => 'Einst*in'
the loop doesn't work.. idk .. only the first letter from array is replaced...
if someone offers to help me I would be very grateful..
-Thanks !
How about something like this?
public String generatClue(String answer,int level){
if(level >= answer.length()/2)
return answer.replaceAll("[^ ]","*");
return answer.substring(0,level)
+ answer.substring(level,answer.length()-level).replaceAll("[^ ]","*")
+ answer.substring(answer.length()-level);
}
Output:
generateClue("Einstein",1);
=> E******n
generateClue("Einstein",3);
=> Ein**ein
generateClue("Einstein",4)
=> Einstein
generateClue("Hans Christian Andersen",4)
=> Hans ********* ****rsen
EDIT: Here's one for random characters in the string:
public String generatClue2(String answer,int level){
if(answer.length()==level)
return answer.replaceAll("[^ ]","*");
Random rand=new Random();
for(int i=0; i<level; ++i){
char c;
int n;
do{
n=rand.nextInt(answer.length());
c=answer.charAt(n);
}
while(c == ' ' || c == '*');
answer = answer.substring(0,n) + '*' + answer.substring(n+1);
}
return answer;
}
Output:
generateClue2("Hans Christian Andersen",4);
=> Han* C*ri*tian Ande*sen
generateClue2("Hans Christian Andersen",4);
=> *ans Chr*sti*n An*ersen
generateClue2("Hans Christian Andersen",17);
=> H**s ******i** ***e****
generateClue2("Hans Christian Andersen",23);
=> **** ********* ********
Why not use something like JDOM and grab the XML elements by name?
SAXBuilder b = New SAXBuilder();
Document doc = b.build(pathToFile);
List<?> elements = b.getChildren("clue");
for (Element e : elements ) {
(Element) e.setAttribute("value",
obfuscateClueText(e.getAttribute("value")); //updated, see below
}
In response to your comment, could you write a method that generates the random clue symbols?
private String obfuscateClueText(String clueValue) {
//do something with clueValue
return obfuscatedValue;
}
I tried before this method
public class Test
{
static String s = "Hans Christian Andersen";
public static void main(String[] args)
{
char c = '*';
System.out.println(replaceCharAt(s, 0, c));
}
public static String replaceCharAt(String s, int pos1, char c)
{
StringBuffer buf = new StringBuffer(s);
int max = (s.length()-3), contor = 0;
while (contor < max)
{
for(int i = pos1; i < (s.length()); i++)
{
if(Rnd.get(100) > 50 && contor < max)
{
buf.setCharAt(i, c);
contor++;
}
}
}
return buf.toString();
}
}
the problem is that 'SPACE' from string ..
output: ***s*******i*n *nde**e*

replacing a character every occurrence in a string in java

I'm suppose to replace a "L" in a string every time it is found in the string HELLO WORLD, with "x". and the x is to increased every occurrence of L.
input: "HELLO WORLD"
output: "HExxxO WORxxxD"
use only String methods: .length; .indexOf; .substring
and .concat (or +).
EDIT
Here's my try:
public static String replace(String input,String pattern) {
String result = " ";
int stringLength;
int patternIndex;
while (input !=null) {
patternIndex = input.indexOf(pattern);
stringLength = input.length();
}
return result;
}
i only find the index of the pattern and the length of the string having problem with replacing the character.
First: sane solution:
StringBuilder sb = new StringBuilder();
StringBuilder r = new StringBuilder();
for( char c : "HELLO LAZY LIMBO WORLD" .toCharArray() ) {
if( c == 'L' ) {
sb.append(r.append('x'));
} else {
sb.append( c );
}
}
return sb.toString() );
Then modified to meed the criteria of only using valid methods .length; .indexOf; .substring and .concat (or +) ( removing toCharArray(); and StringBuilder )
public static String replace( String input ){
String replacement = "";
int iot = -1;
while( ( iot = input.indexOf('L')) > -1 ) {
input = input.substring(0,iot) +
( replacement+='x' ) +
input.substring(iot+1);
}
return input;
}
That one look like a for loop. Let's change it!
With only two statements ( declr and a for loop ):
public static String replace( String in ){
String x = "";
for( int i = 0; ( i = in.indexOf('L',i)) > -1 ;
in = in.substring(0,i++) + ( x=x+'x' ) + in.substring(i) );
return in;
}
Yields:
HExxxO xxxAZY xxxxIMBO WOxxxxxR
Now, that's! a for loop. I almost make Java look like perl.
static String xform(String helloWorld) {
if (helloWorld.intern() != "HELLO WORLD")
throw new IllegalArgumentException("bad World");
return "HExxxO WORxxxD";
}
and here is a very special version for the ones w/o sense of humor: the special edition - loplez&funless
public class TheLoop {
public static void main(String[] args) throws Throwable{
System.out.println(xForm2("Hello World -L".toUpperCase(),0));
}
static String xForm2(String s,int k){
return k<-1?"x"+xForm2(s,k+1):(k==-1?"":("L".equals(s.substring(0,1))?xForm2(s,-(k+1)-1) :s.substring(0,1))+(s.length()==1?"":xForm2(s.substring(1), "L".equals(s.substring(0,1))?k+1:k)));
}
}
200 bounty if anyone manages to write the function in a single line (single semicolon) and uglier than this
String x_ify(String input) {
String output = "";
int start = 0;
int count = 0;
int nextL;
while ((nextL = input.indexOf('L', start)) >= 0) {
if (nextL > start) {
output = output + input.substring(start, nextL);
}
++count;
for (int i = 0; i < count; ++i) {
output = output + "x";
}
start = nextL + 1;
}
if (start < input.length()) {
output += input.substring(start);
}
return output;
}
char charToReplace = 'l';
String str = " Hello World";
char newChar = 'x';
String newString = "x";
StringBuilder result = new StringBuilder();
for (int index = 0; index < str.length(); index++) {
if (str.charAt(index) == charToReplace) {
result.append(newString);
newString += newChar;
} else {
result.append(str.charAt(index));
}
}
System.out.println(result);
Note: it can be optimized
A bodyless one-liner for statement, specially for bestsss:
public static String replace(String s) {
for (String x=""; s.indexOf('L') > -1 ; s = s.substring(0,s.indexOf('L')) + ( x=x+'x' ) + s.substring(s.indexOf('L')+1) );
return s;
}
Although not using the standard functions you mentioned but this is an alternate way:
public static void first()
{
String input = "HELLO WORLD";
String X = "";
int numofL = input.length() - input.replaceAll("L+", "").length();
for(int i=0;i<numofL;i++)
X += "x";
String output = input.replaceAll("L+", X);
System.out.println(output);
}
public static void main(String[] args) {
String input = "HELLO WORLD";
String output = "";
String repl = "x";
int idx, start = 0;
while ((idx = input.indexOf('L', start)) > 0) {
output += input.substring(start, idx);
output += repl;
start = idx + 1;
repl += "x";
}
if (start < input.length()) {
output += input.substring(start);
}
System.out.println(output);
}
public class Main {
public static void main(String[] args) {
System.out.println(replace("hello world", "x"));
}
public static String replace(String in, String xs) {
return in.indexOf("l") != -1 ? replace(in.substring(0, in.indexOf("l")) + xs + in.substring(in.indexOf("l") + 1), xs + "x") : in;
}
}
public class ReplaceChar {
public static void replaceChar(String s, StringBuilder sb, int depth){
int i = s.indexOf('L');
if(i==-1){
return;
}
else
sb.append(s.substring(0,i));
for(int j=depth;j>0;j--){
sb.append('x');
}
replaceChar(s.substring(i+1),sb,++depth);
}
public static void main(String[] args){
StringBuilder sb = new StringBuilder();
System.out.println("main "+sb);
replaceChar("HELLO WORLD",sb,1);
}
}

Categories