Java Create Strings Dynamically With Loops - java

I need to create a program that creates strings dynamically with some sort of loop (for/while). It would start out as a single-character string with an ASCII value of 1, than 2, than 3, and so on, until is reached 128. Once it reached 128, it would be a two-character string, with the first character of an ASCII value of 1, and the second character being 1. It would then be 1;1, 1;2, 1;3, until the second digit reached 128, and then which the first character would have a value of 2. How is this logically possible?
Here's what I tried so far:
for (int i = 0; i < 128; i++) {
str = ((char) i) + "";
for (int j = 0; j < 128; j++) {
str += ((char) j) + "";
//workWithString(str);
System.out.println(str);
str = str.substring(0, str.length() - 1);
}
}
And this works, but only for 2 digits. I would like for it to work with up to 32 digits. Is there any easier way to accomplish this without having 32 for loops?
Thanks!

Sorry, guys. Figured it out on my own. For anyone who's interested in the answer, I achieved it like so:
public static void addCharacter(String str, int depth) {
for (int j = 33; j < 127; j++) {
for (int i = 0; i < depth; i++) {
str += ((char) j) + "";
System.out.println(str);
addCharacter(str, depth - 1);
str = str.substring(0, str.length() - 1);
}
}
}
Where depth is the amount of digits you want it to calculate, and str is the string you want to add a character to.

public class StringCreator {
public static void main(String[] args) {
for(int i=0;i<=128;i++){
for(j=0;j<10;j++){
System.out.println(i+"."+j);
}
}
}
}

Related

How to print int n values

I am new to Java and just start my journey but i have problem with this simple function.
I am should have result like that
*2345
**345
***45
****5
But my function return something else :D What should I have to change?
public class Main08 {
public static void main(String[] args) {
int n = 5;
for (int i = 0; i < n; i++) {
String row = "";
for (int j = 0; j < n; j++) {
if (j < n) {
System.out.println(row += "*");}
else {
System.out.print(n);}
}
}
}
}
You can try like this:
public class MyClass {
public static void main(String[] args) {
int n = 5;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n; j++) {
if (j <= i) {
System.out.print("*");
} else {
System.out.print(j + 1);
}
}
System.out.print(" ");
}
}
}
Your issue is, that you prolonged the string multiple times and every time print it out again. I changed it such, that I only print out the numbers and asterisks depending on how the i and j relate to each other.
Also i limit the outer loop to n-1, because otherwise you will print 6 blocks (because you are starting from zero) and have a block of only asterisks at the end.
Output: *2345 **345 ***45 ****5
What you are asking is a way to replace some characters in an existing string.
The easiest way is to use the StringBuilder class because you can manage the characters, while a String is an unmodifiable sequence of characters:
A mutable sequence of characters.
In particular you need to use the method replace that:
Replaces the characters in a substring of this sequence with characters in the specified String
So to pass from an original string 12345 to **345 for example you need to do the following:
// THe original string
String original = "12345";
// THe StringBuilder populated with the original string
StringBuilder stringBuilder = new StringBuilder(original);
// Replacing the first two characters (so 12) with the string **
// to obtain the stringbuilder holding **345
stringBuilder.replace(0, 2, "**");
// Get the string **345
String result = stringBuilder.toString();
You can put this logic in your loop and apply it multiple times.
Eventually you can reuse the same StringBuilder, so in this case you need to replace a single character for each step of your for loop.
public class Main08 {
public static void main(String[] args) {
int n = 4;
int countStar=0;
int startNum=1;
for (int i = 1; i <= n; i++) {
//for displaying the "*"
countStar++;
startNum++;
for (int j = 1; j <= countStar; j++)
System.out.print("*");
//for displaying the digit
for (int k = startNum; k <= 5; k++)
System.out.print(k);
}
}
}
You can take a outer loop and inside the outer loop take two inner loops . one for printing * and the other for printing the digit. This can help you in solving other design problems if you understand the logic.
You could try this :
public static void main(String[] args) {
int n = 5;
String row = "";
for (int i = 1; i <= n; i++) {
row += i;
}
for (int i = 1; i < n; i++) {
StringBuffer buf = new StringBuffer(row);
buf.replace(0, i, "*".repeat(i));
System.out.println(buf);
}
}
The first loop create the initial row you want, and the second loop will replace the characters by stars.
The repeat appends * with same long as iterator i dynamically

