Nested loop construction - java

This is part of my homework. All I need is a bit of advice. I need to write some nested loop constructs, to print the following:
"122333444455555"
"+**+++****+++++"
"--***++++-----******+++++++"
Here is my code to print the first set of symbols
public static void main (String[] args)
{
int i,j;
for(i=1;i<6;++i)
{
for(j=1;j<i+1;++j)
{
System.out.print(i);
}
}
}
This works perfectly fine. I'm just having trouble figuring out the second and third set of symbols. Apologies for my lack of experience, I'm fairly new to Java.

One solution is:
final String[] arr = {"*", "+"};
And in your inner loop:
System.out.print(arr[i % 2]);
The % (Modulo) operator is responsible of the switches between * and + symbols:
For even i it'll be *, otherwise it'll be +.
Output: "+**+++****+++++".
(Regarding the second output, I'll not show you the solution, but it's very similar to this one once you understand it).

public static void main(String[] args) throws IOException {
int i, j;
for (i = 1; i < 6; ++i) {
for (j = 1; j < i + 1; ++j) {
System.out.print(i);
}
}
System.out.println();
for (i = 1; i < 6; i++) {
if (i % 2 == 1) {
for (j = 1; j < i + 1; ++j){
System.out.print("+");
}
} else {
for (j = 1; j < i + 1; ++j){
System.out.print("*");
}
}
}
System.out.println();
for (i = 2; i < 8; i++) {
if (i % 3 == 1) {
for (j = 1; j <= i; ++j){
System.out.print("+");
}
} else if (i % 3 == 2) {
for (j = 1; j <= i; ++j){
System.out.print("-");
}
} else {
for (j = 1; j <= i; ++j){
System.out.print("*");
}
}
}
}
Cycle #1:
You have to print out numbers from one to five and each number N has to be printed out N times.
for (i = 1; i < 6; ++i) { // this would set `i` to numbers from 1-5
for (j = 1; j < i + 1; ++j) { // for each cycle (next number) it prints
//it out N times where N is the cycle number. 1 is the first cycle,
//2 is the second and so on.
Cycle #2:
Same problem but instead of printing out number of the cycle you have to print out + or * based on if the cycle number is odd or even.
To check if the number is even you can use:
int number = 1;
if(number % 2 == 0){ // is true if the number is even
This checks whats the remainder from the division of number by two.
Cycle #3:
Same as #2 but you start from the second cycle, not from the first and you check for the remainder after division by 3.

If I understand, the third set is composed by sequence of "-*+" so:
String sequence = "-*+";
String s = "+**+++****+++++";
int seqI = 0;
for(i=0; i != s.size(); ++i) {
for(j=0; j < i+2; ++j) {
System.out.print(sequence[seqI]);
}
if(seqI < sequence.size()) {
++seqI;
} else {
seqI = 0;
}
}

You can define a function like this:
public static char Output(int i, int mode)
{
if (mode == 1)
{
return (char) i;
}
else if (mode == 2)
{
if (i % 2 == 0)
{
return '+';
}
else
{
return '*';
}
}
else if (mode == 3)
{
if (i % 3 == 0)
{
return '-';
}
else if (i % 3 == 1)
{
return '*';
}
else
{
return '+';
}
}
}
And use it just like:
for (int mode = 1 ; mode < 4 ; mode++)
{
for (int i = 1 ; i < 6 ; i++)
{
for (int j = 0 ; j < i + (int)(mode / 3) ; j++)
{
System.out.println(Output(i, mode));
}
}
}
Note: Yes! Actually my code is hard to read, but if you try to read it, you will learn something more than other answers!

Related

Break statement not taking me outside of loop java

I am solving this problem on code forces.
https://codeforces.com/contest/1675/problem/B
The break statement I have doesn't break out of the while loop.
When I use this input:
It outputs -1 one twice in the same case, which shows that the break statement isn't taking me outside the loop?
Why is this happening?
public class vanita {
public static void main (String[]args) {
Scanner in = new Scanner(System.in);
int cases = in.nextInt();
for (int i = 0; i < cases; i++) {
boolean test = true;
int arrLength = in.nextInt();
int arr[] = new int[arrLength];
for (int j = 0; j < arrLength; j++) {
arr[j] = in.nextInt();
}
int operations = 0;
int after;
for (int j = arrLength-1; j >= 1 ; j--){
after = arr[j-1];
while (arr[j] <= after) {
arr[j-1] = (int)Math.floor(arr[j-1]/2);
after = arr[j-1];
operations++;
if (arr[j] == 0 && arr[j-1] == 0) {
//System.out.println("current: " + arr[j]);
//System.out.println("after: " + arr[j-1]);
//System.out.println("Case " + i);
System.out.println("-1");
test = false;
break;
}
}
}
for (int s = 0; s < arrLength; s++) {
//System.out.print(arr[s] + " ");
}
//System.out.println(" ");
if (test == true) {
System.out.println(operations);
}
}
}
}
i think it breaks out of the inner while loop, but not the outer for loop. So the inner while loop runs multiple times.
Problems
Normally a break; will always break out of the most recent loop. If you can't break out of your loop, the problem is your algorithm or your condition.
Solutions
First, always debug to see if you enter your if statement.
Second, use something else as condition of your while loop. You could use a boolean and change its value to break the while condition. Ex:
boolean hasFoundDuplicate = false;
while(!hasFoundDuplicate){
arr[j-1] = (int)Math.floor(arr[j-1]/2);
after = arr[j-1];
operations++;
if(arr[j] == 0 && arr[j-1] == 0){
hasFoundDuplicate = true;
}
}

find all subsets of array having subset of size greater than or equal to 2

The below code prints all subsets, but I need of size greater than or equal to 2.
public static void printSubsets(char set[])
{
int n = set.length;
for (int i = 0; i < (1<<n); i++)
{
System.out.print("{ ");
for (int j = 0; j < n; j++)
if ((i & (1 << j)) >0 )
System.out.print(set[j] + " ");
System.out.println("}");
}
}
A subset of size 0 corresponds to i == 0. To eliminate the empty subset start at i = 1.
A subset of size 1 corresponds to i having exactly one bit set; or, equivalently, when it is a power of 2. A positive number i is a power of two if (i & (i - 1)) == 0.
for (int i = 1; i < (1<<n); i++) {
if ((i & (i - 1)) == 0) {
continue;
}
System.out.print("{ ");
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0) {
System.out.print(set[j] + " ");
}
}
System.out.println("}");
}
Alternatively, you could keep your original loop and simply insert this check:
if (Integer.bitCount(i) < 2) {
continue;
}
It's not as clever or efficient, but it is nice and readable.

Java output in lines of ten

I'm in a beginners java class and I have a quick question about the output statement on my array problem for week 5. So basically I have the core of the program down, but I'm supposed to output the result in lines of ten. I for some reason can not get it to work even with looking at similar posts on here. I'm a beginner and am pretty slow at putting 2 and 2 together when it comes to programming. Once I see it I have that ah-ha! moment and that's how this whole class has gone. I know I have to use the modulus, but in my trial and error I lost my way and have probably done more damage than good. Help would be appreciated.
Here is what I have and as you can tell I was trying something without modulus:
import java.util.*;
public class ArrayLoop
{
public static void main(String args[])
{
double alpha[] = new double[50];
*//Initialize the first 25 elements of the array (int i=0; i<25; i++)//*
for(int i = 0; i < 25; i++)
{
alpha[i]= i * i;
}
*//Initialize the last 25 elements of the array (i=25; i<50; i++)//*
for(int i = 25; i < 50; i++)
{
alpha[i]= 3 * i;
}
*//Print the element of the array*
System.out.println ( "The values are: " );
for (int i = 0; i < 50; i++)
System.out.println ( alpha[i] );
}
*//Print method to display the element of the array*
void print(double m_array[])
{
for(int i = 1; i < m_array.length; i++)
{
if(i % 10 == 0){;
System.out.println();
}else{
System.out.print(" ");
}
}
if (m_array.length % 10 != 0) {
System.out.println();
}
}
}
Um .. this isn't eloquent in the least but I tried to make the fewest changes to your existing code sample.
public class ArrayLoop {
public static void main(String args[]) {
double alpha[] = new double[50];
for (int i = 0; i < 25; i++) {
alpha[i] = i * i;
}
for (int i = 25; i < 50; i++) {
alpha[i] = 3 * i;
}
System.out.println("The values are: ");
for (int i = 0; i < 50; i++) {
System.out.print(alpha[i] + " ");
}
System.out.println();
System.out.println();
for (int i = 1; i < alpha.length; i++) {
if (i != 1 && i % 10 == 0) {
System.out.print(alpha[i - 1] + " ");
System.out.println();
} else {
System.out.print(alpha[i - 1] + " ");
}
}
System.out.print(alpha[49]);
}
}
Edit: A better condition would be ...
for (int i = 0; i < alpha.length; i++) {
if (i > 0 && i % 10 == 9) {
System.out.print(alpha[i] + " ");
System.out.println();
} else {
System.out.print(alpha[i] + " ");
}
}
You have to print the number first then decide whether to print space or newline by checking the modulus:
int arr[] = new int[50];
// Initialize array here
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i > 0 && (i + 1) % 10 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
You have a couple of % 10 snippets in your code so I'm not entirely certain how that's "trying something without modulus" :-)
Having said that, modulus is exactly what you need, as per the following psuedo-code:
count = 0
for each item in list:
if count > 0 and (count % 10) == 0:
print end of line
print item
print end of line
In Java, you would use something like:
public class Test {
static public void main(String args[]) {
for (int i = 0; i < 24; i++) {
if ((i > 0) &&((i % 10) == 0)) {
System.out.println();
}
System.out.print ("" + i * 3 + " ");
}
System.out.println();
}
}
In other words, immediately before you print an item, check to see if it should be on the next line and, if so, output a newline before printing it.
Note that arrays in Java are zero based, so you need to start with an index of zero rather than one in your loops.
Now that's pretty close to what you have so you're on the right track but, for the life of me, I cannot see in your print() method where you actually print the item! That should be number one on your list of things to look into :-)
I urge you to try and work it out from the above text and samples but, if you're still having troubles after more than half an hour or so, the below code shows how I'd do it.
public class Test {
static void print (double m_array[]) {
for (int i = 0; i < m_array.length; i++) {
if ((i > 0) && ((i % 10) == 0))
System.out.println();
System.out.print (m_array[i] + " ");
}
System.out.println();
}
static public void main(String args[]) {
double[] x = new double[15];
for (int i = 0; i < x.length; i++)
x[i] = i * 3;
print (x);
}
}

