Java - Comparing single Char to String - java

Thanks for taking your time to look at my question. This is one of the methods I created for decrypting a message. This isn't the entire code, believe me I have been trying for hours messing with the code, I didnt just hop on here and hope you guys would do it for me, I'm just asking a HOW to do something!
Just so you guys know, I can't really change much from what I currently have because I'm limited based on the assignment.
My problem: I need to make any character that is an "x" equal a SPACE or " ". Basically I'm trying to hardcode every "x" within the string to become a space because it's not printing what it should be.
What I currently have:
public static String decryption(String s, int n)
{
int originalChar, decryptedChar;
String message = "";
char c;
for(int i = 0; i < s.length(); ++i)
{
c = s.charAt(i);
decryptedChar = (int)c;
if(decryptedChar + n > 126)
originalChar = 32 + ((decryptedChar + n) - 113);
// Problem here
if(c.equals("x"))
originalChar.equals(" ");
else
originalChar = decryptedChar + n;
message = message + (char)originalChar;
}//end for loop
return message;
}//end method
I marked the problem area. If anyone can tell me how to do this properly so that I can make any "x" equal " " instead that would be awesome! Thanks for your time.

your problem is with:
originalChar.equals(" ");
equals() method is a method that checks equality - it returns true if originalChar equals " ", and what matters in your case- it does not alter originalChar in any way, just compares it to " ".
if you want to set originalChar to be " ", you need to do originalChar = " "
In any case, a much easier solution would be:
s = s.replace("x"," ");

one of the problems is with .equals. That is not meant to do a comparison on a character, only Strings.
Further more below you try to assign a String to a character with ""s, a character assignment needs ''.
I dont get the encryption part so much so I mocked up just a simple replacement code.
Bonus: you may want to ensure both x and X are replaced.
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "xxistheXbestxandxmorexxHehehe";
int n = 100;
String message = decryption(s, n);
System.out.println(message);
}
public static String decryption(String s, int n)
{
int originalChar, decryptedChar;
String message = "";
String ret = "";
char c;
for(int i = 0; i < s.length(); ++i)
{
c = s.charAt(i);
decryptedChar = (int)c;
if(decryptedChar + n > 126)
originalChar = 32 + ((decryptedChar + n) - 113);
// Problem here
if(c =='x')
{originalChar = ' ';
c = ' ';}
else
{originalChar = decryptedChar + n;
c = c;}
message = message + (char)originalChar;
ret += c;
}//end for loop
//return message;
return ret;
}//end method

Use the method replaceAll of the String class.
For example:
String a = "AxBxCxD";
String b = a.replaceAll("x"," ");
String b is what you want, that is "A B C D". You need b, because replaceAll does not change a.
If you want to change a, you can set it to b:
a = b;
That's all :)

Related

Print a string backwards and shifted once ex: cat = ubd