Java - removeDuplicates

Given a text string, only remove consecutive duplicate occurrences of the same character, but the later occurrences of the same character remain in the result as long as there was some other character between these occurrence.
Example: given argument aaaabxaaddee returns abxade.
Here's what I've tried so far:
char[] new_string = text.toCharArray();
String result = "";
for (int i = 1; i < text.length(); i++) {
if (text.charAt(0) != text.charAt(i)) {
text.charAt(0) = text.charAt(i);
result += text.charAt(i);
}
}
return res;
This is pretty simple iterate over given string only once:
public static String removeDuplicates(String str) {
StringBuilder buf = new StringBuilder(str.length());
char prv = '\0';
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != prv)
buf.append(ch);
prv = ch;
}
return buf.toString();
}
I suggest you start with a StringBuilder whenever you want to mutate a sequence of characters in Java. Here you can loop from the left to the right, and start a second inner loop removing duplicate characters from the StringBuilder. Something like,
public static String removeDuplicates(String text) {
StringBuilder sb = new StringBuilder(text);
for (int i = 0; i < sb.length() - 1;) {
char ch = sb.charAt(i);
int j = i + 1;
while (j < sb.length() && sb.charAt(j) == ch) {
sb.deleteCharAt(j);
}
i = j;
}
return sb.toString();
}
Which I tested like
public static void main(String[] args) {
System.out.println(removeDuplicates("aaaabxaaddee"));
}
And it outputs (as requested)
abxade
You are comparing with the first character only. Update your logic to compare the current char (at i) to the next (at i+1) and also start your loop from 0.
You are only comparing the 0-th index of the char array which won't lead to the desired result. Also, you can't modify the string by text.charAt(0) = text.charAt(i). It's invalid in Java.
Instead can use a while loop inside your for loop to check for consecutive occurrences. Keep checking if the current and next character in the string is equal. If they are equal then move ahead else break the while loop and continue with other iterations.
for (int i = 0; i < text.length(); i++)
{
result += text.charAt(i);
while (i < text.length()-1 && text.charAt(i)==text.charAt(i+1))
++i;
}
You are thinking in the right direction but instead of comparing each character with 0 index position character you can compare it with previous character since you have to ignore the consecutive ones .
char[] new_string = text.toCharArray();
String result = ""+text.charAt(0);
for (int i = 1; i < text.length(); i++) {
if (text.charAt(i-1) != text.charAt(i)) {
result += text.charAt(i);
}
}
return result;
}
}
Note:-
"text.charAt(0) = text.charAt(i)" This cannot be done in java as String is an immutable Class.
You are returning 'res' while you are storing the required string in 'result'.

How to print the first recurring character in a string?

