StringBuilder.insert() not changing output - java

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?

You have a few issues with your code. Before I present an implementation that works, let's look at those other issues.
Your while loop checks if i > finale.length(). Since i = 0 the while loop never has a chance to begin.
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.
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.

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

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

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;
}
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');
}

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);

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(" ");

Related

whats the simplest way to write a palindrome string using a while loop in java

I've searched about everywhere but I just can't find anything very concrete. I've been working on this code for awhile now but it keeps stumping me.
public static void main(String[] args) {
System.out.println(palindrome("word"));
}
public static boolean palindrome(String myPString) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word:");
String word = in.nextLine();
String reverse = "";
int startIndex = 0;
int str = word.length() -1;
while(str >= 0) {
reverse = reverse + word.charAt(i);
}
}
There's a lot of ways to accomplish this using a while loop.
Thinking about simplicity, you can imagine how could you do this if you had a set of plastic separated character in a table in front of you.
Probably you'll think about get the second character and move it to the begin, then get the third and move to begin, and so on until reach the last one, right?
0123 1023 2103 3210
WORD -> OWRD -> ROWD -> DROW
So, you'll just need two code:
init a variable i with 1 (the first moved character)
while the value of i is smaller than total string size do
replace the string with
char at i plus
substring from 0 to i plus
substring from i+1 to end
increment i
print the string
The process should be:
o + w + rd
r + ow + d
d + row +
drow
Hope it helps
Here is an piece of code I write a while back that uses almost the same process. Hope it helps!
String original;
String reverse = "";
System.out.print("Enter a string: ");
original = input.nextLine();
for(int x = original.length(); x > 0; x--)
{
reverse += original.charAt(x - 1);
}
System.out.println("The reversed string is " +reverse);

Is this a type casting error or are arguments not being passed to the method properly?

We are asked to do the following:
Receive the first names of your family members (between 3 to 6 members of your family), create an array of String.
Write a static method called generateNewName() as following:
It receives the array of String as a parameter.
It creates a new first name by using the 2nd character of each String from the array
Example: If you enter as first names Rocky, Ashley, Ocarina, Baron, Ernest, the resulting name should be oscar.
Display the names that were entered and newly generated name
This is what I have:
import java.util.Arrays;
import java.util.Scanner;
public class Foothill {
static Scanner input;
public static void main(String[] args) {
input = new Scanner (System.in);
String[] getNames = new String[5];
char Output;
Output = generateNewName(getNames);
System.out.println(Output);
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
}
public static char generateNewName(String[] getNames)
{
String newS = Arrays.toString(getNames);
char result = '\0';
for(int j = 0; j < getNames.length; j++){
result = (char) (result + newS.charAt(1));
}
return result;
}
}
It is properly taking the input, however it seems to not be executing the generatNewName method. Am I doing something wrong with the types of methods i'm using? Should generateNewName return a string-type? If so, how do I get the second letter of all input strings and concatenate them? Thanks,
Your generateNewName() method should be returning a String, not a char.
Then you would have to change that
char result = '\0';
with
String result = "";
and then you start appending (using +) the letters to the String.
You can also read about StringBuilder, which would make the code more efficient.
Also, String newS = Arrays.toString(getNames); that line doesn't make much sense. You want to be looping through the names you have, not through all the letters of your name.
I would rewrite that loop to something like:
for (int i = 0 ; i < names.length ; i++) {
result += names[i].charAt(1);
}
or, using a for-each loop
for (String name : names) {
result += name.charAt(1);
}
"Enter 5 names:" is misleading. Consider "Enter name " + (x + 1) + " (of " + 5 + "):" or something similar.
But to answer your question: You are running generateNewName before you get any names! It's being executed for an array of only null elements!
Change this:
Output = generateNewName(getNames);
System.out.println(Output);
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
to this
for(int x = 0; x < 5; x++){
System.out.println("Enter 5 names: ");
getNames[x] = input.nextLine();
}
Output = generateNewName(getNames);
System.out.println(Output);
:)
Also consider renaming your variables to (a) follow naming conventions such as variable names should be lowercase, and (b) to be more indicative of what they hold and what they are (string, char, array, etc.). Such as names or nameArray instead of getNames and newName or outputName instead of Output.
Finally, and as stated by others, you're using and returning a char in the generateNewName, and obviously a name is a string, not a char.
generateNewName should return a String, not a char. A char is a single character, like the letter A.
You can't generate the new name before asking for the old names, right? Within a method, unless you say otherwise (e.g. with a loop), code runs from top to bottom, like a list of instructions.

out of bounds error with word count

