Different behavior between String.value0f and Character.toString in Java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
In the following example, this program snippet does not compile, but if we replace the method Character.toString(char) by String.valueOf(char), everything is fine. What is the issue why Character.toString here ? In the documentation, these methods seem to have the same behavior. Thanks for explanation.
public static void main (String args[]) {
String source = "19/03/2016 16:34";
String result = Character.toString(source.substring(1,3));
System.out.print(result);
}

Character.toString(char c) method accepts char value as an argument and you are passing a String class instance which is produced from source.substring(1,3) method. String and char are incompatible types, so compiler can't create correct method call and pass the value
Your code should be rewritten as:
public static void main (String args[]) {
String source = "19/03/2016 16:34";
String result = source.substring(1, 3);
System.out.print(result);
//equivalent to the previous System.out.println call
System.out.print(source.substring(1, 3));
}
Also note that the first substring argument is an inclusive start index, the second one is exclusive end index and the leading index in Java String is 0 (not 1) exactly like in arrays (which is not a coincidence - String characters are stored in char array). So if you want to get a "19" String you should write source.substring(0, 2)

What does the compiler error message say? Anyway, source.substring(1,3) gives you a String while Character.toString() needs a char and does not accept a String.
String.valueOf(source.substring(1,3)) would call String.valueOf(Object), not String.valueOf(char).
You may obtain the same even simpler:
String result = source.substring(1,3);

Related

Parse String statement into a boolean expression [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
I have a string statement String s = sb.contains("is");
I want to use this in an if condition like
if (s) {
//do something
}
How can I achieve this functionality?
Edit: Basically I get a boolean logic along with strings as an input. Ex: "Stack & over & (is | flow)". I have an array of sentences and I have to pick every sentence that follows this logic. I thought I would construct a string like "sb.contains(stack) && sb.contains(over) && (sb.contains(is) || sb.contains(flow))" and I thought I would run this boolean logic over all the sentences. Is there any other way of doing this?
The contains method returns a boolean value, so you can just simply set the type of variable 's' to a boolean.
public class Main
{
public static void main(String[] args) {
String sb = "crisis";
boolean s = sb.contains("is");
if(s){
System.out.println("S is true");
System.out.println(s);
}
}
}
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains(java.lang.CharSequence)

How to write a for loop for encoding and decoding in java? the program only encode one letter when I enter a string. College level 1 lesson [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I should write a encoding and decoding program in a class and then use it in main. The program needs the position for each letter to increase by 2.
When I run the program, the problem is that when I enter a string (like cookie), only the last letter is encoding. Here is a Screenshot of program running.
What is the problem for my program.
Thanks.
The lesson is very basic tho and the assignment are forbid students import any other java method like base64.Only use the starter code.
The code I will put here as well
public class SimpleCipher {
/*
* comments here to overview the method
*/
public String encode(String text) {
String result = "";
char[] chars = text.toCharArray();
int length = chars.length;
for (char x: chars) {
x+=2;
result = Character.toString(x);
}
// ToDo
// convert text into char array
// reverse the array using provided method (see below)
// loop over array adding 2 to each element
// convert the char array back to a String named result
// return the resulting String.
return result;
}
The main problem is that you are overwriting your result in each iteration.
Instead you want to append the character to the result string.
You can simply do that with
result = result + Character.toString(x);
result += Character.toString(x); // shorter version
result += x; // java can append characters to strings without explicit conversion
According to the comment that is - even tho it is working - not the desired solution anyways. The task is to create a new character array and fill it.
Do that by creating a new array of the same length as the original, iterating over the indexes of your arrays ( for (int i=0; i<chars.length; i++) ) and for each index write the updated character into the new array. The string class has a constructor that accepts a char array.

Java - Event handle data protection for Strings with 2 data types [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
For event handling how can you check a string that has a combination of integers and a character?
For example - 1234p
If the user enters the example above, how can you check if the user enters integers first and then a character at the end? What kind of exception will be thrown if the data type input is not an integer or char?
You can use REGEX [0-9]+[a-zA-Z] to match if the string contains chars and integers otherwise throw an IllegalArgumentException
public void check(String input) {
if (!input.matches("[0-9]+[a-zA-Z]")) {
throw IllegalArgumentException("Not valid string");
}
// do other logic
}
So from your question it sounds like you expect a string that has all numbers except the last character that has to be an alphabet. You can check if the given string matches this condition the following way too:
String string = "1234p";
int length = string.length();
boolean numsFirst = string.substring(0, length - 1).chars().allMatch(x -> Character.isDigit(x));
boolean lastChar = Character.isDigit(string.charAt(length - 1));
if(numsFirst && lastChar)
return true;
else
return false;

What can I use instead of lcs (Longest common substring) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am trying to calculate the common string using lcs, but this algorithm only calculates 1 string. What can I use instead?
LCS = "aaabbbcccxxx" and "aaadddccc" result: "aaa"
but what i want= "aaaccc"
help please:)
You can apply your LCS algorithm once to get the "aaa" result, then remove this result from both strings, and re-apply your LCS algorithm to get the "ccc" result. Finally you will concatenate the temporary results.
Your java code in the main class may look like the following (assuming that you have a method LCS(String string_1 ,String string_2) performing yourLCS algorithm:`
public static ArrayList<String> temp_results;
public static String string_1,string_2,temp_result,final_string;
public static void main(String args[]) {
while (temp_result != null && !temp_result.equals("")) {
temp_result = LCS(string_1,string_2);
string_1.replaceAll(temp_result,"");
string_2.replaceAll(temp_result,"");
temp_results.add(temp_result);
}
for (String iterator_string : temp_results){
final_string = final_string + iterator_string;
}
System.out.println("This is the result "+final_string);
}
public static String LCS(String string_1, String string_2){
return ""; //put your actual LCS logic here, you should not return an empty string!
}

valid word counter out of bounds error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
{
public static int WordCount (String cString)
{
String currentWord;
int index;
int spacePos;
int validWordCount=0;
boolean validWord;
char upClowC;
cString=cString.trim()+" ";
spacePos=cString.indexOf(" ");
validWord=true;
for(index=0;index<cString.length();index++)
{
currentWord=cString.substring(0,spacePos);
upClowC=Character.toUpperCase(currentWord.charAt(index));
if(upClowC<'A'||upClowC>'Z')
{
validWord=false;
}
}
if(validWord==true)
{
validWordCount++;
}
return validWordCount;
}
public static void main(String[] args)
{
String sentence;
System.out.println("enter a sentence:");
sentence=EasyIn.getString();
WordCount(sentence);
}
}
I'm trying to create a method which takes a sentence and picks out the valid words (i.e. no numbers or symbols), but I keep getting an out of bounds error.
I can't use an array.
Your problem is here:
currentWord = cString.substring(0, spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
currentWord gets shorter, but index is still running from 0 to the length of the string.
General notes:
Follow Java naming conventions and change the name of your method to begin with small letter
if(validWord) is enough when you want to compare something to true, otherwise it's like asking "is it true that the value is true" instead of simply "is the value true"
Next time post your stack trace to get better and sooner help
In your code, you are doing
spacePos = cString.indexOf(" ");
And then inside the loop:
currentWord = cString.substring(0,spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
Now, because of the loop, the index will take values from 0 to your string length minus 1. If your substring (currentWord) is smaller than your string - which probably is -, then currentWord.charAt(index) will try to index out of the bounds of the substring, which is why you get the error.

Categories

Resources