I got a school assignment that I have to create a program that prints the first recurring character in a given string.
For example, if the input is "helloo", then it should output as "l". I wrote the following code but it prints "l" and "o" both.
String text = "helloo";
int length = text.length();
for (int i = 0; i <= length - 1; i++) {
char curChar = text.charAt(i);
for (int j = i + 1; j <= length - 1; j++) {
if (curChar == text.charAt(j)) {
System.out.println(curChar);
break;
}
}
}
Can someone help me out with this? Thanks for any answers!
You're breaking just the inner loop but not the outer loop. You can use break with a label for the outer loop. For example:
String text = "helloo";
int length = text.length();
outerloop:
for (int i = 0; i <= length - 1; i++) {
char curChar = text.charAt(i);
for (int j = i + 1; j <= length - 1; j++) {
if (curChar == text.charAt(j)) {
System.out.println(curChar);
break outerloop;
}
}
}
Get more information here - How to break out of nested loops in Java?
Hope this helps, but you should try doing your school assignments yourself.
I realize that you are asking for a direct fix to your current approach. But for those who might read this question in the future, there is a very sleek approach here using regular expressions:
String text = "helloo";
String match = text.replaceAll("^.*?(.)\\1.*", "$1");
System.out.println(match);
l
Demo
The basic idea of the pattern ^.*?(.)\1 is to consume the least number of characters in the string until we hit a single character which is followed by that same character.
Here's another variant:
String text = "helloo";
ArrayList<String> a = new ArrayList<String>(Arrays.asList(text.split(Pattern.quote(""))));
for(int i = 0; i < a.size()-1;i++) {
if(a.get(i).compareTo(a.get(i+1)) == 0) {
System.out.println(a.get(i));
break;
}
class FirstRepeatingChar
{
public static void main(String args[])
{
String s="hello";
for(int i=0;i<s.length();i++)
{
for(int j=0;j<s.length();j++)
{
if(s.charAt(i)==s.charAt(j))
{
System.out.println(" the First non repeating character is " +s.charAt(i));
break;
}
}
}
}
}

Finding the middle letter and make it uppercase.. am stuck and the end .. :(

Here am finding the middle letter of each element of the array and making it upper case and merge it so that it'll give me a result like e:g- {bOy, inDia, apPle}
Following is the code am trying till now.
public class FindMiddle {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("boy india apple");
String str[] = al.toArray(new String[al.size()]);
String newar[];
String delimiter = " ";
newar = str[0].split(delimiter);
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
System.out.println(c[j]);
}
newar[i] += c[j];
}
}
}
}
It's only giving me O D P.
I want them merged with the original elements like bOy inDia apPle.
that's because you print only the middle char (the println is inside the if statement)
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
System.out.println(c[j]);
}
I would suggest using StringBuilder.setCharAt
for (int i = 0; i < newar.length; i++) {
StringBuilder updateString = new StringBuilder(newar[i]);
int middleIndex = newar[i].length /2;
updateString.setCharAt(middleIndex, Character.toUpperCase(newar[i].charAt(middleIndex));
System.out.println(updateString);
}
you could use the charAt function of the String object and replace function
using the full String.length is not accurate when you will be accessing the middle index of the String since index are length - 1 (because it starts with 0) so you need to deduct 1 from the length and then divide it by half.
for(int i=0;i<newar.length;i++){
int index = (newar[i].length()-1)/2;
newar[i] = newar[i].replace(newar[i].charAt(index), Character.toUpperCase(newar[i].charAt(index)));
System.out.println(newar[i]);
}
output:
bOy
inDia
aPPle
Try this :
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
//System.out.print(c[j]); <--- you keep getting O D P because you
print them here
}
// newar[i] += c[j]; <-- here you just concat changed elements to newar
System.out.print(c[j]); <--- print the value of array none middle and middle one
}
if (i != newar.length-1) { <-- avoid printing , for last item
System.out.print(",");
}
}
output:
bOy,inDia,apPle
My explanations are as comment inside the code.
Note: when you are in a for loop, you are checking whether you ecnounter the middle character. if you encountered, you will make it uppercase other wise nothing is changed, and each character is printed out on the console.
import java.util.ArrayList;
public class Test
{
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("boy india apple");
String str[] = al.toArray(new String[al.size()]);
String newar[];
String delimiter = " ";
newar = str[0].split(delimiter);
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
// System.out.println(c[j]);
// (1)
}
System.out.print(c[j]);
// (2)
newar[i] += c[j];
}
System.out.println();
// (3)
}
}
}
(1) - I got rid of this because it would only print out the uppercase letter. You had set the middle characters in all 3 words to uppercase, but, you need to print out the whole word, not just one letter.
(2) - You do, however, want to print out the whole word, which is what this line is doing. Instead of doing println, it only does print. Reason is because we are taking advantage of that for loop that is going through each character in the specific word to be able to print out each letter after we are done checking if it's the middle letter.
(3) - We have this line here because we want to be able to separate between words. I am not sure how you want these words separated so change this as you feel it's necessary, I just separated them so you could see.
There are a lot of things wrong with your code, so here is a simplified rewrite:
public static void main(String[] args) {
String s = "boy india apple";
String[] split = s.split( " " );
String[] toReturn = new String[split.length];
for (int i = 0; i < split.length;i++)
{
String word = split[i];
char[] chars = word.toCharArray();
chars[chars.length/2] = Character.toUpperCase( chars[chars.length/2] );
toReturn[i] = String.valueOf( chars );
}
System.out.println(Arrays.toString( toReturn ));
}
In order to correct your code you can start by removing the useless ArrayList and moving the System.out outside of the for loop. There are some other issues like you are appending the new result to the original so newar after this runs will look like {boybOy, indiainDia, appleapPle}.
EDIT:
For teaching purposes, here is your code modified so that it will work; however inefficient.
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("boy india apple");
String str[] = al.toArray(new String[al.size()]);
String newar[];
String delimiter = " ";
newar = str[0].split(delimiter);
System.out.print("{");
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
}
System.out.print(c[j]);
}
newar[i] = String.valueOf(c);
if (i < newar.length - 1)
System.out.print(",");
}
System.out.println("}");
}
String temp = ""; //define temp string as "" (don't assign null)
for (int j = 0; j < c.length; j++) {
...
//newar[i] += c[j]; //don't append to existing String in array
temp += c[j];
newar[i] = temp;
}
//after replacement is done
//now can print replaced string in array by looping
for (String string : newar) {
System.out.println(string);
}

