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()
Related
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);
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.
So, I'm writing a program that returns pyramids when you give a word as an input
for instance:
"Enter a word: "
Hello
Justification (L=left, R=Right)?
L
would print
H
ee
lll
llll
oooo
import java.util.Scanner;
public class Justification{
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
System.out.println("Enter a word: ");
String word=in.nextLine();
System.out.println("Justification (L=left, R=Right)?");
String Justification=in.nextLine();
if(Justification.equalsIgnoreCase("l")){
for (int i = 0; i < word.length(); i++) {
for (int j = 1; j <= i; j++) {
System.out.print(word.substring(i,i));
}
System.out.println();
}
}else if(Justification.equalsIgnoreCase("r")){
for (int i = word.length()-1; i >= 0; i--) {
for (int s = 0; s < i; s++) {
System.out.print(" ");
}
for (int j = word.length()-1; j >= i; j--) {
System.out.println(word.substring(i,i));
}
System.out.println("");
}
}else System.out.println("Bad input");
}}
You are using substring(begin,end) incorrectly. The character at the begin index is included while the character at the end index is not.
If the word is hello, and you call substring(2,4), it would be ll
String str = "hello".substring(2,4); //str is "ll"
One way to check if substring is used correctly is that endIndex-beginIndex=length of substring. In this case, 4-2=2, so the substring should contain 2 characters, which it does.
An easier way to print out the ith character is to use charAt(i) instead of substring(i,i+1);
System.out.println("hello".substring(0,1)); //prints h
System.out.println("hello".charAt(0)); //also prints h
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.
I'm trying to count consecutive letters in java using JOptionPane and when I try to compile and run my code I get this:
exception in thread main java.lang.StringIndexOutOfBoundsException: String index out of range: 5
I feel like I have most of it down so I'm not exactly sure what's wrong here. Any help would be appreciated.
My code:
import javax.swing.JOptionPane;
public class Project {
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Enter a string...");
while (true) {
if (input.equals("Stop")) System.exit(0);
else {
int count = 0;
int len = input.length();
for (int i = 0; i < len; i++) {
if (input.charAt(i) == input.charAt(i + 1)) count++;
}
JOptionPane.showMessageDialog(null, "There are " +
count + "pairs of consecutive letters.");
input = JOptionPane.showInputDialog(null,
"Enter a string...");
}
}
}
}
Problem is:
input.charAt(i + 1)
This will throw an error because when you are at the last element of the array it will try and get the next element but there isn't one. Consider revising your logic slightly.
In your for loop you could do:
for (int i = 0; i < len - 1; i++) {
The JOptionPane has absolutely nothin to do with that, you should fix your title. The problem is here :
for (int i = 0; i < len; i++) {
if (input.charAt(i) == input.charAt(i + 1)) count++;
}
replace that piece of code with
for (int i = 0; i < len - 1 ; i++) {
if (input.charAt(i) == input.charAt(i + 1)) count++;
}
This is a basic error, it is important for an efficient programer to be able to deal with this alone and quickly.