Trying to get a loop to work through alternate arrays - java

I'm trying to print out a string by alternating its letter cases. I want YourString to come out as YoUrStRiNg. I've tried three things but I can't get the loop to work the way I need it to. Here's what I have so far:
//one attempt
String s = "yourString";
String x = "";
for (int i = 0; i < s.length(); i += 2) {
for (int j = 1; j < s.length(); j += 2) {
x += Character.toUpperCase(s.charAt(i));
x += Character.toLowerCase(s.charAt(j));
}
}
System.out.println(x);
//the desired result but not the ideal solution
String[] sArray = {"Your", "String"};
String f = "";
for (String n : sArray) {
f += n;
}
char[] c = f.toUpperCase().toCharArray();
char[] d = f.toLowerCase().toCharArray();
System.out.print(c[0]);
System.out.print(d[1]);
System.out.print(c[2]);
System.out.print(d[3]);
System.out.print(c[4]);
System.out.print(d[5]);
System.out.print(c[6]);
System.out.print(d[7]);
System.out.print(c[8]);
System.out.print(d[9]);
System.out.println();
//third attempt with loop but the first loop keeps starting from zero
String t = "";
for (int i = 0; i < c.length; i += 2) {
for (int j = 1; j < d.length; j += 2) {
t += Character.toUpperCase(c[i]);
t += Character.toLowerCase(d[j]);
}
System.out.print(t);
}
What am I doing wrong?

Actually, there's no need to iterate more than once through the elements of the String. As you need to change the case of the character alternatively, you can just count the position of your iteration, by using the operator %. So, for example, given c as the current String character, the operation would be like this:
System.out.print(i % 2 == 0, (char)Character.toUpperCase(c) : (char)Character.toLowerCase(c));
However, you can actually take advantages from Java Stream and lambda expression, so to realize a very elegant solution for that.
I am going to show you my proposal solution. The only issue is that you cannot actually have a proper cycle variable, as the variable you access inside the lamba expression must be final or effective final, so I used a sort of trick for it.
That is just to give you an idea, you can actually personalize, make it reusable, and improve it as you wish:
public class MyStringTest {
public static void main(String args[]) {
String s = "yourString";
initializeCycleVariable();
s.chars().forEach(c ->
{System.out.print( MyStringTest.getAndIncrement() %2 == 0 ?
(char)Character.toUpperCase(c) :
(char)Character.toLowerCase(c));
});
}
private static int i = 0;
public initializeCycleVariable() { i = 0; }
public static int getAndIncrement() { return i++; }
}
And here is the output:
YoUrStRiNg

You should iterate over the string char by char. You could do upper case for the even indexes, and lower case for the odd ones. Sorry for not providing more detail, but it is clear that this is an assignment.

Try this one out,
String s = "yourString", x = "";
for(int i = 0; i < str.length(); i++){
if(i % 2 == 0)
x += Character.toUpperCase(s.charAt(i));
else
x += Character.toLowerCase(s.charAt(i));
}
System.out.println(x);

Related

How to print letters(DNA) in a format of (0,10,6)