Columnar Transposition decryption algorithm in Java

Is anyone able to give the reverse/decryption algorithm for this Columnar cipher? The key length may vary, but here it is given as 4 for the encryption.
String input = "Hello World"
String output = "Hore llWdlo"
int key =4;
public static String encrypt(int key, String plainT) {
String outString= "";
for (int j = 0; j < key; j++) {
for (int i = j; i < plainT.length(); i += key) {
outString+= plainT.charAt(i);
}
}
return outString;
}
Java Strings are immutable, so you can't operate on their data. But if you could rewrite your encoding function to use an array of chars:
public static String encrypt(int key, String plainT)
{
char[] res = new char[plainT.length()];
int k = 0;
for (int j = 0; j < key; j++) {
for (int i = j; i < plainT.length(); i += key) {
res[k++] = plainT.charAt(i);
}
}
return String.copyValueOf(res);
}
Then you can easily revert the process:
public static String decrypt(int key, String encT)
{
char[] res = new char[encT.length()];
int k = 0;
for (int j = 0; j < key; j++) {
for (int i = j; i < encT.length(); i += key) {
res[i] = encT.charAt(k++);
}
}
return String.copyValueOf(res);
}
Concatenation is implemented here with an auxiliary char array and an additional index k. Reverting the process is then the same as reverting the indices. (This means that the decrypted array is not populated in order, just like the original string is not read from in order on encrypting.)
(Caveat: I'm not familiar with Java, so I hope that changing the char array and converting it to a string works as I expect and also that I haven't told any outright nonsense about Java Strings.)
Addendum You can also use your original concatenation code as base, but it will be a bit more complicated. Your column-wise encryption can be represented as:
H o r
e _ l
l W d
l o
The encrypted string is read horizontally, the decrypted original string vertically. If your string were "Hello World!", with an excamation mark, you'd have a string of length 12 and you could use your original code with a reverted key of 12 / 4 == 3.
But we actually have a variable key: 3 for the first lines and 2 for the last line.
public static String decrypt(int key, String str)
{
String out = "";
int skip = str.length() / key;
int rest = str.length() % key * (skip + 1);
for (int j = 0; j < skip; j++) {
int i = j;
while (i < str.length()) {
out += str.charAt(i);
i += skip;
if (i < rest) i++;
}
}
for (int i = skip; i < rest; i += skip + 1) {
out += str.charAt(i);
}
return out;
}
The inner loop now has a key of skip or skip + 1, depending on the region of the string. The last column (of the sketch above) is treated in a separate loop, because it looked tidier.

Categories

Resources