Java - Removing char at - java

I don't think I have a firm understanding of why -1 works in this code: is it just a place marker allowing the program to continue to run? Any help or guidance would be greatly appreciated.
public class RemovingChar {
public static void main(String[]args)
{
String str = "Looking out the window of my small apartment";
String remove = "aeiou";
String x = " ";
for(int i=0; i<str.length(); i++)
{
char c = str.charAt(i);
if(remove.indexOf(c) == -1)
{
x+= c;
}
}
System.out.print(x);
}
}

public int indexOf(int ch)
if no such character occurs in this string, then -1 is returned.

-1 means Character Not found in the given String.
In docs its clearly written :
if no such character occurs in this string, then -1 is returned.

remove.indexOf(c) == -1
if c will not appear in remove string returns -1

indexOf() returns the index of the matched string... or -1 if not found.
e.g.
if your string is "hello" then the index of "ello" is 1 (because it's found at position 1).
or
if your string is "hello" then the index of "bla" is -1 (because it's not found and so indexOf returns -1)
Reference is at W3Schools

-1 is returned by the method indexOf if the parameter character is not in the remove variable.

StringBuilder strB = new StringBuilder(yourstring);
strB.deleteCharAt(yourstring.length() - 1);
System.out.print( strB.toString());
if you want to make a JButton will work like Backspace here's a Tutorial

Related

Writing method that spells word backwords and identifies number of palindromes

I'm new to java and I wrote this method to input a string word and output the word spelled backwards. The intent is to create a method and not use an already existing method such as the simple reverse. Please help point me in the direction of how to do this to reverse a word. I'm also trying to determine/count if there are palindromes. Please help! I've read other questions and I can't find anything specific enough to my case. I know that my code doesn't run, though I'm unsure how to fix it to get the correct output.
An example would be the word "backwards" to go to "sdrawkcab".
public static int reverseWord(String word) {
int palindromes = 0;
for (int i = word.length(); i >= 0; i--) {
System.out.print(i);
word.equalsIgnoreCase();
if (word.charAt(i)) == index(word.charAt(0 && 1))) {
palindromes++
System.out.println(palindromes)
}
return i;
}
}
There are multiple problems with your code.
1.The prototype of equalsIgnoreCase is
public boolean equalsIgnoreCase(String str);
So this method expect a String to be passed,but your not not passing anything here.To fix this,pass another string with whom you want to match your word like this..
word.equalsIgnoreCase("myAnotherString");
2.word.charAt(i);
Suppose word="qwerty",so indexing of each character will be like this
/* q w e r t y
0 1 2 3 4 5 */
So when you use i = word.length();i will 6 since word is of length 6.So
word.charAt(i) will search for character at index 6,but since there is not index 6,it will return an exception ArrayIndexOutOfBound.To fix this,start i from word.length()-1.
3.if (word.charAt(i));
This extra " ) ".Remove it.
Is Index() your own method?.If Yes,then check that also.
the below code prints the reverse of the input string and checks if it is a palindrome
public static void main(String[] args) {
String input = "dad";
char temp[] = input.toCharArray();//converting it to a array so that each character can be compared to the original string
char output[] = new char[temp.length];//taking another array of the same size as the input string
for (int i = temp.length - 1, j = 0; i >= 0; i--, j++) {//i variable for iterating through the input string and j variable for inserting data into output string.
System.out.print(temp[i]);//printing each variable of the input string in reverse order.
output[j] = temp[i];//inserting data into output string
}
System.out.println(String.valueOf(output));
if (String.valueOf(output).equalsIgnoreCase(input)) {//comparing the output string with the input string for palindrome check
System.out.println("palindrome");
}
}
Because your question about what is wrong with your code was already answered here is another way you could do it by using some concepts which are somewhat less low level than directly working with character arrays
public static boolean printWordAndCheckIfPalindrome(final String word) {
// Create a StringBuilder which helps when building a string
final StringBuilder reversedWordBuilder = new StringBuilder("");
// Get a stream of the character values of the word
word.chars()
// Add each character to the beginning of the reversed word,
// example for "backwards": "b", "ab", "cab", "kcab", ...
.forEach(characterOfString -> reversedWordBuilder.insert(0, (char) characterOfString));
// Generate a String out of the contents of the StringBuilder
final String reversedWord = reversedWordBuilder.toString();
// print the reversed word
System.out.println(reversedWord);
// if the reversed word equals the given word it is a palindrome
return word.equals(reversedWord);
}

Method to check if a Char is present on a specific String

I need to write a program where the main reads two strings as input: if the strings have the same length, then it has to pass the whole first string and the first char of the second string to a method called find, which has to return 'true' if the character appears even a single time on the string. If the length differs, then it will pass the whole second sentence and the last char of the first string to find. At last, the main will give whatever the method returns as output, so it has to be true, or false. I've created the whole main, and it works correctly, but I have no idea how to create the find method. Here is the code:
import java.util.Scanner;
public class Exercise {
/*
* public static boolean find(String... sentence, char... character) {
* // No, I can't use multiple varargs...
* }
*/
public static void main(String[] args) {
String first, second;
char firstChar, lastChar;
Scanner keyboard = new Scanner(System.in);
int lengthFirst, lengthSecond;
boolean goal = true;
first = keyboard.nextLine();
lengthFirst = first.length();
lastChar = first.charAt(lengthFirst - 1);
second = keyboard.nextLine();
lengthSecond = second.length();
firstChar = second.charAt(0);
System.out.println("Length 1: " + lengthFirst); // Those lines are test lines.
System.out.println("Length 2: " + lengthSecond); // They're here just to check
System.out.println("Char 1: " + firstChar); // if everything else works.
System.out.println("Char 2: " + lastChar);
if (lengthFirst == lengthSecond) {
goal = find(first, firstChar);
System.out.println("Goal is: " + goal);
System.exit(0);
} else
goal = find(second, lastChar);
System.out.println("Goal is: " + goal);
System.exit(0);
}
}
I was thinking about using the varargs option, using a varargs for the String, and another for the char, and then using a 'for' loop inside of the method to check if the character appears or not, and everything was easy on my head...but with some research I found out it will be a waste of time, because I can't use two varargs on the same method. The for loop idea works, but I can't figure out how to pass only the right String and the right Char. How should I pass them to the method, without passing them both?
Edit: No, this is not a duplicate. I allow loops, the other question doesn't. Also, my problem is about how am I supposed to pass multiple variables, but then using just some. That's an example:
The strings are both long 50, so the method needs to use only 'first' as String, and 'firstChar' as Char.
You can use String.indexOf().
returns the index within this string of the first occurrence of the
specified character. If a character with value ch occurs in the
character sequence represented by this String object, then the index
(in Unicode code units) of the first such occurrence is returned, if
no such character occurs in this string, then -1 is returned.
public static boolean find(String str, char ch){
if(str.indexOf(ch) == -1)
return false;
return true;
}
As you are thinking, you don't need four parameters for this function. You can use this function with two parameters for both cases:
goal = find(first, firstChar);
goal = find(second, lastChar);
EDIT I think you have misunderstood the way the parameters are mapped.
if you have a function like
public static boolean find(String str, char ch){
//do something
}
You don't need to call the find with same parameters str and ch, I mean find(str,ch). You can call them with any parameter, with any name, like :
goal = find(s,c); // s is a string and c is a char
goal = find(a,b); // a is a string and b is a char
when you call find(s,c), s will be mapped to the first argument in your function that is str and c will be mapped to your second argument that is ch.
This is the reason you are able to call both find(first, firstChar) and find(second, lastChar) with a single function.
private static boolean find(String str, char Char) {
for(int i=0;i<str.length();i++)
if(str.charAt(i)==Char)
return true;
return false;
}
This would help hopefully...
Seems like what you are looking for is:
if (second.indexOf(c) == -1) return false; //char c not found
return true;
Find will simply contain
private boolean find(String subject, char first) {
return subject.indexOf(first) > -1;
}

StringIndexOutOfBoundsException while converting string to char. Possible causes?

The code below is giving problems, I just need to turn a letter from a string into a character, and when I run my testing, I keep getting an error when the code gets to char c = t.charAt(0); The exact error message is:
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
I cannot get it to just turn the string letter into a char. Any tips would be greatly appreciated.
String[] zombies;
int num = 0;
Vector<Zombie> practice = new Vector<Zombie>();
String zombieString = "SZI1";
zombies = zombieString.split("");
for (String t : zombies) {
if (isNumeric(t)) {
int multiplier = Integer.parseInt(t);
String extraZombie = zombies[num - 1];
char x = extraZombie.charAt(0);
for (int i = 0; i <= multiplier; i++) {
Zombie zombie = Zombie.makeZombie(x);
practice.add(zombie);
}
} else {
char c = t.charAt(0);
//Zombie zombie = Zombie.makeZombie(c);
//practice.add(zombie);
num++;
}
}
Your split("") returns an empty string, and if you call charAt(0) on an empty string it will give this error.
To solve this you could replace the split("") operation with toCharArray(), this will directly generate an array of chars:
char[] zombies = zombieString.toCharArray();
Since it says "string index out of range 0", then your string has no characters in it. Might have something to do with the fact that you're telling String.split() to split on an empty string, when it needs a string delimiter on which to split.
Quoted:
https://stackoverflow.com/a/5235439/2214674
"SZI1".toCharArray()
But if you need strings
"SZI1".split("")
Edit: which will return an empty first value (extra empty String => [, S, Z, I,1].).

Finding various char's within a String

I have a basic String variable that contains the letter x a total of three times.
I have attempted to find x within the String using charAt, and then print the char and the next two characters next to it.
I have hit a snag within my code and would appreciate any help.
Here is my code.
public class StringX{
public static void main(String[] args){
String ss = "xarxatxm";
char first = ss.charAt(0);
char last == ss.charAt(3);
if(first == "x"){
String findx = ss.substring(0, 2);
}
if(last == "x"){
String findX = ss.substring(3, 5);
}
System.out.print(findx + findX);
}
}
Also, is there a way to implement the for loop to cycle through the String looking for x also?
I just need some advice to see where my code is going wrong.
You cannot find characters using charAt - it's for getting a character once you know where it is.
Is there a way to implement the for loop to cycle through the String looking for x also?
You need to use indexOf for finding positions of characters. Pass the initial position which is the position of the last x that you found so far to get the subsequent position.
For example, the code below
String s = "xarxatxm";
int pos = -1;
while (true) {
pos = s.indexOf('x', pos+1);
if (pos < 0) break;
System.out.println(pos);
}
prints 0 3 6 for the three positions of 'x' in the string.

StringBuffer Append Space (" ") Appends "null" Instead

Basically what I'm trying to do is take a String, and replace each letter in the alphabet inside, but preserving any spaces and not converting them to a "null" string, which is the main reason I am opening this question.
If I use the function below and pass the string "a b", instead of getting "ALPHA BETA" I get "ALPHAnullBETA".
I've tried all possible ways of checking if the individual char that is currently iterated through is a space, but nothing seems to work. All these scenarios give false as if it's a regular character.
public String charConvert(String s) {
Map<String, String> t = new HashMap<String, String>(); // Associative array
t.put("a", "ALPHA");
t.put("b", "BETA");
t.put("c", "GAMA");
// So on...
StringBuffer sb = new StringBuffer(0);
s = s.toLowerCase(); // This is my full string
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
String st = String.valueOf(c);
if (st.compareTo(" ") == 1) {
// This is the problematic condition
// The script should just append a space in this case, but nothing seems to invoke this scenario
} else {
sb.append(st);
}
}
s = sb.toString();
return s;
}
compareTo() will return 0 if the strings are equal. It returns a positive number of the first string is "greater than" the second.
But really there's no need to be comparing Strings. You can do something like this instead:
char c = s.charAt(i);
if(c == ' ') {
// do something
} else {
sb.append(c);
}
Or even better for your use case:
String st = s.substring(i,i+1);
if(t.contains(st)) {
sb.append(t.get(st));
} else {
sb.append(st);
}
To get even cleaner code, your Map should from Character to String instead of <String,String>.
String.compareTo() returns 0 if the strings are equal, not 1. Read about it here
Note that for this case you don't need to convert the char to a string, you could do
if(c == ' ')
use
Character.isWhitespace(c)
that solves the issue. Best practice.
First, of all, what is s in this example? It's hard to follow the code. Then, your compareTo seems off:
if (st.compareTo(" ") == 1)
Should be
if (st.compareTo(" ") == 0)
since 0 means "equal" (read up on compareTo)
From the compareTo documentation: The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal;
You have the wrong condition in if (st.compareTo(" ") == 1) {
The compareTo method of a String returns -1 if the source string precedes the test string, 0 for equality, and 1 if the source string follows. Your code checks for 1, and it should be checking for 0.

Categories