I have successfully printed my String backwards, but I'm having a hard time getting it to shift forward a letter. My outputs have been numbers instead of letters, so I have tried to convert those numbers back to letters unsuccessfully. There is other code in this as well, but I only need help with this one bit.
package inlämningsuppgift4;
import java.util.Scanner;
public class Inlämningsuppgift4 {
public static void word(String w1){
//char a[]= w1.toCharArray();
for (int i=w1.length()-1; i>=0; i--)
//char c = 'a';
//c = (char) (((c - 'a' - 1) % 26) + 'a');
{System.out.print(w1.charAt(i));
}
System.out.println();
}
public static void word2(String w2){
for (int j=0;j<w2.length(); j++)
{System.out.print("*"+w2.charAt(j));
}
System.out.println("*");
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Ange ett ord: ");
String ord = input.nextLine();
word2(ord);
word(ord);
}
}
It seems like I was on the right path trying to set up "//char c" but I couldn't get it to function as written. I got that code from a questions search, but can't wrap my head around it. How do I make it fit with my code already written? Or should I find a different way?
You have two different problems:
reversing a string. There are a lot of ways to do it.
String s1 = "cat";
String s2 = "";
for (int i =0 ; i < s1.length(); i++) {
s2 = s1.charAt(i) + s2;
}
System.out.println(s2);
So just create a new string by adding strings backwards.
"Shifting" a character, which presumably means taking the code-point and modifying it, and possibly wrapping it (eg: Z wraps to A, instead of moving forward to [)
String s1 = "cat";
String s2 = "";
for (int i =0 ; i < s1.length(); i++) {
char c = s1.charAt(i);
c += 1;
// reverse string implementation omitted
}
System.out.println(s2);
Java seems to let you add directly to char so whatever works. Note that this does not care about wrapping, so z would not wrap to a. That's up to you to figure out.
Now you just need to combine that with the string building.

How to replace characters in a string in Java without using .replace?

The goal of this program is to prompt the user for a single character and a phrase, and then replace any instances of that character within that phrase with a '$'. My program below does just that, but when I showed it to my professor I was told that I cannot use .replace in the methods I built, so I have to figure out a way to not use that. I have worked at it for a while, and thus far I know that I can replace it with a for loop, but after several frustrating iterations, I can't seem to get it right. Excuse me if my code looks funky, I am still an introductory java student so I'm still learning the basics. I have provided a proposed solution at the end of my code snippet below.
public static char getKeyCharacter(String userInput) {
char keyCharacter;
Scanner inputStream = new Scanner(System.in);
while(userInput.length() > 1)
{
System.out.println("Please enter a SINGLE character to use as key: ");
userInput = inputStream.nextLine();
}
keyCharacter = userInput.charAt(0);
return keyCharacter;
}
public static String getString(String userResponse) {
Scanner inputStream = new Scanner(System.in);
String theString;
while(userResponse.length() > 500) {
System.out.println("Please enter a phrase or sentence >= 4 and <=500 characters: ");
userResponse = inputStream.nextLine();
}
while(userResponse.length() < 4) {
System.out.println("Please enter a phrase or sentence >= 4 and <=500 characters: ");
userResponse = inputStream.nextLine();
}
theString = userResponse;
return theString;
}
public static String maskCharacter(String theString, char keyCharacter){
String maskedString = "";
final char mask = '$';
maskedString = maskedString + theString.replace(keyCharacter, mask);
System.out.println("String with " + keyCharacter + " masked: ");
return maskedString;
}
public static String removeCharacter(String theString, char keyCharacter) {
String modifiedString = " ";
final char replaceChar = ' ';
modifiedString = modifiedString + theString.replace(keyCharacter, replaceChar);
System.out.println("String with " + keyCharacter + " removed:");
return modifiedString;
}
public static int countKey(String theString, char keyCharacter) {
int charCount = 0;
for (int c = 0; c < theString.length(); c++) {
if (theString.charAt(c) == keyCharacter) {
charCount++;
}
}
System.out.println("Occurences of " + keyCharacter + " in string:");
return charCount;
}
}
I believe the solution is will look something like this, but thus far I've been unsuccesful -
public static String maskCharacter(String theString, char keyCharacter){
String maskedString = "";
final char mask = '$';
for (int k = 0; k < theString.length(); k++) {
if (theString.charAt(k) == keyCharacter) {
keyCharacter = mask;
}
System.out.println("String with " + keyCharacter + " masked: ");
return maskedString;
}
My issue lies in making the maskedString = theString with all the keyCharacters replaced by mask. For the record, I have yet to learn anything about those fancy arrays, so if there is a way to do this using a simple for loop I would greatly appreciate it. Thank you for the assistance in advance!
I would use a StringBuilder and String#toCharArray() with a simple for-each loop. Like,
public static String maskCharacter(String theString, char keyCharacter){
StringBuilder sb = new StringBuilder();
for (char ch : theString.toCharArray()) {
if (ch == keyCharacter) {
sb.append('$'); // <-- mask keyCharacter(s).
} else {
sb.append(ch); // <-- it isn't the character to mask
}
}
return sb.toString();
}
I wouldn't use a StringBuilder: just use the result of toCharArray() directly:
char[] cs = theString.toCharArray();
for (int i = 0; i < cs.length; ++i) {
if (cs[i] == keyCharacter) cs[i] = '$';
}
return new String(cs);
Not only is it more concise, but:
It will run faster, because it's cheaper to access an array element than to invoke a method; and because it doesn't require StringBuilder's internal buffer to resize (although you could just pre-size that);
It will use less memory, because it doesn't require storage for the copy inside StringBuilder.
public static String maskCharacter(String theString, char keyCharacter){
String masked = "";
for (int i = 0 ; i < theString.length() ; i++) {
if (theString.charAt(i) == keyCharacter) {
masked += "$";
}
else {
masked+=theString.charAt(i)+"";
}
}
return masked;
}
An answer that only uses string concatenation and basic character access.
You seem to know that you can concatenate something to a string and get a different string.
maskedString = maskedString + ...;
You also know you can build a for-loop that gets each individual character using .charAt()
for (int k = 0; k < theString.length(); k++) {
char nch = theString.charAt(k);
}
You can check equality between chars
if (nch == keyCharacter)
... assuming you know about else-branches, isn't it clear you just need to put them together?
if (nch == keyCharacter) {
// append '$' to maskedString
}
else {
// append nch to maskedString
}
Of course this creates a new string on every loop iteration so it is not terribly efficient. But I don't think that's the point of the exercise.

Counting the number of specific occurrences in a java String

I am attempting to solve a problem where I create a method that counts the number of occurrences of capital and lowercase ("A" or "a") in a certain string. I have been working on this problem for a week now, and the main error that I am receiving is that "char cannot be dereferenced". Can anyone point me in the correct direction on this Java problem? Thank you.
class Main{
public static int countA (String s)
{
String s1 = "a";
String s2 = "A";
int count = 0;
for (int i = 0; i < s.length; i++){
String s3 = s.charAt(i);
if (s3.equals(s1) || s3.equals(s2)){
count += 1;
}
else{
System.out.print("");
}
}
}
//test case below (dont change):
public static void main(String[] args){
System.out.println(countA("aaA")); //3
System.out.println(countA("aaBBdf8k3AAadnklA")); //6
}
}
try a simpler solution
String in = "aaBBdf8k3AAadnklA";
String out = in.replace ("A", "").replace ("a", "");
int lenDiff = in.length () - out.length ();
Also as #chris mentions in his answer, the String could be converted to lowercase first and then only do a single check
the main error that I am receiving is that "char cannot be
dereferenced"
change this:
s.length // this syntax is incorrect
to this:
s.length() // this is how you invoke the length method on a string
also, change this:
String s3 = s.charAt(i); // you cannot assign a char type to string type
to this:
String s3 = Character.toString(s.charAt(i)); // convert the char to string
another solution to accomplishing your task in a simpler manner is by using the Stream#filter method. Then convert each String within the Stream to lowercase prior to comparison, if any Strings match "a" we keep it, if not we ignore it and at the end, we simply return the count.
public static int countA(String input)
{
return (int)Arrays.stream(input.split("")).filter(s -> s.toLowerCase().equals("a")).count();
}
For counting the number of time 'a' or 'A' appears in a String:
public int numberOfA(String s) {
s = s.toLowerCase();
int sum = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == 'a')
sum++;
}
return sum;
}
Or just replace everything else and see how long your string is:
int numberOfA = string.replaceAll("[^aA]", "").length();
To find the number of times character a and A appear in string.
int numA = string.replaceAll("[^aA]","").length();

