For loop with substrings - java

Beginning CS student here, trying to get a handle on loops. My task is to take a String s, such that if s = 'abcd', the program will print: 'a,b,c,d,ab,bc,cd,abc,bcd,abcd'. Clearly the begin index and end index change as the loop iterates—(0,1),(1,2),(2,3),(3,4). That's fine and I can print: 'a,b,c,d'. But how do I control it such that it will go from that to (0,2),(1,3),(2,4) and then (0,3),(1,4), and finally (0,4)? This is where I am stumped. Thanks for the assistance and here's my code:
void printSubstring()
{
int len = s.length();
for (int i=0;i<len;i++)
{
for (int k=0;k<len;k++)
System.out.print(s.substring(k,k+1)+", ");
}
System.out.println();
}

for (int i=0;i<len;i++)
{
for (int k=0;k<len-i;k++)
System.out.print(s.substring(k,k+i+1)+",");
}
This as your for structure should work.
At each step inner loop, the number of strings to print decreases (using -i). And the length of the strings increase (using +i in the substring)
Tested with: abcdefghijklmnopqrstuvwxyz
Output:
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,ab,bc,cd,de,ef,fg,gh,hi,ij,jk,kl,lm,mn,no,op,pq,qr,rs,st,tu,uv,vw,wx,xy,yz,abc,bcd,cde,def,efg,fgh,ghi,hij,ijk,jkl,klm,lmn,mno,nop,opq,pqr,qrs,rst,stu,tuv,uvw,vwx,wxy,xyz,abcd,bcde,cdef,defg,efgh,fghi,ghij,hijk,ijkl,jklm,klmn,lmno,mnop,nopq,opqr,pqrs,qrst,rstu,stuv,tuvw,uvwx,vwxy,wxyz,abcde,bcdef,cdefg,defgh,efghi,fghij,ghijk,hijkl,ijklm,jklmn,klmno,lmnop,mnopq,nopqr,opqrs,pqrst,qrstu,rstuv,stuvw,tuvwx,uvwxy,vwxyz,abcdef,bcdefg,cdefgh,defghi,efghij,fghijk,ghijkl,hijklm,ijklmn,jklmno,klmnop,lmnopq,mnopqr,nopqrs,opqrst,pqrstu,qrstuv,rstuvw,stuvwx,tuvwxy,uvwxyz,abcdefg,bcdefgh,cdefghi,defghij,efghijk,fghijkl,ghijklm,hijklmn,ijklmno,jklmnop,klmnopq,lmnopqr,mnopqrs,nopqrst,opqrstu,pqrstuv,qrstuvw,rstuvwx,stuvwxy,tuvwxyz,abcdefgh,bcdefghi,cdefghij,defghijk,efghijkl,fghijklm,ghijklmn,hijklmno,ijklmnop,jklmnopq,klmnopqr,lmnopqrs,mnopqrst,nopqrstu,opqrstuv,pqrstuvw,qrstuvwx,rstuvwxy,stuvwxyz,abcdefghi,bcdefghij,cdefghijk,defghijkl,efghijklm,fghijklmn,ghijklmno,hijklmnop,ijklmnopq,jklmnopqr,klmnopqrs,lmnopqrst,mnopqrstu,nopqrstuv,opqrstuvw,pqrstuvwx,qrstuvwxy,rstuvwxyz,abcdefghij,bcdefghijk,cdefghijkl,defghijklm,efghijklmn,fghijklmno,ghijklmnop,hijklmnopq,ijklmnopqr,jklmnopqrs,klmnopqrst,lmnopqrstu,mnopqrstuv,nopqrstuvw,opqrstuvwx,pqrstuvwxy,qrstuvwxyz,abcdefghijk,bcdefghijkl,cdefghijklm,defghijklmn,efghijklmno,fghijklmnop,ghijklmnopq,hijklmnopqr,ijklmnopqrs,jklmnopqrst,klmnopqrstu,lmnopqrstuv,mnopqrstuvw,nopqrstuvwx,opqrstuvwxy,pqrstuvwxyz,abcdefghijkl,bcdefghijklm,cdefghijklmn,defghijklmno,efghijklmnop,fghijklmnopq,ghijklmnopqr,hijklmnopqrs,ijklmnopqrst,jklmnopqrstu,klmnopqrstuv,lmnopqrstuvw,mnopqrstuvwx,nopqrstuvwxy,opqrstuvwxyz,abcdefghijklm,bcdefghijklmn,cdefghijklmno,defghijklmnop,efghijklmnopq,fghijklmnopqr,ghijklmnopqrs,hijklmnopqrst,ijklmnopqrstu,jklmnopqrstuv,klmnopqrstuvw,lmnopqrstuvwx,mnopqrstuvwxy,nopqrstuvwxyz,abcdefghijklmn,bcdefghijklmno,cdefghijklmnop,defghijklmnopq,efghijklmnopqr,fghijklmnopqrs,ghijklmnopqrst,hijklmnopqrstu,ijklmnopqrstuv,jklmnopqrstuvw,klmnopqrstuvwx,lmnopqrstuvwxy,mnopqrstuvwxyz,abcdefghijklmno,bcdefghijklmnop,cdefghijklmnopq,defghijklmnopqr,efghijklmnopqrs,fghijklmnopqrst,ghijklmnopqrstu,hijklmnopqrstuv,ijklmnopqrstuvw,jklmnopqrstuvwx,klmnopqrstuvwxy,lmnopqrstuvwxyz,abcdefghijklmnop,bcdefghijklmnopq,cdefghijklmnopqr,defghijklmnopqrs,efghijklmnopqrst,fghijklmnopqrstu,ghijklmnopqrstuv,hijklmnopqrstuvw,ijklmnopqrstuvwx,jklmnopqrstuvwxy,klmnopqrstuvwxyz,abcdefghijklmnopq,bcdefghijklmnopqr,cdefghijklmnopqrs,defghijklmnopqrst,efghijklmnopqrstu,fghijklmnopqrstuv,ghijklmnopqrstuvw,hijklmnopqrstuvwx,ijklmnopqrstuvwxy,jklmnopqrstuvwxyz,abcdefghijklmnopqr,bcdefghijklmnopqrs,cdefghijklmnopqrst,defghijklmnopqrstu,efghijklmnopqrstuv,fghijklmnopqrstuvw,ghijklmnopqrstuvwx,hijklmnopqrstuvwxy,ijklmnopqrstuvwxyz,abcdefghijklmnopqrs,bcdefghijklmnopqrst,cdefghijklmnopqrstu,defghijklmnopqrstuv,efghijklmnopqrstuvw,fghijklmnopqrstuvwx,ghijklmnopqrstuvwxy,hijklmnopqrstuvwxyz,abcdefghijklmnopqrst,bcdefghijklmnopqrstu,cdefghijklmnopqrstuv,defghijklmnopqrstuvw,efghijklmnopqrstuvwx,fghijklmnopqrstuvwxy,ghijklmnopqrstuvwxyz,abcdefghijklmnopqrstu,bcdefghijklmnopqrstuv,cdefghijklmnopqrstuvw,defghijklmnopqrstuvwx,efghijklmnopqrstuvwxy,fghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuv,bcdefghijklmnopqrstuvw,cdefghijklmnopqrstuvwx,defghijklmnopqrstuvwxy,efghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvw,bcdefghijklmnopqrstuvwx,cdefghijklmnopqrstuvwxy,defghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwx,bcdefghijklmnopqrstuvwxy,cdefghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwxy,bcdefghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwxyz,

