I saw a code segment as follows:
public class Practice
{
public static void main( String[] args )
{
String i = new String("I love you");
System.out.println(doSomething(i));
}
public static String doSomething( String s )
{
final String BLANK = " ";
String str = "";
String temp;
for ( int i = 0; i < s.length(); i++)
{
temp = s.substring(i, i + 1);
if (!(temp.equals(BLANK)))
{
str += temp;
}
}
return str;
}
}
I am very confused by the code here. I believe that whenever the for loop runs, one of the characters of the String will be extracted out. For example, when i = 0, temp should be "I", and i = 1, " ", i = 2, "l", etc. And when temp = " ", the if statement states that the blank will be adding to the String str. So whenever for-loop is run, the temp will change accordingly and hence cannot store the value unless its value is " ".
The output is Iloveyou.
Here is the problem:
if (!(temp.equals(BLANK)))
{
str += temp;
}
IF temp IS NOT (the ! means NOT) BLANK,
then do: str += temp;
Related
I am having trouble when I call my toString method and my code isn't following the correct format like it should, this is how I've been trying to call it.
public static void loadQueue(Queue<String> queue, String str) {
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
queue.toString();
}
}
Here is the toString that I want to format it to:
#Override
public String toString() {
String str = "[ ";
if ( !isEmpty() ) {
for (int i = 0; i < queue.length - 1; i++){
str += queue[i] + ", ";
}
str += queue[queue.length - 1] + " ";
}
str += "]";
return str;
Is there a better way to be calling this so that it prints out the correct out put?
Correct format should be [ a, b, c, d ] but all I'm getting is [ abcd ].
Edit, added toString method
If you're trying to use the values between commas in the str as the values to push onto the queue then you don't need to call toString().
Does this work for you?
public static void loadQueue(Queue<String> queue, String str) {
if (null == queue) throw new IllegalArgumentException("Expected non-null queue");
if (null == str) throw new IllegalArgumentException("Expected non-null str");
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
}
}
I can't tell which class your toString override is on, but it wouldn't be on string or queue.
Queue.toString will probably not be what you want. Is there some reason you want to override toString rather than just have a method by another name?
Technique #1
Put all the methods in your existing class
public String queueToString(Queue<String> queue) {
String str = "[ ";
if ( !isEmpty() ) {
for (int i = 0; i < queue.length - 1; i++){
str += queue[i] + ", ";
}
str += queue[queue.length - 1] + " ";
}
str += "]";
return str;
}
...
public static void loadQueue(Queue<String> queue, String str) {
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
}
System.out.println( queueToString(queue) );
}
Technique #2
Create a custom class for your queue and modify the behavior.
public class MyStringQueue extends Queue<String>
{
#Override
/* override the toString method here */
}
...
/* in your class, create an use a MyStringQueue instead of Queue<String> */
public static void loadQueue(MyStringQueue queue, String str) {
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
}
System.out.println( queue.toString() );
}
I'm trying to make an encryptor.What i want it to do:
Get the text i enter and reverse the first two letters of every word
and then display it again.
I have tried a lot of ways.This is the last one i've tried:
private void TranslateToEf(){
String storage = Display.getText();
String[] arr = storage.split("\\W+");
for ( String ss : arr) {
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
Display.appendText(swappedString + " ");
}
}
You may want to consider maintaining all the delimiters lost from the first String.split("\\W+") so they can be included in the final result. I would do that with a String.split("\\w+")
You may also want to consider that when you swap the first two letters, if the first letter is capital it becomes lowercase and the second letter becomes uppercase. Otherwise, just do a direct swap.
Code sample:
public static void main(String[] args) throws Exception {
String data = "Hello;World! My name is John. I write code.";
String[] words = data.split("\\W+");
String[] delimiters = data.split("\\w+");
int delimiterIndex = 0;
StringBuilder sb = new StringBuilder();
for (String word : words) {
if (word.length() < 2) {
sb.append(word);
} else {
char firstLetter = word.charAt(0);
char secondLetter = word.charAt(1);
if (Character.isUpperCase(firstLetter)) {
// Swap the first two letters and change casing
sb.append(Character.toUpperCase(secondLetter))
.append(Character.toLowerCase(firstLetter));
} else {
// Swap the first two letters
sb.append(secondLetter)
.append(firstLetter);
}
// Append the rest of the word past the first two letters
sb.append(word.substring(2));
}
// Append delimiters
if (delimiterIndex < delimiters.length) {
// Skip blank delimiters if there are any
while (delimiters[delimiterIndex].isEmpty()) {
delimiterIndex++;
}
// Append delimiter
sb.append(delimiters[delimiterIndex++]);
}
}
data = sb.toString();
// Display result
System.out.println(data);
}
Results:
Ehllo;Owrld! Ym anme si Ojhn. I rwite ocde.
public class Encrypto {
public static void main(String[] args) {
String input="Hello World";
String [] word = input.split(" ");
// System.out.println(word[0]);
String encryWord="";
for(int i=0;i<word.length;i++){
if (word[i].length() > 0) {
String tmp0 = String.valueOf(word[i].charAt(1));
String tmp1 = String.valueOf(word[i].charAt(0));
encryWord += tmp0.toLowerCase() + tmp1.toLowerCase() + word[i].substring(2) + " ";
}else{
encryWord +=word[i];
}
}
System.out.println(encryWord);
}
}
I think answer is more helpful for you
There are a few problems.
Declare zz outside the loop if you want to use it outside.
Append zz on every iteration. Not just assign it.
Something like this,
private void TranslateToEf(){
String storage = Display.getText();
String[] arr = storage.split("\\W+");
String zz = "";
for ( String ss : arr) {
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
String b= " ";
zz += swappedString + b;
}
Display.setText(zz + " ");
}
You are splitting with non-word (\W+) characters, but replacing it only with a space " ". This could alter the string with special characters.
Not sure what exactly you are looking for but i little modification in your code see if this suits your needs
String storage = "Test test t";
String[] arr = storage.split("\\W+");
String abc = "";
for ( String ss : arr) {
if(ss.length() > 1)
{
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String( c );
String b = " ";
String zz = swappedString + b;
abc = abc + zz;
}else{
abc = abc + ss;
}
}
System.out.println(abc);
In Java strings are immutable. You can't modify them "on the fly", you need to reassign them to a new instance.
Additionally, you are setting the last display text to zz, but zz is a local variable to your loop, and therefore it gets re-instantiated with every iteration. In other words, you would be assigning to display only the last word!
Here is what you have to do to make it work:
String storage = Display.getText();
String[] arr = storage.split("\\W+");
String[] newText = new String[arr.length];
for ( int i = 0; i<arr.length; i++) {
String original = arr[i];
String modified = ((char) original.charAt(1)) + ((char) original.charAt(0)) + original.substring(2);
newText[i] = modified;
}
//Join with spaces
String modifiedText = Arrays.asList(newText).stream().collect(Collectors.join(" "));
Display.setText(modifiedText);
Note that:
1) We are assuming all strings have at least 2 chars
2) that your splitting logic is correct. Can you think some edge cases where your regexp fails?
Here is my code to print string characters reversed in Java without using any API. But it's not working properly. Can anybody help me to correct it?
public static void main(String args[]) {
String input = "I am test";
String result = "";
for (int i = input.length() - 1; i > 0; i--) {
Character c = input.charAt(i);
if (c != ' ') {
result = c + result;
} else {
System.out.println(result + " ");
}
}
}
It is giving output "test amtest", while the output should be "test am I".
Please help me to get exact output without using predefined methods or API's.
There are four problems with your implementation:
You do not go all the way down to zero,
You put an end of line after each printout in the loop,
You do not print the "tail" result after the loop is over, and
You do not clear out result after printing it in the loop.
Fixing these issues will give you proper output (demo).
try
public static void main(String args[]) {
String input = "I am test";
String result = "";
int start=input.length()-1;
for (int i = input.length()-1; i >=0; i--) {
Character c = input.charAt(i);
if (c == ' ') {
for(int j=i+1;j<=start;j++)
result +=input.charAt(j);
result+=" ";
start=i-1;
}
else if (i==0)
{
for(int j=0;j<=start;j++)
result +=input.charAt(j);
}
}
System.out.println(result);
}//It is giving output as test amtest
//output should be : test am I
public static void main(String args[]) {
String input = "I am test";
String result = "";
String[] frags = input.split(" ");
for (int i = frags.length - 1; i >= 0; i--) {
System.out.print(frags[i] + " ");
}
System.out.println();
}
You can try recursion as well -
public static void main(String args[]) {
String input = "I am test";
List<String> listOfString = Arrays.asList(input.split(" "));
System.out.println(reverseString(listOfString));
}
private static String reverseString(List<String> input) {
int n = input.size();
String result = "";
if(input.isEmpty()){
return result;
}
if(n>1){
/*adding last element with space and changes the size of list as well
test + " " + [am, I]
test + " " + am + " " + [I]*/
result = input.get(n-1) + " " + reverseString(input.subList(0, n-1));
}else{
result = input.get(n-1);
}
return result;
}
hope it helps.
public static void main(String args[]){
String input = "I am test";
String result="";
for(int i=input.length()-1;i>=0;i--){
result=result+input.charAt(i);
}
System.out.println(result);
}
I am trying to build a function that evaluates an ArrayList (with contents from a file) and checks if all its characters are contained inside a variable (String), and act accordingly if thats not the case.
For example, ["hello", "I am new to Java", "Help me out!"].contains("aeIou") would be ok because all the chars in "aeIou" exist on the array. If it was "aeiou" it would return a message, because 'i' is not in the array, as it's case sensitive (it wouldn't need to test the others). But note that the test chars could be anything, not just letters.
I've built this function, and although it does compile without errors, it always returns that the character is not in the array, although it is:
private static void ValidateDecFile(String testStr, ArrayList<String> fcontents) {
int count = 0;
for(int j = 0; j < testStr.length(); j++) {
if(!Arrays.asList(fcontents).contains(testStr.charAt(j))) {
String errMsg = "Character '" + testStr.charAt(j) + "' is not in the string.";
}
}
}
From the searches I've made, I am assming this is a variable type problem, that does not return the expected "output" for the comparison.
But I've outputed testStr.length(), Arrays.asList(fcontents), testStr.charAt(j) and they all return the expected results, so I have no idea what's going on!
Whatever I do, this function always returns the errMsg String, and the char that "fails" the comparison is always the first char of testStr.
You can do the test in one line:
List<String> list;
String chars;
String regex = chars.replaceAll(".", "(?=.*\\Q$0\\E)") + ".*";
StringBuilder sb = new StringBuilder();
for (String s : list)
sb.append(s);
boolean hasAll = s.toString().matches(regex);
In java 8, the whole thing can be one line:
boolean hasAll = list.stream()
.collect(Collectors.joining(""))
.matches(chars.replaceAll(".", "(?=.*\\Q$0\\E)") + ".*");
The trick is to turn chars into a series of look ahead assertions and run that over the list concatenate into one giant string.
This will work for any input chars and any test chars, due to the regex treating each char as a literal.
Invoking contains() on a List will compare each element in the list to the argument, so in your example it would be comparing hello, I am new to Java and so on to each one of the search characters.
Inside the loop, you should be testing if any of the Strings in the List contain the character, not if one of the Strings in the List is the character.
Note that String.contains() needs a CharSequence as an argument, and charAt returns a char. You could use indexOf instead and test if it returns a positive number.
private static void ValidateDecFile(String testStr, ArrayList<String> fcontents) {
int count = 0;
String errMsg;
for(int j = 0; j < testStr.length(); j++) {
boolean found = false;
for (int i = 0;i<fcontents.size() && !found;i++) {
found = fcontents.get(i).indexOf(testStr.charAt(j)) >= 0;
}
if (!found){
errMsg = "Character '" + testStr.charAt(j) + "' is not in the string.";
}
}
}
Ideone demo.
Try the below one, You need to iterate and check each elements in the list and not the list
Hopt you will get the required
private static void ValidateDecFile(String testStr, ArrayList<String> fcontents) {
int count = 0;
boolean flag = false;
for(int j = 0; j < testStr.length(); j++) {
flag = false;
for(String content:fcontents){
if(content.contains(""+(testStr.charAt(j)))){
flag=true;
}
}
if(flag) {
String errMsg = "Character '" + testStr.charAt(j) + "' is not in the string.";
}
}
}
private static void ValidateDecFile(String testStr, ArrayList<String> fcontents) {
String fullStr = "";
for( int j = 0; j < fcontents.length(); j++ ) {
fullStr += fcontents.get( j );
}
for(int j = 0; j < testStr.length(); j++) {
if( !fullStr.contains( testStr.charAt(j) ) ) {
String errMsg = "Character '" + testStr.charAt(j) + "' is not in the string.";
System.out.println( errMsg );
}
}
}
In Java 8 using streams you can simplify it with the following:
String searchStr = "aeliou";
List<String> data = Arrays.asList("hello", "I am new to Java", "Help me out!");
for(int i = 0; i < searchStr.length(); i++ )
{
final int c = i;
if( ! data.stream().anyMatch(t -> t.contains(Character.toString(searchStr.charAt(c)))) )
System.out.println("not found:" + searchStr.charAt(i));
}
Or even shorter in a single statement using the chars() method from java 8:
String searchStr = "aeliou";
List<String> data = Arrays.asList("hello", "I am new to Java", "Help me out!");
searchStr.chars().forEach(c -> {
if (!data.stream().anyMatch(t -> t.contains(Character.toString((char)c))))
System.out.println("not found:" + Character.toString((char)c));
} );
From my current code how would i print the array{10,20,30,40,50,60,70,88,99,100} using a method display and calling it using System.out.println(myobject.display()) in my main.
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(){
String str = "";
for(int i = 0; i < 10; i++){
str= str+ " ";
}//for
return str;
}//display
My current method display does not display anything.
public TestA()
{
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
System.out.println(display(iA));
}
public static String display(int[] myData)
{
String str = "";
for(int i = 0; i < myData.length; i++){
str += myData[i]+ " ";
}
return str;
}
You need to call the method and print the result. Also use the array iA in your method.
System.out.println(display());
Your for loop is just adding an empty string to an empty string 10 times. You are never adding in the text from your array based on the index i. During your loop, you should be adding the space as well as the value at the current array position.
Your method display() is indeed doing something. It is returning 10 spaces, which are being printed out in your main method. You need to actually use the array at some point. Try something like:
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(int[] iA){
String str = "";
for(int i = 0; i < 10; i++){
str= str + Integer.toString(iA[i]) + " ";
}//for
return str;
}//display