Java - Reverse String null error

The input is meant to appear like this, example.
\n
Kazan R
\n
6789
\n
Nzk462
\n
However the output I receive looks like this
kzn462nullnzk
Why is this? and How can i solve it?
private void btnGenerateActionPerformed(java.awt.event.ActionEvent evt) {
secondname = JOptionPane.showInputDialog("Enter your surname:");
firstname = JOptionPane.showInputDialog("Enter your firstname:");
idno = JOptionPane.showInputDialog("Enter your idno:");
nametag = firstname.substring(0, 1);
initials = secondname + " " + nametag;
int randnum;
do {
randnum = (int) (Math.random() * 900) + 100;
} while (randnum % 2 != 0);
code = secondname.replaceAll("[aeiou || AEIOU](?!\\b)", "")+randnum ;
txaDisplay.append(initials + '\n' + idno.substring(6,10) + '\n' + code);
int length = secondname.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + secondname.charAt(i);
}
String end = reverse + code;
txaDisplay.append( reverse);
Why don't you use
new StringBuilder(secondname).reverse().toString()
to reverse your String? It's better, simple and more maintanable.
Get the character array from your source string
Create a new char array of same length
Start iterating from 0 to (sourceStringLength-1)
In each iteration, get the last character
from the end in your source array and populate in your new array
Create a new string from this new array
String source = "abcdefg";
char[] chars = source.toCharArray();
char[] reverseChars = new char[source.length()];
int len = source.length();
for(int i= 0; i < len; i++){
reverseChars[i] = chars[len-1-i];
}
String reverse = new String(reverseChars);
System.out.println(reverse);
Since You don't want to use StringBuilder/StringBuffer.
Try this
String reversedString="";
for(int i=inputString.length-1;i>=0;){
reversedString+=inputString.charAt(i--);
}
I think the problem is your definition of reverse, maybe you have something like:
String reverse;
Then you don't initialize your "reverse" so when your program makes the first concatenation in your loop, it looks like this:
reverse = null + secondname.charAt(i);
The null value is converted to a string so it can be visible in the output.
I hope this information helps you.
Good Luck.

