duplicate characters in a loop - java

I need to write a small program that takes in a string like Hello World and prints out HHHEEELLLOOO WWWOOORRRLLLDDD, but instead of just hello world it would take in any string using the scanner function and produce the same result. I am new to java and cannot figure out how to create this program at all.

They key to learning how to program is to break up the problem into smaller pieces.
Write a program, using Scanner, to echo back the input and exit.
Modify that program so that you loop over the input and print each character.
Modify that program to print each character twice.
Modify that program to print each character n number of times.

I would do it like this at the first thought, but there may be an easier solution saving all the concatenations.
String produceString(String source, int numberPerLetter) {
String result = "";
for (int i = 0; i < source.length(); i++) {
char c = source.charAt(i);
for (int j = 0; j < numberPerLetter; j++) {
result += c;
}
}
return result;
}

Get the string from whichever source you want, e.g. scanner. Then iterate over each character in the string and print it as many times as you want.
int charRepeats = 3;
String input = "Whatever"; // Get from whichever source you want.
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
for (int j = 0; j < charRepeats; j++) {
System.out.print(c);
}
}

int No_of_Repeats = 2;
Scanner sc = new Scanner(System.in);
String user_input=sc.next();
for (int i = 0; i < user_input.length(); i++) {
char c = input.charAt(i);
for (int j = 0; j < No_of_Repeats; j++) {
result+=c;
}
}
return result;

Related

I have to capitalize the first letter of a String in Java.(I cant use the method in string class to do so). but i keep getting out of bounds error

here is the code. I keep getting the error: String index out of range:5, I don't know what I'm doing wrong so any help will be appreciated. Also, I'm not allowed to use any Scanner class methods other than length.
import java.util.*;
public class capitalLetter
{
public static void main(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a non capitalized word");
String word = sc.next();
int length = word.length();
char ch[] = new char[length];
for(int i = 0;i<length-1;i++){
ch[length] = word.charAt(length);
}
ch[0]+=32;
for(int i = 0;i<length-1;i++){
System.out.print(ch[length]);
}
}
}
Firstly, within the for loop you need to use the loop variable i, rather than length. Also, i should go to the last element of the array.
This
for(int i = 0; i < length-1; i++){
ch[length] = word.charAt(length);
}
should be
for(int i = 0; i < length; i++){
ch[i] = word.charAt(i);
}
Secondly, you're adding 32 when you should be subtracting.
Putting this together you get:
String word = "hello";
int length = word.length();
char ch[] = new char[length];
for(int i = 0; i < length; i++) {
ch[i] = word.charAt(i);
}
ch[0] -= 32;
for(int i = 0; i < length; i++) {
System.out.print(ch[i]);
}
Output:
Hello
In both of your loops, you are indexing by length instead of by i.
e.g this line
ch[length] = word.charAt(length);
should be like this
ch[i] = word.charAt(i);

Trying to get a loop to work through alternate arrays

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

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.

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

Is it possible to increment a string or character in Java?

My output should look like:
1 star(*)
3 stars(***)
4 stars(****)
For example i have code:
char array[] = new char[3];
char x = '*';
For (int i= 0; i < array.length; i++)
{
array[i]='*'
x = x+2;
system.out.println(array[i]);
}
No it's not possible in char[] array, you should do it like,
String array[] = new String[3];
String x = "*";
for (int i= 0; i < array.length; i++)
{
array[i] = "";
array[i] = array[i] + x;
system.out.println(array[i]);
x = x + "*";
}
This will print the output as,
*
**
***
Your array is a char array, so each element contains a single char. Therefore your output will be :
*
*
*
To get the output you want, you'll need a String array (or no array at all - you can used a nested loop instead).
In addition, x = x+2; doesn't do what you think it does. It assigns a new character to x. If the initial value of x is '*', it will change it to the char whose numeric value is higher by two compared to the numeric value of '*'.
Just to provide an alternative to the already existing answers, it is also possible to just work with char. The trick then is to use System.out.print() rather than System.out.println(). An example:
int n = 3; //the number of lines you want to print
char x = '*';
for(int i = 0; i < n; i++) {
for(int j = 0; j <= i; j++) {
System.out.print(x);
}
System.out.print("\n");
}
Note: this is just an alternative to the already proposed solutions
For that you need to change array to String type and concat * on it in each level.
Code
String array[] = new String[3];
char x = '*';
array[0]=""+x;
for (int i= 0; i < array.length; i++)
{
System.out.println(array[i]);
if(i!=array.length-1)
array[i+1]='*'+array[i];
}
And you also have so much compilation error in your code like For,Array,system.
Also check DEMO
Considering your out put it can be derived from following
String s="*";
StringBuffer sb =new StringBuffer();
for(int i=1;i<=4;i++)
{
System.out.println(sb.append(s));
}
Output will be
*
**
Tc

Categories