I am new to android and trying to write this pyramid in java but it is not printing exactly.
my code to write this is
String searchQuery = "rooms in mumbai";
int n = searchQuery.length();
for (int i = 0; i<=n; i )
{
for (int j = 0; j<=i-1; j )
{
System.out.print(searchQuery.charAt(j));
}
System.out.println();
}
but this printing this
r
ro
roo
room
rooms
rooms
rooms i
rooms in
rooms in
rooms in m
rooms in mu
rooms in mum
rooms in mumb
rooms in mumba
rooms in mumbai
As we can see it is priting some lines two times and I want the print to start from "roo" but it is printing from "r". Guide me how can i do that
CodePudding user response:
BE SIMPLE!!!
String str = "rooms in mumbai";
for (int i = 3; i <= str.length(); i )
if (str.charAt(i) != ' ')
System.out.println(str.substring(0, i));
Output:
roo
room
rooms
rooms i
rooms in
rooms in m
rooms in mu
rooms in mum
rooms in mumb
rooms in mumba
rooms in mumbai
CodePudding user response:
To start printing from roo
instead of r
, change the outer loop
for (int i = 0; i<=n; i )
into
for (int i = 3; i<=n; i )
If you want to avoid/skip
, just add this line after System.out.println()
if (j 1 < n && searchQuery.charAt(j 1).equals(" ")){
i ;
}
This will effectively skip printing new lines that simply have an extra space compared to the previous line
CodePudding user response:
To make it start from roo
just simply make int i = 3