Binary to decimal, error message

I wrote a program that convert a binary number to decimal number.
When I run the program with some binary number, the program give me the decimal number but with an error message.
my code:
public class ohad {
public static void main(String[] args) {
String bin = "10011";
int length = bin.length();
int j = 0;
int sum = 0;
if (length != 0) {
for (int i=0; i < bin.length(); i++){
if (bin.charAt(i) == '0' || bin.charAt(i) == '1'){
for (int t = (length - 1); t >= 0; t--){
String s = bin.charAt(j) + "";
sum = (int)(sum + (Integer.valueOf(s)) * (Math.pow(2, t)));
j++;
}
System.out.println(sum);
}
else {
System.out.println("illegal input.");
}
}
} else {
System.out.println("illegal input.");
}
}
}
error message:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:646)
at ohad.main(ohad.java:15)
I think it's something with my j index. What should I do?
What should I do?
I would use Integer.parseInt(String,int) like
String bin = "10011";
System.out.println(Integer.parseInt(bin, 2));
Output is
19
Do you need j index? Looking at this quickly, I think you can use i index instead j.
String s = bin.charAt(j) + "";
String s = bin.charAt(i) + "";
You need to reset your j variable.
in the second iteration of the i for loop that is for (int i=0; i < bin.length(); i++){
j goes out of bounds as it is not set to zero again try the following code :
for (int i=0; i < bin.length(); i++){
j=0; // add this
if (bin.charAt(i) == '0' || bin.charAt(i) == '1'){
for (int t = (length - 1); t >= 0; t--){
String s = bin.charAt(j) + "";
sum = (int)(sum + (Integer.valueOf(s)) * (Math.pow(2, t)));
j++;
}
System.out.println(sum);
} else {
System.out.println("illegal input.");
}
}
While Elliott's answer is absolutely correct and gives a much easier way of solving the problem of converting a binary number to its decimal equivalent, it does not tell you what is causing the error.
You are correct that the exception is thrown because of the j variable, the issue lies in that the j variable is never set back to 0 when the inner loop (with index variable t). I changed your code to reflect this:
for (int t = (length - 1); t >= 0; t--){
String s = bin.charAt(j) + "";
sum = (int)(sum + (Integer.valueOf(s)) * (Math.pow(2, t)));
j++;
}
j = 0; //this is the added code
System.out.println(sum);
This prevents the exception being thrown however causes another issue with the loop being called again, printing each time until you hit 95. I'll let you fix this problem.
You've got one loop too much. That's why j keeps increasing causing the error message.
Delete the t loop:
public static void main(String[] args) {
String bin = "10011";
int length = bin.length();
int j = 0;
int sum = 0;
if (length != 0) {
for (int i = length - 1; i >= 0; i--) {
if (bin.charAt(i) == '0' || bin.charAt(i) == '1') {
String s = bin.charAt(j) + "";
sum = (int) (sum + (Integer.valueOf(s)) * (Math.pow(2, i)));
j++;
} else {
System.out.println("illegal input.");
}
}
System.out.println(sum);
} else {
System.out.println("illegal input.");
}
}

Making a hollow diamond with a word in it

What I need is a little modification to my code so that every part of my hollow diamond prints a letter of the word "HURRICANE"
My code is:
String st1 = "HURRICANE";
int a = 0;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(a)); //needs change
} else {
System.out.print(' ');
}
}
System.out.println();
}
for (int i = 2; i <= 5; i++) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(a)); //needs change
} else {
System.out.print(' ');
}
}
System.out.println();
}
The output comes out as:
H
H H
H H
H H
H H
H H
H H
H H
H
I need to modify my "charAt" statement a little so it comes out to be:
H
U U
R R
R R
I I
C C
A A
N N
E
How should I make my print statement?
It's worth noting that the example provided only works for Strings the same length as "HURRICANE". A superior solution would work for all strings.
Partial solution for you to complete, since I guess it's your coursework and I don't want you to copy / paste / fail exams :P
public static void main(String[] args) {
String st1 = "HURRICANE";
char[] st1CharArray = st1.toCharArray();
int maxSpaces = st1CharArray.length / 2 + 1;
for (int i = 0; i <= st1CharArray.length / 2; i++) {
if (i == 0) {
System.out.println(getSpacesString(maxSpaces) + st1CharArray[i]);
} else {
System.out.println(getSpacesString(maxSpaces - i)
+ st1CharArray[i] + getSpacesString(i * 2 - 1)
+ st1CharArray[i]);
}
}
// Loop from st1CharArray.length / 2 + 1 and get the second half done.
}
private static String getSpacesString(int numberOfSpaces) {
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < numberOfSpaces; i++) {
strBuilder.append(" ");
}
return strBuilder.toString();
}
//: Playground - noun: a place where people can play
import UIKit
var name : String = "HURRICANE"
var dimensions : Int = name.count - 1
var k : Int = 0
for rows in 0...dimensions{
for columns in 0...dimensions{
k = abs( (dimensions/2) - rows )
if columns == k || columns == dimensions - k{
print(Array(name)[rows], terminator: "")
}
else{
print(" ", terminator: "" )
}
}
print("")
}
String st1 = "HURRICANE";
int a = 0;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(5 - i));
} else {
System.out.print(' ');
}
}
System.out.println();
}
for (int i = 2; i <= 5; i++) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(3 + i));
} else {
System.out.print(' ');
}
}
System.out.println();
}
Let's assume that a word has an odd number of characters, otherwise we get a crooked diamond.
Try it online!
public static void main(String[] args) {
String str = "abrahadabra";
int n = str.length() / 2;
for (int i = -n, ch = 0; i <= n && ch < str.length(); i++, ch++) {
for (int j = -n; j <= n; j++)
if (Math.abs(i) + Math.abs(j) == n)
System.out.print(str.charAt(ch));
else
System.out.print(" ");
System.out.println();
}
}
Output:
a
b b
r r
a a
h h
a a
d d
a a
b b
r r
a

Categories