I am struggling with this code here. I want print out dna in java that shows format of (0, 10, 6) which need to pass a until test
instead of looking like this
ACAAGATGCC ATTGTCCCCC GGCCTCCTGC TGCTGCTGCT CTCCGGGGCC ACGGCCACCG
CTGCCCTGCC CCTGGAGGGT GGCCCCACCG GCCGAGACAG CGAGCATATG CAGGAAGCGG
CAGGAATAAG GAAAAGCAGC CTCCTGACTT TCCTCGCTTG GTGGTTTGAG TGGACCTCCC
AGGCCAGTGC CGGGCCCCTC ATAGGAGAGG AAGCTCGGGA GGTGGCCAGG CGGCAGGAAG
GCGCACCCCC CCAGCAATCC GCGCGCCGGG ACAGAATGCC CTGCAGGAAC TTCTTCTGGA
AGACCTTCTC CTCCTGCAAA TAAAACCTCA CCCATGAATG CTCACGCAAG TTTAATTACA
It looks like this
ATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGCCTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGG....
here is my code
public String formatInGroups(int index, int basesPerGroup, int groupsPerLine) {
StringBuilder formattedSequence = new StringBuilder();
String sequence = sequences.get(index);
int num = 0;
while(num < sequence.length()) {
for(int i = 0; i < groupsPerLine; i++) {
for( int j = 0; j < basesPerGroup; j++) {
if(num < sequence.length()) {
formattedSequence.append(sequence.charAt(num));
num++;
}
}
}
}
return sequence;
}
}
You should append a white space to the sequence after a dna sequence is appended (at the end of the inner for loop). Also, when a line is full, you should append a new line (\n) character to the sequence(at the end of the outer for loop).
public String formatInGroups(int index, int basesPerGroup, int groupsPerLine) {
StringBuilder formattedSequence = new StringBuilder();
String sequence = sequences.get(index);
int num = 0;
while(num < sequence.length()) {
for(int i = 0; i < groupsPerLine; i++) {
for( int j = 0; j < basesPerGroup; j++) {
if(num < sequence.length()) {
formattedSequence.append(sequence.charAt(num));
formattedSequence.append(" ");
num++;
}
}
formattedSequence.append("\n");
}
}
return formattedSequence.toString();
}
Looking at your code, I think you just missed some little things here and there, add a new line break after a certain character count and a space after some groups, and also you were returning the wrong variable.
Here check this code I edited based on yours, I just added some simple stuff and you got the remaining right.
public String formatInGroups(int index, int basesPerGroup,
int groupsPerLine) {
// I suppose you have a 'sequences' list somewhere
sequences.add(dna());
StringBuilder formattedSequence = new StringBuilder();
String sequence = sequences.get(index);
int num = 0;
while(num < sequence.length()) {
for( int j = 0; j < basesPerGroup; j++) {
if(num < sequence.length()) {
if (num % (basesPerGroup * groupsPerLine) == 0){
formattedSequence.append("\n");
}
formattedSequence.append(sequence.charAt(num));
num++;
}
}
formattedSequence.append(" ");
}
return formattedSequence.toString().trim();
}
Little things to consider on your next problem:
1 - You were returning your original sequence instead of the formattedSequence.toString();
2 - Try to avoid using global variables, you can declare them inside your for loop;
3 - Try using better variable names, instead of num you could name your variable after something that it is doing, like charPositionCounter, it will improve your code readability.

How can I print a word two letters at a time? - java

The input is supposed to have an even length. The problem is that on the first iteration of the loop, it print Sc, but then it prints ch instead of ho. I'm not sure how to make that jump.
public static void twoAtATime(String a) { // School
int len = a.length();
if(len%2 == 0) {
for(int i = 0; i <a.length()/2; i++) {
System.out.print(a.substring(i,i+1) + a.substring(i+1,i+2));
System.out.println();
}
}
The output is supposed to be like this:
Sc
ho
ol
To fix it:
Increase i by 2.
Iterate until i < len.
You can improve it:
By calling substring once for two chars.
Using println with param.
Incrementing i once - i += 2.
After improvements:
public static void twoAtATime(String s) {
int len = s.length();
if (len % 2 == 0) {
for (int i = 0; i < len; ) {
System.out.println(s.substring(i, i += 2));
}
}
}

String-Word counter

I have to print the count of the words in a string which are repeated exactly N times?
example:
one two three four three two five
1
output:3
since one,four and five appears only once.
My code shows me the output as 1.
what is wrong with my code and logic?thank you.
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
String s=scan.nextLine(),b;
int n=scan.nextInt();
int c=0,f=0,i;
String[] a=s.split(" ");
for(i=0;i<a.length;i++)
{
b=a[i];
for(int j=i+1;j<a.length;j++)
{
if(b.equalsIgnoreCase(a[j]))
{
c++;
}
}
if(n==c)
{
f++;
}
else
{
c=0;
}
}
System.out.print(f);
}
}
I see three reasons that makes your result incorrect.
First one is c
If a word is here once only, then the if statement if(b.equalsIgnoreCase(a[j])) will never be true. Which means that c will be always equal to 0.
So you you need to use 1 as default value for c or you should check the value of c using the following statement if (n == c + 1)
The second point is that you should reset the value of c even if it is equal to n.
Then with this double for loop:
for (i = 0; i < a.length; i++) {
b = a[i];
for (int j = i + 1; j < a.length; j++) {
When you searching for a value that is there once only, the last occurence of every words will be counted as well.
There is lot of ways to solve that. one of them is to use a Set<String> and only count for the words that has not been used before.
So at the end you will have something similar to that:
int c=1,f=0,i;
String[] a=s.split(" ");
Set<String> words = new HashSet<>();
for (i = 0; i < a.length; i++) {
b = a[i];
if (words.add(b)) {
for (int j = i + 1; j < a.length; j++) {
if (b.equalsIgnoreCase(a[j])) {
c++;
}
}
if (n == c) {
f++;
}
c = 1;
}
}
I think It's because you don't initialize C when n==c . Therefor it increases to 1 after one and one are matched. And it's not working well . It should be 0 for every loop
Also why j starts from i+1? After each loop it will lose comparison one by one Since a[j] is getting smaller. It should always containt list of full input numbers

Stopping a for loop without using break

I'm trying to write a program that prints all substrings of entered string. For example if user enter "rum" the output will be this:
r
u
m
ru
um
rum
import java.util.Scanner;
public class AllSubStrings
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = in.next();
String sub = "";
for(int i=0; i<str.length(); i++)
{
for(int a=0; a<str.length() ; a++)
{
if(i+a+1>str.length())break;
sub = str.substring(a,i+a+1);
System.out.println(sub);
}
}
}
}
This program works perfectly but since we didn't learn how to use "break" in classes, i'm looking for something different. Any idea apart from "break" are welcome.
Thanks in advance.
You can use this while loop cycle instead of for:
int a = 0;
while (a < str.length && i + a < str.length()) {
sub = str.substring(a, i + a + 1);
System.out.println(sub);
a++;
}
Also it is possible to replace break with return statement
Calculate how many possible substrings there can be for a certain length. For example, length 1 = 1 substring, length 2 = 3, length 3 = 6, and so on.
Then loop for that many times. There should be a generic formula you can use for no matter how long of an input string.
You don't need a break to do this task.
int len = str.length();
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
System.out.println( str.substring( i, j + 1 ) );
}
}
You can have two conditions in the for loop
for(int a = 0; a < str.length() && i + a < str.length(); a++)
{
sub = str.substring(a,i+a+1);
System.out.println(sub);
}
Note that i + a + 1 <= str.length() is the same as i + a < str.length()