Inner loop should be -
for (int k=0;k<len-i;k++)
System.out.print(s.substring(k,k+i+1)+", ");
Hope that helps

You could try something like this,
void printSubstring(String s){
if(s == null){
return;
}
for(int lenghtSubstring = 1; lenghtSubstring <= s.length(); lenghtSubstring++){
for(int index = 0; index <= s.length() - lenghtSubstring; index++){
System.out.print(s.substring(index, index + lenghtSubstring) + ",");
}
}
}

void printSubstring() {
int len = s.length();
for (int i=1;i<len+1;i++)
{
for (int k=0;k<len-i;k++)
System.out.print(s.substring(k,k+i)+", ");
}
System.out.println();
}

Related

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

How to check if certain numbers appear in an array?

I'm relatively new to java. I'm trying to find if numbers from 0 - 4 are stored
somewhere in an array of size 5. The array is populated by the user entering integers between 0-4. I have successfully managed to get it to confirm that the first number entered by the user is in the array however, the numbers after that not appearing.
So for example: If the user enters the numbers 2,2,2,1,3 I will get only 2 appears in the array as a result.
public static void checkEachNumber(int[] array)
{
int currentNum = 0;
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array.length; j++)
{
currentNum = i;
if(currentNum == array[j])
{
System.out.println(currentNum + " appears in the array");
break;
}
else
{
System.out.println(currentNum + " doesn't appear in the array");
break;
}
}
}
}
To resolve your problem you should simply remove the have used in the else part of the array.
Consider a case like this
ex. 2 1 4 3
when checking for i=1 it will first compare the value with 2 so it will come out of the loop.
public static void checkEachNumber(int[] array)
{
int currentNum = 0;
for(int i = 0; i < array.length; i++)
{
int flag=0;
for(int j = 0; j < array.length; j++)
{
currentNum = i;
if(currentNum == array[j])
{
System.out.println(currentNum + " appears in the array");
flag=1;
break;
}
}
if(flag==0)
{
System.out.println("currentNum+"Doesn't appear in array");
}
}
}
When you execute a break statement, the loop stops running completely. In general, the way to scan for a match is going to look like this:
found_match = no
for (... in ...) {
if (match) {
found_match = yes
break
}
}
if (found_match) {
do_found_match_stuff();
}

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 use a while loop instead of a for loop?

The problem is:
Given a string, return the number of times "e" is in the string minus the number of times "a" is in the String. Ignore the case of the letters.
I was wondering if you are able to use a while loop instead of a for loop to solve this problem. I was also wondering if using just if-else statements would work. If they are possible, could someone show me how to do it?
public int eLessA(String str){
int E = 0, A = 0;
for (int i = 0; i < str.length(); i++){
if (str.substring(i, i+1).equalsIgnoreCase("e")){
E++;
}
if (str.substring(i, i+1).equalsIgnoreCase("a")){
A++;
}
}
return E - A;
}
Of course.
Any time you have a forloop:
for(int i = 0; i < str.length(); i++) {
//do something
}
You can do
int i = 0;
stringLength = str.length();
while(i < stringLength) {
//do something
i++;
}
Yes you can use a while loop instead of a for loop. The only difference when using the while loop is that you increment in the body of the loop.
int i = 0;
while(i < str.length())
{
// Do what you want here
i++;
}

Why won't this print in Reverse?

I have a very simple problem but I can't seem to solve it. I'm getting an out of bounds error on this code
int c = 0;
System.out.println();
System.out.println("Printing array in Reverse order:");
for (int i = array.length ; i >= -1; i--)
{
System.out.println(array[i] +" ");
c++;
if(c == 10)
{
System.out.println();
c=0;
}
}
What's the deal?
for (int i = array.length ; i >= -1; i--) {
wrong, arrays starts at index zero, so a "length" array is from index 0 to index "length - 1"
so your code is wrong, you should use
for (int i = array.length - 1 ; i >= 0; i--) {
You get an IndexOutOfBounds because you're starting out of the array
int c = 0;
System.out.println();
System.out.println("Printing array in Reverse order:");
for (int i = array.length -1; //HERE
i >= 0;//HERE
i--) {
System.out.println(array[i] +" ");
c++;
if(c == 10) {
System.out.println();
c=0;
}
}
In Java, array index go from 0 to "length - 1". So if you start in array.length, you are trying to access out of the array's positions. Same occurs if you try to access to -1 index, because your least index is 0.
Here is a small piece of code which will work you to get the reverse :)
public class newarray {
public static void main(String args[]){
int arr[]={10,20,30};
int size=arr.length;
for(int i=size-1;i>=0;i--){
System.out.println(arr[i]);
}
}
}
OutPut :
30
20
10

Categories