I have written my own deleteSubString method as i'm experimenting creating all the java functions. However i'm having issues with the output it produces. Here is my code:
//deleteSubString
String subString = "ON";
String delString = "PONY";
String emp = "";
int delIndex = 0;
for(int i=0; i<delString.length()-1; i++){
if(delString.contains(subString)){
//do nothing
//read the rest of the string to confirm it contains
for(int j=delIndex; j<delString.length()-1; j++){
if(delString.contains(subString)){
//do nothing
}
else{
emp += delString.charAt(j);
}
}
}
System.out.println("Delete SubString");
System.out.println(emp);
}
What I expect to happen is the string to print out as "PY" but instead it chooses not to print anything at all. Any ideas would be greatly appreciated!
if(delString.contains(subString)){ is always true so emp is never set to a new String.
PONY contains ON and delString.length()-1 won't consider the last character,so your else part would not run.
Instead simply do
if(delString.contains(subString))
{
int delSize=subString.length();
int index1=delString.indexOf(subString);
int index2=index1+delSize;
return delString.substring(0,index1)+""+delString.substring(index2+1);
}
else return delString;
You have:
(delString.contains(subString))
This statement will always be true with the strings you've provided.
for(String s : delString.split(subString)) {
emp += s;
}
is this what you want?
String subString = "ONY";
String delString = "PONY";
String emp = "";
StringBuilder sb1=new StringBuilder(subString);
StringBuilder sb2=new StringBuilder(delString);
for(int i=0;i<sb2.length();i++)
{
for(int j=0;j<sb1.length();j++)
{
if(sb2.charAt(i)==sb1.charAt(j))
{
sb2.deleteCharAt(i);
}
}
}
emp=sb2.toString();
System.out.println(emp);
Sorry!!I have revamped the code but looks like its going to work fine...the problem with the string class is its immutability...The cod which you wrote doesnt give the require output...if it gives it can delete only first character i.e only O in your case Y is not getting deleted so i converted into StringBuffer class and wrote that..Happy Coding!
Related
I have a simple method where the goal is to add "[" and "]" before and after every "."
For example:
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"
Here is the function I've written, the problem here is where I have concatenate, why is this happening?
public static String defangIPaddr(String address) {
String returnStr = "";
for(int i = 0; i < address.length(); i++) {
char c = address.charAt(i);
if(c == '.') {
returnStr.concat("[");
returnStr.concat(".");
returnStr.concat("]");
} else {
returnStr.concat(address);
}
}
return returnStr;
}
Use replace() instead, just like this:
public static String defangIPaddr(String address) {
return address.replace(".", "[.]");
}
As has been explained, concat doesn't change the string, but rather returns a new string which is the concatenation of the two strings.
returnStr = returnStr.concat("[");
However, don't use concat. You rarely (if ever) need to use this. Instead use +=:
returnStr += "[";
But you don't even really want to use this, because it inefficiently creates a new string every time you do this. That's fine if the concatenation is a one-off, but you don't want to do this in a loop.
Use a StringBuilder instead, which allows you to append to the string without creating a new object each time:
String returnStr = new StringBuilder();
for(int i = 0; i < address.length(); i++) {
// ...
returnStr.append("[");
// ...
}
return returnStr.toString();
Or, of course, in this simple case, use replace.
This exercise is asking us to make a "RoadTrip" class that creates an ArrayList of geolocations using a geolocation class. Part of the exercise asks that we make a toString method within the RoadTrip Class that would end up returning a string like:
1. San Francisco (37.7833, -122.41671)
2. Los Angeles (34.052235, -118.2436831)
3. Las Vegas (36.114647, -115.1728131)
making a string for each of the GeoLocation objects within the ArrayList.
But I cannot put the return statement in a for loop. Here's an example of me "cheating" to get it do simulate what I would want it do actually do.
public String toString()
{
int counter = 1;
for (int i = 0; i < locationList.size() ; i++)
{
System.out.println(counter + ". " + locationList.get(i).toString());
counter++;
}
return "";
}
If I were to simply replace the System.out.println() with return and remove the return "";, I would get the errors:
RoadTrip.java:43: error: unreachable statement
counter++;
^
RoadTrip.java:45: error: missing return statement
}
^
2 errors
I saw other solutions that would utilize a StringBuilder, but I am assuming that the creators of the curriculum intend that we complete the exercises with the tools we are provided. Is there another method that I can use that would limit itself to the given "toolset"?
Pardon me if my techincal language is off, I'm still relatively new to coding.
Why the problem happens-
The control encounters the return statement on the first loop iteration and goes back to where the method was called from. Hence the following lines in the loop body are not reachable.
Since the return statement is within a loop and is subject to conditional execution, the compiler tells you there is a missing return statement. See code below:
public class Program
{
public static void main(String[] args) {
System.out.println(method());
}
static int method()
{
int i= (int)Math.random();
if(i>0)
return 1;
}
}
Since this is your assignment I won't be providing working code.
The easiest solution would be to define a String variable, store an empty String ("") in it, concat whatever you need in the loop and return it.
If you cannot use StringBuilder, why not concatenate Strings like this;
public String toString()
{
int counter = 1;
String str = "";
for (int i = 0; i < locationList.size() ; i++)
{
str = str + counter + ". " + locationList.get(i).toString();
str = str + "\n";
counter++;
}
return str;
}
P.S - I didn't run the code.
I periodically check if a string which I get from a web service changed. This works just fine but if an old string is deleted from my method triggers, too.
For Example:
//I get this at the beginning
"One,Two,Three"
//And at the next check I get this
"Two,Three"
So the String changed and my method returned true like it is supposed to do.
But I only want to return true if e.g. "Four" is added to the string.
Can anyone give me a solution for this problem?
Thank you a lot,
Freezed
if (!oldstring.contains(newstring)))
return true;
Perhaps you could use split like so
public class MyClass {
public static void main(String args[]) {
String oldString = "This,Is,A,Test";
String[] oldItems = oldString.split(",");
String newString = "This,Is,A,New";
String[] newItems = newString.split(",");
// For each new item, check all old items
for (String newItem: newItems)
{
Boolean foundItem = false;
for (String oldItem: oldItems)
{
// Item was already in the old items
if (newItem.equals(oldItem))
{
foundItem = true;
break;
}
}
// New item is not in the old list of items
if (!foundItem)
{
System.out.println("New item added: " + newItem);
}
}
}
}
Something like
newString.contains(oldString) && !newString.equals(oldString)
Why not just trigger when the length of the string increases? The question doesn't state that what is being added matters--only whether something is being added at all.
boolean result = false;
if(newString.length() > oldString.length()) {
result = true;
break;
}
return result;
EDIT: Based on further clarification, I understand that the length of the string is not the best indicator, since something can be removed and added at the same time, in which case OP wants true returned--even if length is shorter. Here's a solution that splits the strings into tokens, and then checks whether the last token of the old string occurs before the last token of the new string, because that means something was added after it:
boolean result = false;
String delim = ",";
String oldStringTokens[] = oldString.split(delim);
String newStringTokens[] = newString.split(delim);
for(int i = 0; i < newStringTokens.length; i++) {
if(oldStringTokens[oldStringTokens.length-1].equals(newStringTokens[i])) {
if(i < newStringTokens.length - 1) {
result = true;
}
}
}
return result;
So i'm using IntelliJ and the replace buzzword is highlighted. Most of the tips are over my head so i ignore them, but what i got for this one was that the result of string.replace is ignored. Why?
would i need something like ( string = string.replace(string.charAt(i));)?
import java.util.Scanner;
public class PhoneNumberDecipher {
public static String phoneNumber;
public static String Decipher(String string) {
string = phoneNumber;
for(int i =0; i<=phoneNumber.length(); i++) {
if(string.equalsIgnoreCase("A")
||string.equalsIgnoreCase("B")
||string.equalsIgnoreCase("C")) {
string.replace(string.charAt(i),'2')
}
else if(string.equalsIgnoreCase("D")
||string.equalsIgnoreCase("E")
||string.equalsIgnoreCase("F")) {
string.replace(string.charAt(i),'3');
}
else if(string.equalsIgnoreCase("G")
||string.equalsIgnoreCase("H")
||string.equalsIgnoreCase("I")) {
string.replace(string.charAt(i),'4');
}
else if(string.equalsIgnoreCase("J")
||string.equalsIgnoreCase("K")
||string.equalsIgnoreCase("L")) {
string.replace(string.charAt(i),'5');
}
else if(string.equalsIgnoreCase("M")
||string.equalsIgnoreCase("N")
||string.equalsIgnoreCase("O")) {
string.replace(string.charAt(i),'6');
}
else if(string.equalsIgnoreCase("P")
||string.equalsIgnoreCase("Q")
||string.equalsIgnoreCase("R")
|| string.equalsIgnoreCase("S")) {
string.replace(string.charAt(i),'7');
}
else if(string.equalsIgnoreCase("T")
||string.equalsIgnoreCase("U")
||string.equalsIgnoreCase("V")) {
string.replace(string.charAt(i),'8');
}
else if(string.equalsIgnoreCase("W")
||string.equalsIgnoreCase("X")
||string.equalsIgnoreCase("Y")
||string.equalsIgnoreCase("Z")) {
string.replace(string.charAt(i),'9');
}
}
return string;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please Enter a Phone Number you Wish to Decipher...");
phoneNumber = input.nextLine();
System.out.print(Decipher(phoneNumber));
}
}
String objects are immutable.
From the docs:
public String replace(char oldChar,char newChar)
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
Hope this helps.
IntelliJ is complaining that you're calling a method whose only effect is to return a value (String.replace) but you're ignoring that value. The program isn't doing anything at the moment because you're throwing away all the work it does.
You need to use the return value.
There are other bugs in there too. You might be able to progress a little further if you use some of this code:
StringBuilder convertedPhoneNumber = new StringBuilder();
// Your loop begins here
char curCharacter = phoneNumber.charAt(i);
if (curCharacter == 'a') {
convertedPhoneNumber.append("2");
}
// More conditional logic and rest of loop goes here.
return convertedPhoneNumber.toString();
I had the same problem, but i did it like this:
String newWord = oldWord.replace(oldChar,newChar);
use that statement
string = string.replace(string.charAt(i));
Why? String is an immutable object. Look at this thread to get a complete explanation. This a fundemental part of Java, so make sure you learn it well.
string = string.replace(string.charAt(i), '<The char to replace>') will work.
Refer to this article you might understand better:
https://alvinalexander.com/blog/post/java/faq-why-isnt-replace-replaceall-replacefirst-not-working/
Since string is immutable, you have to reassign the a string with the string.replace() string.
Here is the function i wrote. it take a Stringbuffer text then assign v[0]=text[0] , then starts from text[1] >>>text[n-1] the comparing. The vector v should contain the characters. I don't know where is the problem. Can you help me?
public void setdirectory(StringBuffer text)
{
String temp;
boolean t;
v.add(0,String.valueOf(text.charAt(0))); //A[0]=first letter in text.
for(int i=1;i<text.length();++i)
{
temp=String.valueOf(text.charAt(i));
try{
for(int j=0;j<v.capacity();++j)
{
if(!temp.equals(v.elementAt(j)))
{
v.add(i,temp);
}
v.trimToSize();
}
// System.out.println(v.capacity());
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("usage error");
}
}
}
If you're using Java 8+, then it might be simpler to use the new Stream API...
String str = "aabbc";
StringBuilder sb = new StringBuilder(str.length());
str.chars().distinct().forEach(c -> sb.append((char)c));
System.out.println(sb.toString());
Which prints
abc
I'd write a function to get unique characters, and assuming you need to preserve the insertion order, I'd use a LinkedHashSet<Character> and I'd prefer StringBuilder over StringBuffer. Something like
static String getUniqueCharacters(String text) {
Set<Character> set = new LinkedHashSet<>();
for (char ch : text.toCharArray()) {
set.add(ch);
}
StringBuilder sb = new StringBuilder();
for (char ch : set) {
sb.append(ch);
}
return sb.toString();
}
An alternative Java 8 solution is:
String str = "aabbc";
String str2 = str.chars().distinct().mapToObj(j->""+(char)j).collect(Collectors.joining());
System.out.println(str2);
Behind the scenes, this is similar to other answers here as IntStream::distinct is implemented using a LinkedHashSet<Integer>, and joining uses a StringBuilder.
You need to keep track of where you are adding your value in the vector. Also the number of objects in a vector is size(), not capacity() (look up the API for both; capacity() shows the current number of 'spaces' filled and available to fill before the vector needs to expand, it doesn't show how much of it has actually been filled).
Doh, and the third reason your code would not have worked: you were adding the character every time it found a non-matching one in the vector (over-writing itself each time so you would have only seen the last addition)
public void setdirectory(StringBuffer text) {
String temp;
boolean t;
int addAt = 0;
v.add(addAt,String.valueOf(text.charAt(0))); //A[0]=first letter in text.
for(int i=1;i<text.length();++i) {
temp=String.valueOf(text.charAt(i));
try {
boolean found = false
for(int j=0;j<v.size();++j) {
if(temp.equals(v.elementAt(j))) {
found = true;
break;
}
}
if (!found) {
addAt++;
v.add(addAt,temp);
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("usage error");
}
}
}
And although this would fix your code as it stands (which will be an important exercise for a beginner programmer), there are other ways of doing this that you should explore.