Repeat an integer n times

I'm trying to make a pyramid out of an integer.
I.E the number 3 :
3
33
333
So based on the answers i found i made this :
int n = 8;
String n2 = Integer.toString(n);
for (int i=0; i<n; i++) {
System.out.println(StringUtils.repeat(n2, i));
}
But it's not working and would be suboptimal. Is there a simple way to repeat an integer n times in the same line ?
EDIT : made myself a method.. not quite happy either but it seems i can't just use something like System.out.println(int x, int n times)
int n = 8;
for (int i=0; i<=n; i++) {
for (int j=0; j<i; j++) {
System.out.print(n + " ");
}
System.out.println("");
}
Ok, you can do this without explicit loops using Java-8 streams:
IntStream.range(1,n).forEach(i -> System.out.println(StringUtils.repeat(n2, i));
or even without apache-commons:
IntStream.range(0,n).forEach(i -> System.out.println(String.join("", Collections.nCopies(i+1, n2))));
But in any case internally all these methods use loops.
I mean isn't it suboptimal to convert my int into a string ? AIn't
there a direct way to deal with the integer ? –
If you dont want to convert int to string.
This may help you.
int n = 3;
for (int i=1; i<=n; i++) {
System.out.println(new String(new char[i]).replace("\0", n+""));
}
Something as below.
public class Test{
public static String repeat(String str, int times) {
return new String(new char[times]).replace("\0", str);
}
public static void main(String[] args) {
for (int i = 1; i < 5; i++) {
System.out.println(repeat("3", i));
}
}
}
Output
3
33
333
3333
You could try to use a StringBuilder.
You would still have to loop, but it might be slightly better performance-wise.
int n = 8;
String n2 = Integer.toString(n);
StringBuilder builder = new StringBuilder(n);
for(int i = 0; i < n; i++) {
builder.append(n2);
System.out.println(builder.toString());
}
This does what you want, but not in the way you think about it. Instead of repeatedly having to create the repeating integer string, we simply build ONE string, saving us the work of repeating it.
To actually answer your question, you could use this code, although I would recomend the first approach:
char[] str = new char[n];
Arrays.fill(str, (char)(number + '0'));
new String(str);
This would only work if your integer is 0 <= number < 10.
To keep with integers, you may store last value each time, and add the next part :
i = 0 --> you get 3
i = 1 --> you get 33 (i0 + 30)
i = 2 --> you get 333 (i1 + 300)
int lastValue = 0;
for (int i=0; i<=n; i++) {
int currentValue = lastValue + (n * Math.pow(10, i));
System.out.println(currentValue);
lastValue = currentValue ;
}
This obviously works for one-digit integers only.

Categories