0

I'm trying to make a short program that converts any string into T H I S F O N T.

For example: "This is a test sentence" turns into "T H I S I S A T E S T S E N T N C E"

I have a StringBuilder inside a while loop, but using finale.insert(i, '\t'); doesn't work.

import java.util.Scanner;

public class Executable {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String x;
        int i = 0;

        System.out.print("Input text here: ");
        x = input.nextLine();

        StringBuilder finale = new StringBuilder(x.toUpperCase());

        while(i > finale.length()) {
            if(finale.substring(i, i) == " ") {
                i += 2;

                finale.insert(i, '\t');
            }
        }

        System.out.println(finale);

    }
}

Any help?

5
  • What do you mean by "doesn't work?" Commented Oct 30, 2018 at 20:38
  • while(i > finale.length()) should be while(i < finale.length()) Commented Oct 30, 2018 at 20:38
  • Also, you are trying to compare Strings using ==; this is incorrect. Use string.equals() instead. Commented Oct 30, 2018 at 20:39
  • Plus, your while loop will never run because i is never greater than the length of your original string. Commented Oct 30, 2018 at 20:40
  • Okay, so I fixed what @mettleap said, and made it a .equals, but now it never prints anything. Sorry, I'm still relatively new to coding. Commented Oct 30, 2018 at 20:42

6 Answers 6

1

You have a few issues with your code. Before I present an implementation that works, let's look at those other issues.

  1. Your while loop checks if i > finale.length(). Since i = 0 the while loop never has a chance to begin.
  2. You are comparing strings using == and this is not correct. == is used to confirm two objects are equal, not the value of two strings. You would need to use string.equals() instead.
  3. You're doing too much in your loop anyway. Using a simple for loop can accomplish the goal quite simply.

Here is a new loop you can use instead of what you have:

for (int i = 1; i < finale.length(); i++) {
    finale.insert(i++, " ");
}

The output: T H I S F O N T


For those unfamiliar with for loops, here's a very simple breakdown of how the above is structured.

The for loop is defined in three parts:

for (variable_to_increment; repeat_until_this_condition_is_met; modify_variable_on_each_iteration) {
    // Code to be executed during each pass of the loop
}
  • First, we define a variable that we can track on each loop: int i = 1. By setting i = 1, we are going to skip the first character in the string.
  • The next statement, i < finale.length() means that we want to keep repeating this loop until we reach the length of our string. For example, if the string is 5 characters long and we've run the loop 4 times, i now equals 5 and is no longer less than the string's length, so the loop ends.
  • The last part is i++. This tells Java what we want to do with i after each loop. In this case, we want to increment the value by 1 each time the loop repeats.
  • Everything inside the brackets is, obviously, the code we want to execute on each loop.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @Zephyr, this is awesome. I'm still bad with for loops, so it can be... difficult. This solves my issue. Thanks!
I added a little bit of explanation to my answer for how the for loop is defined. Hope it helps make it a little easier to understand!
1

You're saying while i>finale.length() but i is initialized as 0. You never enter the while loop.

Comments

1

Some issues with your code (see inline comments):

import java.util.Scanner;

public class Executable {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String x;
        int i = 0;

        System.out.print("Input text here: ");
        x = input.nextLine();

        StringBuilder finale = new StringBuilder(x.toUpperCase());

        while(i > finale.length()) { // this condition is incorrect. Initially
                                     // this condition will always be false
                                     // if you input some sentence. It should be 
                                     // i < finale.length()
            if(finale.substring(i, i) == " ") { // here preferably you should use
                                                // equals method to compare strings
                i += 2;
                // you are only incrementing the i if the ith
                // substring equals " ". Firstly, substring(i,i)
                // will return empty string because the second argument
                // is exclusive
                finale.insert(i, '\t');
            }
        }

        System.out.println(finale);

    }
}

If you want to have an alternate method (not very optimal) for doing what you want to do, you can try the following approach:

import java.util.Scanner;

public class Executable {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String x;
        int i = 0;

        System.out.print("Input text here: ");
        x = input.nextLine();

        String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");



        System.out.println(finale);

    }
}

First, convert the string to uppercase --> then remove all spaces between the words --> then insert spaces between all letters. The code line which does this is,

String finale = x.toUpperCase().replaceAll(" ","").replaceAll("", " ");

Here is a sample run:

Input text here: This is a sentence
 T H I S I S A S E N T E N C E 

Comments

0
  1. The correct way with your method would be, just increment until you have twice the size of the initial String

    while (i < x.length() * 2) {
        finale.insert(i, '\t');
        i += 2;
    }
    
  2. An easier way would be with a classic for-loop:

    StringBuilder finale = new StringBuilder();
    for (char c : x.toUpperCase().toCharArray()) {
        finale.append(c).append('\t');
    }
    

Comments

0

Use a for loop since you know the number of iterations:

    Scanner input = new Scanner(System.in);

    String x;

    System.out.print("Input text here: ");
    x = input.nextLine();

    StringBuilder finale = new StringBuilder(x.toUpperCase());

    int len = finale.length();
    for (int i = 1; i < 2 * len; i+=2 ) {
        finale.insert(i, '\t');
    }

    System.out.println(finale);

Comments

0

You are comparing strings with ==. Never do that; use equals instead.

For future readers: this job can be done elegantly using Java 8 Streams:

String result = str.chars()
    .filter(i -> i != ' ')
    .mapToObj(t -> (char) t)
    .map(Character::toUpperCase)
    .map(Character::valueOf)
    .collect(Collectors.joining(" ");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.