I'm trying to write my own Java word count program. I know there may already be a method for this, but I'd like to get it work. I'm getting an out of bounds error at line 14. I'm trying to use an input word to count how many times it appears in an input string. So I'm looping up to stringlength - wordlength, but that's where the problem is.
Here is the code:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print( "Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
First of all, two Scanners are not necessary, you can do many inputs with the same Scanner object.
Also, this if condition
if (match(substring, word) == true)
can be rewritten like
if (math(substring, word))
I would also recommend you to use i++ to increase the loop variable. Is not strictly necessary but is "almost" a convention. You can read more about that here.
Now, about theIndexOutOfBoundsException, I've tested the code and I don't find any input samples to get it.
Besides, there is an issue, you are missing one iteration in the for:
for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1'
String substring = string.substring(i, i + word.length());
// System.out.println(substring);
if (match(substring, word)) {
count++;
}
}
You can test it by putting a print statement inside the loop, to print each substring.
I'm not getting an out of bounds error, can you tell me what values you were using for word and string?
I have identified a bug with your program. If word is equal to string, it still returns count 0. I suggest adding one more iteration and using regionMatches instead. RegionMatches makes your match method obsolete and will return false if word.length() + i is equal or greater than string.length(), avoiding out of bounds issues.
As you can see I also moved the calculations to a seperate method, this will make your code more readable and testable.
And as Christian pointed out; you indeed do only need one Scanner object. I've adapted the code below to reflect it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter word : ");
String word = sc.nextLine();
System.out.print("Enter string: ");
String string = sc.nextLine();
int count = calculateWordCount(word, string);
System.out.println("There are " + count + " repetitions of the word " + word);
}
private static int calculateWordCount(String word, String string) {
int count = 0;
for (int i = 0; i < string.length() - word.length() + 1; i++) {
if (word.regionMatches(0, string, i, word.length())) {
count++;
}
}
return count;
}

Convert numbers into word-numbers (using loop and arrays)

How do I write a simple program that converts numbers into word-numbers, using loops and arrays?
like this: input: 1532
output: One Five Three Two
Here's what I tried:
class tallTilOrd
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
String [] tall = {"null", "en" , "to", "tre", "fire" ,
"fem", "seks", "syv", "åtte", "ni", "ti");
System.out.println("Tast inn et ønsket tall");
int nummer = input.nextInt();
for (int i = 0; i<tall.length; i++)
{
if(nummer == i)
{
System.out.println(tall[i]);
}
}
}
}
Scanner input = new Scanner (System.in);
String in = Integer.toString(input.nextInt());
String [] tall = {"null", "en" , "to", "tre", "fire" , "fem", "seks", "syv", "åtte", "ni", "ti"};
for(char c : in.toCharArray()){
int i = (int) (c-'0');
for (int j = 0; j<tall.length; j++) {
if(i == j){
System.out.print (tall[j] + " ");
}
}
}
I give you a hint:
You could convert your Integer input into a String and then process each Character of that string. Check out the javadoc for String to figure out how to do it ;-)
Now I'm not sure this is the perfect way to do it, but it would be a possible one.
Instead of iterating over the length of your tall array, you need to iterate over the digits of nummer (to do this, check out the methods String.valueOf(int), String.charAt(int) and String.length()). Then use those digits as indices for tall to get their string representation.
A few notes:
In the code you provided, you need to use == instead of =. == is for comparison, = is for assignment.
Instead of looping through the predefined array, loop through the input. Instead of treating the number entered as an int, treat it as a string and then convert each character in the string into a number, which you can use as an index to fetch the corresponding string from your array.
Also, note that println prints a newline each time.

Can not figure out Javas strings?

