this is my first question here and I've been desperate enough to ask it, since I haven't found any other posts related to my problems or which are related but too complex and don't relate to the actual code I have.
The thing is I want to ask the user for input and the input's letters shall be inverted, e.g: Hello to hELLO and vice versa. But the warning comes up "Result of 'Character.toUpperCase()' is ignored", any idea how to solve?
for (int i = 0; i < word.length(); i++)
{
if (Character.isLowerCase(word.charAt(i)))
{
Character.toUpperCase(word.charAt(i));
}
else
{
Character.toLowerCase(word.charAt(i));
}
}
Hello and welcome to Stack overflow.
The problem is that the Character.toUpperCase() won't overwrite the character in the string.
public static void main(String[] args) {
String word = "Hello";
String wordInverted = "";
for (int i = 0; i < word.length(); i++)
{
//Get the char as a substring
String subChar = word.substring(i, i+1);
if (Character.isUpperCase(word.charAt(i)))
{
subChar = subChar.toLowerCase();
}
else
{
subChar = subChar.toUpperCase();
}
wordInverted += subChar; //Add the newly inverted character to the inverted string
}
System.out.println(wordInverted);
}
Related
I will ask this again. I have this problem which is to create a program that would read a string input from the user (sentence or word). And the Nth number (from the user) will turn into upper case and the rest will be in lowercase.
Example:
string = "good morning everyone"
n = 2
Output = gOod mOrning eVeryone
for (int x = 0; x < s.length(); x++)
if (x == n-1){
temp+=(""+s.charAt(x)).toUpperCase();
}else{
temp+=(""+s.charAt(x)).toLowerCase();
}
s=temp;
System.out.println(s);
}
Output: gOod morning everyone
I know what you want to happen - but you didn't phrase your question very well. The only part your missing is iterating through every word in the sentence. If you asked "how do I apply a function on every word in a String" you likely would have gotten a better response.
This is a bit sloppy since it adds a trailing " " to the end - but you could fix that easily.
public class Test {
static String test = "This is a test.";
public static void main(String[] args) {
String[] words = test.split(" ");
String result = "";
for (String word : words) {
result += nthToUpperCase(word, 2);
result += " ";
}
System.out.println(result);
}
public static String NthToUpperCase(String s, int n) {
String temp = "";
for (int i = 0; i < s.length(); i++) {
if (i == (n-1)) {
temp+=Character.toString(s.charAt(i)).toUpperCase();
} else {
temp+=Character.toString(s.charAt(i));
}
}
return temp;
}
}
You can do this with two for loops. Iterate over each word and within the iteration iterate over each character.
toUpperCase(2, "good morning everyone");
private static void toUpperCase(int nth, String sentence) {
StringBuilder result = new StringBuilder();
for(String word : sentence.split(" ")) {
for(int i = 0; i < word.length(); i++) {
if(i > 0 && i % nth - 1 == 0) {
result.append(Character.toString(word.charAt(i)).toUpperCase());
} else {
result.append(word.charAt(i));
}
}
result.append(" ");
}
System.out.println(result);
}
gOoD mOrNiNg eVeRyOnE
I am not very good at java so that's why some things might not make sense at all. I was just simply using code from bits I found online which I know is wrong.
My current issue is that it simply prints a blank code; I am not sure how to get it to print it like so:
Input:
APPLE
Output:
A
AP
APP
APPL
APPLE
Current Code:
import java.util.Scanner;
public class WordGrow
{
public static void main(String[]args)
{
//take your word input
//enter word as a parameter in WordGrow()
System.out.println("Please enter the word to *GROW*");
Scanner scan = new Scanner(System.in);
String theword = scan.next();
System.out.println(makeTree(theword, theword.length()));
}
public static String makeTree(String word, int len)
{
int count = 0;
//start with the first letter and print
//and add another letter each time the loop runs
if (word.length() > 0)
{
for(int i = 0; i < word.length();i++)
{
return word.substring(0, i++);
}
}
return (word.charAt(1) + makeTree(word, len));
}
}
Take Java out of it. Let's take this back to pen and paper.
First, look at the pattern you're printing out. How would you print out just one letter of that string? How would you print out two?
Let's start with that approach. Let's try to print out one letter in that string.
public void printStringChain(String word) {
System.out.println(word.substring(0, 1));
}
What about two letters?
public void printStringChain(String word) {
System.out.println(word.substring(0, 2));
}
What about word.length() letters?
public void printStringChain(String word) {
System.out.println(word.substring(0, word.length()));
}
The main thing I'm trying to get you to see is that there's a pattern here. In order to accomplish this, you likely need to go from zero to the length of your string in order to print out each line on its own.
Here's a start. I leave figuring out the nuance and barriers inside of the substring as an exercise for the reader.
public void printStringChain(String word) {
for (int i = 0; i < word.length(); i++) {
// the question mark relates to i, but in what way?
System.out.println(word.substring(0, (?)));
}
}
If recursion is not compulsory, you could simply iterate through the given String:
String str = "APPLE";
for(int x=0; x<str.length(); x++){
System.out.println(str.substring(0, x+1));
}
Output:
A
AP
APP
APPL
APPLE
One cannot return multiple times, at the first moment the result is passed on to the caller.
For String there is a buffering class for efficiency, the StringBuilder.
Including the empty string that would be:
public static String makeTree(String word) {
StringBuiilder sb = new StringBuilder();
for (int i = 0; i < word.length(); i++){
sb.append(word.substring(0, i));
sb.append("\r\n");
}
return sb.toString();
}
It uses the Windows end-of-line characters CR+LF aka \r\n.
You can make that platform independent, but you get the idea.
WITH RECURSION
public static String makeTree(String word)
{
if (word.length() <= 1){
return word;
}
return makeTree(word.subSequence(0, word.length()-1).toString()) + System.lineSeparator() + word;
}
In a recent interview, I was asked this to find the length of the longest sub-string with no consecutive repeating characters. This is different from the standard question, since it considers only consecutive repeating characters.
For example :
WOOD : 2
Italics : 7
This, of course, has to be done in O(N) time and space.
Go down the string character by character. Keep track of how many characters you've advanced without hitting a repeat in a var say "repeatcounter". If the next character matches the current character record the counter in a separate variable (only if it's bigger than what's already in there) and reset the repeatcounter.
In Python, I would approach it like this:
def interview(s):
current = longest = 0
for index, char in enumerate(s):
if index and char == s[index - 1]:
longest, current = max(longest, current), 0
current += 1
return max(longest, current)
public static void main(String[] args){
String s = "italics";
char[] c = s.toCharArray();
int tmp = 1;
for (int i = 1; i < s.length(); i++) {
if (c[i] == c[i-1]){
tmp = 0;
continue;
}
tmp++;
}
System.out.println(tmp);
}
output = 1
s = "italics"
output = 7
Hope the below code helps you. Thanks.
import java.util.HashSet;
public class SubString {
public static String subString(String input){
HashSet<Character> set = new HashSet<Character>();
String longestOverAll = "";
String longestTillNow = "";
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (set.contains(c)) {
longestTillNow = "";
set.clear();
}
longestTillNow += c;
set.add(c);
if (longestTillNow.length() > longestOverAll.length()) {
longestOverAll = longestTillNow;
}
}
return longestOverAll;
}
public static void main(String[] args) {
String input = "kaveeshkanwal abcvdghytrqp";//"substringfindout";
System.out.println(subString(input));
}
}
Please help me to identify my mistakes in this code. I am new to Java. Excuse me if I have done any mistake. This is one of codingbat java questions. I am getting Timed Out error message for some inputs like "xxxyakyyyakzzz". For some inputs like "yakpak" and "pakyak" this code is working fine.
Question:
Suppose the string "yak" is unlucky. Given a string, return a version where all the "yak" are removed, but the "a" can be any char. The "yak" strings will not overlap.
public String stringYak(String str) {
String result = "";
int yakIndex = str.indexOf("yak");
if (yakIndex == -1)
return str; //there is no yak
//there is at least one yak
//if there are yaks store their indexes in the arraylist
ArrayList<Integer> yakArray = new ArrayList<Integer>();
int length = str.length();
yakIndex = 0;
while (yakIndex < length - 3) {
yakIndex = str.indexOf("yak", yakIndex);
yakArray.add(yakIndex);
yakIndex += 3;
}//all the yak indexes are stored in the arraylist
//iterate through the arraylist. skip the yaks and get non-yak substrings
for(int i = 0; i < length; i++) {
if (yakArray.contains(i))
i = i + 2;
else
result = result + str.charAt(i);
}
return result;
}
Shouldn't you be looking for any three character sequence starting with a 'y' and ending with a 'k'? Like so?
public static String stringYak(String str) {
char[] chars = (str != null) ? str.toCharArray()
: new char[] {};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == 'y' && chars[i + 2] == 'k') { // if we have 'y' and two away is 'k'
// then it's unlucky...
i += 2;
continue; //skip the statement sb.append
} //do not append any pattern like y1k or yak etc
sb.append(chars[i]);
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(stringYak("1yik2yak3yuk4")); // Remove the "unlucky" strings
// The result will be 1234.
}
It looks like your programming assignment. You need to use regular expressions.
Look at http://www.vogella.com/articles/JavaRegularExpressions/article.html#regex for more information.
Remember, that you can not use contains. Your code maybe something like
result = str.removeall("y\wk")
you can try this
public static String stringYak(String str) {
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i)=='y'){
str=str.replace("yak", "");
}
}
return str;
}
What I am trying to do, is create a method, that has a string and a character as parameters, the method then takes the string and searches for the given character. If the string contains that character, it returns an array of integers of where the character showed up. Here is what I have so far:
public class Sheet {
public static void main(String[] args) {
String string = "bbnnbb";
String complete = null;
//*******
for(int i = 0; i < string.length(); i++){
complete = StringSearch(string,'n').toString();
}
//********
}
public static int[] StringSearch(String string, char lookfor) {
int[]num = new int[string.length()];
for(int i = 0; i < num.length; i++){
if(string.charAt(i)== lookfor){
num[i] = i;
}
}
return num;
}
}
The method works fine, and returns this:
0
0
2
3
0
0
What I am trying to do, is make those into 1 string so it would look like this "002300".
Is there any possible way of doing this? I have tried to do it in the starred area of the code, but I have had no success.
just do
StringBuffer strBuff = new StringBuffer();
for(int i = 0; i<str.length(); i++)
{
if(str.charAt(i) == reqChar)
{
strBuff.append(str.charAt(i));
}
else
{
strBuff.append('0');
}
}
return str.toString();
Just add the result to the existing string with the += operator
String complete = "";
for(...)
complete += StringSearch(string,'n').toString();
I would just use java's regex library, that way it's more flexible (eg if you want to look for more than just a single character). Plus it's highly optimized.
StringBuilder positions = "";
Pattern pattern = Pattern.compile(string);
Matcher matcher = pattern.matcher(lookfor);
while(matcher.find()){
positions.append(matcher.start());
}
return positions;
Updated with StringBuilder for better practices.
public static String StringSearch(String string, char lookfor) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < string.length; i++){
if(string.charAt(i) == lookfor)
sb.append(i);
else
sb.append("0");
}
return sb.toString();
}
Then you can just call it once, without a for loop. Not sure why you call it for every character in the string.
complete = StringSearch(string,'n');