Two variables initialization at once in for loop

I want to write a code for reversing of string.
I know there are many methods for it. However, I want to try using Arrays. But I am having problem with the output.
Following is my code:
package practice_package;
public class Practice_Class {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = "Jeevan";
char[] a = s1.toCharArray();
String s2 = "satyasahithi";
char[] b = s2.toCharArray();
String rs1 = new String(reverse(a));
System.out.println("The reverse of '" + s1 + "' is: '" + rs1 + "'");
String rs2 = new String(reverse(b));
System.out.println("The reverse of '" + s2 + "' is: '" + rs2 + "'");
}
public static char[] reverse(char[] args) {
char[] r = args;
int i,j;
for(i=args.length-1,j=0; i>=0 && j<args.length; i--, j++) {
r[j]= args[i];
}
System.out.println(r);
return r;
}
}
And my output is:
navvan
The reverse of 'Jeevan' is: 'navvan'
ihtihaahithi
The reverse of 'satyasahithi' is: 'ihtihaahithi'
As you can see, only the first half of the string is being reversed while the second half remains as it is.
What's the wrong in the code. Can I initialize two variables at once in 'for' loop like that. Where am I missing the logic?
When you assign last to first, you lose the char, you should keep it in temporary and assign to other.
for(i=args.length-1,j=0; i>=0 && j<args.length/2; i--, j++) {
char t = r[j];
r[j]= r[i];
r[i] = t;
}
Use StringBuffer.reverse()
String s1 = "Jeevan";
StringBuffer a = new StringBuffer(s1);
System.out.println(a.reverse());
The logic inside your for loop. Lets consider the first iteration where i points to 5 (in case of string Jeevan) and j points to 0. When you say r[j]= args[i] J will be replaces with n and you lose the character J. This is the part where your logic went wrong. As a solution either you can take another array and store as given below
public static char[] reverse(char[] args) {
char[] r = new char[args.length];
int i,j;
for(i=args.length-1,j=0; i>=0 && j<args.length; i--, j++) {
r[j]= args[i];
}
System.out.println(r);
return r;
}
or as nr4bt suggested above.

Categories

Resources