I am a student at the moment so I am still learning. I picked up VB pretty quick and it was simple Java on the other hand I am pretty confused on.
The Assignment I have been given this time has me confused "Write a method to determine the number of positions that two strings differ by. For Example,"Peace" and "Piece" differ in two positions. The method is declared int compare(String word1, String word2); if the strings are identical, the method returns 0. It returns -1 if the two strings have different lengths."
Additional "Write a main method to test the method. The main method should tell how many, positions the strings differ, or that they are identical, or if they are different lengths, state the lengths. Get the strings from the console.
So far this is where I am at and I am looking for someone to help break this down in I DUMDUM terms if they can I don't need a solution only help understanding it.
package arraysandstrings;
import java.util.Scanner;
public class differStrings {
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.print("Enter a word");
String word1;
String word2;
word1 = scanner.next();
System.out.print("Enter another word");
word2 = scanner.next();
int count = 0;
int length = word1.length();
for(int x = 0; x >= length; x = x+1) {
if (word1.charAt(x) == word2.charAt(x)) {
count = count + 1;
System.out.print (count);
}
}
}
}
Additional Question
package arraysandstrings;
import java.util.Scanner;
public class differStrings {
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.println("Enter a word");
String word1 = scanner.next();
System.out.println("Enter another word");
String word2 = scanner.next();
int count = 0;
int word1Length = word1.length();
int word2Length = word2.length();
if (word1Length != word2Length) {
System.out.println ("Words are a diffrent length");
System.out.println (word1 + "Has" + word1.length() + " chars");
System.out.println (word2 + "Has" + word2.length() + " chars");
}
for(int x = 0; x < word1Length; x = x+1) {
if (word1.charAt(x) != word2.charAt(x)) {
count = count + 1;
}}}
System.out.println (count+" different chars");
}
After implementing the knowledge Iv gained from your responses I have ran in to a problem with the last line:
System.out.println (count+" different chars");
It says Error expected however it worked before I added the next part of my assignment which was this:
if (word1Length != word2Length) {
System.out.println ("Words are a diffrent length");
System.out.println (word1 + "Has" + word1.length() + " chars");
System.out.println (word2 + "Has" + word2.length() + " chars");
}
for(int x = 0; x >= length; x = x+1) {
You probably mean
for(int x = 0; x < length; x = x+1) {
Shifting around some code, adding some line breaks and making 2 small tweaks to the logic produces a program that is closer to what you are trying to build.
package arraysandstrings;
import java.util.Scanner;
public class differStrings {
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.println("Enter a word");
String word1 = scanner.next();
System.out.println("Enter another word");
String word2 = scanner.next();
int count = 0;
int length = word1.length();
for(int x = 0; x < length; x = x+1) {
if (word1.charAt(x) != word2.charAt(x)) {
count = count + 1;
}
}
System.out.println (count+" different chars");
}
}
It looks like in addition to the for loop that #LouisWasserman pointed out you had code that was trying to find characters that are the same.
What you need is a loop which compares the two strings and counts the places where they are not equal.
Your logic counts the number of places where the two characters are the same. You are also printing the count each time the two characters are equal.
What it sounds like you need is a loop that iterates over the characters in the two strings comparing each character and incrementing the count of mis-matched or different characters. Then after getting a count of different characters by comparing all of the characters, you would print out the count of different characters.
So the basics would be: (1) read each of the strings, (2) check that the lengths are the same, (3) if same length then loop over the string comparing each character and incrementing the count of mis-matched characters each time there is a difference, (4) print out the count. If the string lengths are different then just set the count to negative one (-1) and do not bother to compare the two strings.
What would be kind of neat to do is to create a string of underscores and asterisk, in which each matching character position is represented by an underscore and each mis-matching character position is represented by an asterisk or perhaps the string would contain all of the matching characters and the mis-matching characters would be replaced by an asterisk.
Edit: adding example program
The example below is an annotated rewrite of your program. One change that I made was to use a function to perform the counting of the non-matching characters. The function, countNonMatchChars () is a static function in order to work around the object oriented nature of Java. This function is a utility type function and not really part of a class. It should be available to anyone who wants to use it.
Also rather than incrementing variables with the syntax of var = var + 1; I instead use the postincrement operator of ++ as in var++;.
package arraysandstrings;
import java.util.Scanner;
public class so_strings_main {
// function to compare two strings and count the number
// of characters that do not match.
//
// this function returns an integer indicating the number
// of characters that did not match or a negative one if the
// strings are not equal in length.
//
// "john" "john" returns 0
// "john1" "john2" returns 1
// "mary1" "john1" returns 4
// "john" "john1" returns -1 (lengths are not equal)
public static int countNonMatchChars (String s1, String s2)
{
// initialize the count to negative one indicating strings unequal in length
// get the lengths of the two strings to see if any comparison is needed
int count = -1;
int word1Length = s1.length();
int word2Length = s2.length();
if (word1Length == word2Length) {
// the lengths of the two strings are equal so we now do our comparison
// we start count off at zero. as we find unmatched characters, we
// will increment our count. if no unmatched characters found then
// we will return a count of zero.
count = 0;
for(int iLoop = 0; iLoop < word1Length; iLoop++) {
if (s1.charAt(iLoop) != s2.charAt(iLoop)) {
// the characters at this position in the string do not match
// increment our count of non-matching characters
count++;
}
}
}
// return the count of non-matching characters we have found.
return count;
}
public static void main (String agrs[]){
Scanner scanner = new Scanner (System.in);
System.out.println("Count non-matching characters in two strings.");
System.out.println("Enter first word");
String word1 = scanner.next();
System.out.println("Enter second word");
String word2 = scanner.next();
int count = countNonMatchChars (word1, word2);
if (count < 0) {
System.out.println ("Words are a diffrent length");
System.out.println (" " + word1 + " Has " + word1.length() + " chars");
System.out.println (" " + word2 + " Has " + word2.length() + " chars");
} else {
System.out.println (count + " different chars");
}
}
}

Categories

Resources