Java nested while loops - java

I need nested while loops to print so that the outter loop k makes one decrement iteration every time that inner loop "I" finishes an iteration. K has to start at 5 and count back to 1 and I has to starts at 0 and count to 10 by 2's. So it would the out put would look like this:
K = 5 I = 0
K = 5 I = 2
K = 5 I = 4
K = 5 I = 6
K = 5 I = 8
K = 5 I = 10
K = 4 I = 0
I have been stumped for hours and tried everyway to I can think of to make it work. Can someone please help?
public class Task1 {
public static int i = 0;
public static int k = 5;
public static void Display(){
while(k > 1){
while(i >=10){
i = i+2;
System.out.println("K = " + k + " I = " + i);
}
if (i >= 10){
k=k-1;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Display();
}
}

There are a few errors. Follow the comments
while(k >= 1){ // Make it >= instead of >
i = 0; // reset i
while(i <=10){ // Make it i<= (less than)
System.out.println("K = " + k + " I = " + i); //print before incrementing
i = i+2;
}
Rest of the code is correct. And the output is as expected
K = 5 I = 0
K = 5 I = 2
K = 5 I = 4
K = 5 I = 6
K = 5 I = 8
K = 5 I = 10
K = 4 I = 0
K = 4 I = 2
K = 4 I = 4
K = 4 I = 6
.
.
.

You need to initialize i before the start of the inner loop, inside the outer loop, so it gets reset each time

while(k > 1) {
i = 0;
while( i <= 10) {
Print
i += 2;
}
k--;
}
Your inner while loop condition was incorrect. And you were adding to i too soon so you would never print for 0.

Something like this
public class Task1 {
public static int i = 0;
public static int k = 5;
public static void Display(){
while(k > 0){
i = 0;
while(i <= 10){
System.out.println("K = " + k + " I = " + i);
i+=2;
}
k--;
}
}
public static void main(String[] args) {
Display();
}
}

Replace your display method with this..
public static void Display(){
while(k > 1){
i=0; //initialise i back to 0
while(i <=10){ //Change >= to <=
i = i+2;
System.out.println("K = " + k + " I = " + i);
}
k--;
//comment or delete below if block
/*if (i >= 10){
k=k-1;
}*/
}
}

use the following code.
public class Task1 {
public static int i = 0;
public static int k = 5;
public static void Display() {
while (k >= 1) { // use >=1 if you wanna print till 1
i = 0; // set i=0
while (i <= 10) {
System.out.println("K = " + k + " I = " + i); // add print
// statement
i = i + 2;
}
k--; // no need to use if (i >= 10){ }
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Display();
}
}

You can do it like this:
for(int k = 5;k>0;k--;){
for(int i = 0;i<10;i+=2;)
System.out.println(k+ "" +i)
}

Related

How do I print out factors of an input using loops?

Here is my mess of a code. I have to write a program that inputs a positive integer greater than 3. Validate that the integer is in fact greater than 3. Then print all possible pairs of positive integers great than whose product is less than or equal to the number entered.
ex. If 24 is the input.
It would print:
4 = 2 x 2
6 = 2 x 3
8 = 2 x 4
10 = 2 x 5
12 = 2 x 6
14 = 2 x 7
16 = 2 x 8....
9 = 3 x 3
12 = 3 x 4..
24 = 3 x 8...
all the way to
24 = 4 x 6
import java.util.Scanner;
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int j = 0;
int k = 2;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
while (product < i) {
if (product == i) { j++; k = 2;
for (j = 2; product < i; k++) {
product = j * k;
System.out.println(product + " = " + j + " x " + k);
if (product == i) { j++; k = 2;
}
}
}
}
}
}
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
for (int j = 2; j < i / 2; j++) {
for (int k = 2; k < i / 2; k++) {
if (j <= k && j * k <= i)
System.out.println(j * k + " = " + j + "*" + k);
}
}
// while (product < i) {
// if (product == i) {
// j++;
// k = 2;
// for (j = 2; product < i; k++) {
// product = j * k;
// System.out.println(product + " = " + j + " x " + k);
// if (product == i) {
// j++;
// k = 2;
// }
// }
// }
// }
}
}

Printing integer from 2D array using nested FOR Loops

I'm having a bit of a problem with a piece of Java code, part of an AI project. The programm is supposed to take a 11x13 2d array representing a maze. The printed maze we are given uses characters for each cell, but for ease of use I've converted it to integers using a mnemonic code.
My problem is when I try to print the 2d integer array to the screen, to check eveything is OK, I get zeros at every cell, even though I have a check function in place which parses the array cell-by-cell checking for incorrect values.
The project is currently composed of 2 files. The main file - function (AISemesterProject.java) and a file that will implement the UCS algorithm in the future (UCS.java)
AISemesterProject.java
package aisemesterproject;
public class AISemesterProject
{
public static void main(String[] args)
{
UCS a = new UCS();
a.checkArrayInt();
a.printInt();
}
}
UCS.java
package aisemesterproject;
import java.util.Arrays;
public class UCS
{
int row = 11;
int col = 13;
int[][] array_int = new int[row][col];
public UCS()
{
// Lets assume
// x = 0
// e = 1
// d = 2
// s = 8
// g = 9
int[][] array_int = new int[][] {
{0,1,0,1,1,1,1,0,0,1,0,9,0},
{1,1,1,2,0,1,1,0,0,1,2,1,0},
{0,1,0,1,1,1,1,0,0,1,0,0,0},
{8,1,2,0,1,2,0,1,1,2,1,1,1},
{0,0,1,1,0,1,1,1,0,0,0,0,0},
{1,2,1,0,1,0,1,1,0,0,1,1,1},
{0,1,2,0,1,0,0,2,1,1,2,1,9},
{1,0,1,1,2,1,1,1,0,1,1,1,1},
{1,1,2,1,1,0,0,1,0,0,0,0,0},
{0,0,1,1,1,0,0,1,1,1,1,1,2},
{0,0,1,0,0,1,1,1,0,9,0,1,1}
};
}
public void checkArrayInt()
{
int i = 0, j = 0;
boolean checker = false;
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
if(!(array_int[i][i] == 0 || array_int[i][j] == 1 || array_int[i][j] == 2 || array_int[i][j] == 8 || array_int[i][j] == 9))
{
checker = true;
System.out.print("Error at Row:" + i + " Column:" + j + "\n");
}
}
}
if(checker == false)
{
System.out.print("Array OK... \n");
}
}
public void printInt()
{
int i = 0, j = 0;
//System.out.println(Arrays.deepToString(array_int));
for(i = 0; i < row; i++)
{
System.out.print("Row " + (i + 1) + ":");
for(j = 0; j < col; j++)
{
System.out.print(" " + String.valueOf(array_int[i][j]));
//System.out.print(" " + Integer.toString(array_int[i][j]));
//System.out.printf(" %d", array_int[i][j]);
//System.out.print(" " + array_int[i][j]);
}
System.out.print("\n");
}
}
}
Output
As you can see the output is not what I expected and I have tried 4 different methods for the print (1 active, 3 commented) but the result is always the same.
Anyone have an idea what am I missing or doing wrong?
Thanks for your time.
It looks like you have a scope issue...
int[][] array_int = new int[row][col];
public UCS()
{
// Lets assume
// x = 0
// e = 1
// d = 2
// s = 8
// g = 9
array_int = new int[][] {
{0,1,0,1,1,1,1,0,0,1,0,9,0},
{1,1,1,2,0,1,1,0,0,1,2,1,0},
{0,1,0,1,1,1,1,0,0,1,0,0,0},
{8,1,2,0,1,2,0,1,1,2,1,1,1},
{0,0,1,1,0,1,1,1,0,0,0,0,0},
{1,2,1,0,1,0,1,1,0,0,1,1,1},
{0,1,2,0,1,0,0,2,1,1,2,1,9},
{1,0,1,1,2,1,1,1,0,1,1,1,1},
{1,1,2,1,1,0,0,1,0,0,0,0,0},
{0,0,1,1,1,0,0,1,1,1,1,1,2},
{0,0,1,0,0,1,1,1,0,9,0,1,1}
};
you already created the array as a class level variable
Your constructor is setting the local variable array_int. This local variable overshadows the field with the same name, and thus it never sees the array you're assigning to it.
You should make sure that you're assigning to the field, which can most easily be done by removing the int[][] word from your constructor.
Thank you everyone. I moved the declatarion from the constructor to the variable at the beggining and it worked.
package aisemesterproject;
import java.util.Arrays;
public class UCS
{
int row = 11;
int col = 13;
// Lets assume
// x = 0
// e = 1
// d = 2
// s = 8
// g = 9
int[][] array_int = new int[][] {
{0,1,0,1,1,1,1,0,0,1,0,9,0},
{1,1,1,2,0,1,1,0,0,1,2,1,0},
{0,1,0,1,1,1,1,0,0,1,0,0,0},
{8,1,2,0,1,2,0,1,1,2,1,1,1},
{0,0,1,1,0,1,1,1,0,0,0,0,0},
{1,2,1,0,1,0,1,1,0,0,1,1,1},
{0,1,2,0,1,0,0,2,1,1,2,1,9},
{1,0,1,1,2,1,1,1,0,1,1,1,1},
{1,1,2,1,1,0,0,1,0,0,0,0,0},
{0,0,1,1,1,0,0,1,1,1,1,1,2},
{0,0,1,0,0,1,1,1,0,9,0,1,1}
};
public UCS()
{
// Lets assume
// x = 0
// e = 1
// d = 2
// s = 8
// g = 9
// Array initialization outside the constructor scope
}
public void checkArrayInt()
{
int i = 0, j = 0;
boolean checker = false;
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
if(array_int[i][j] == 0) //Check for 0 = x
{
checker = false;
}
else if(array_int[i][j] == 1) //Check for 1 = e
{
checker = false;
}
else if(array_int[i][j] == 2) //Check for 2 = d
{
checker = false;
}
else if(array_int[i][j] == 8) //Check for 8 = s
{
checker = false;
}
else if(array_int[i][j] == 9) //Check for 9 = g
{
checker = false;
}
else //All other integers, which are false
{
checker = true;
System.out.print("Error at Row:" + i + " Column:" + j + "\n");
}
}
}
if(checker == false)
{
System.out.print("Array OK... \n");
}
}
public void printInt()
{
int i = 0, j = 0;
//System.out.println(Arrays.deepToString(array_int));
for(i = 0; i < row; i++)
{
System.out.print("Row " + (i + 1) + ":");
for(j = 0; j < col; j++)
{
System.out.print(" " + String.valueOf(array_int[i][j]));
//System.out.print(" " + Integer.toString(array_int[i][j]));
//System.out.printf(" %d", array_int[i][j]);
//System.out.print(" " + array_int[i][j]);
}
System.out.print("\n");
}
}
}

Java For loop !!! printing out values

Write a program that generates a sequence of 20 random die tosses in an array and
that prints the die values, marking only the longest run, like this:
1 2 5 5 3 1 2 4 3 (2 2 2 2) 3 6 5 5 6 3 1
If there is more than one run of maximum length, mark the first one.
I am working on this question and this code works till count the maxCount.
However, I am stuck in printing out the final result which means I am working on the last for loop to print out what the question requires.
But, the result is not what I wanted to get. How can I figure it out?
import java.util.Random;
public class AA {
public static void main(String[] args) {
int count = 1;
int maxCount = 1;
int runEndsAt = 0;
// create array
int[] num = new int[20];
// create random object
Random numbers = new Random();
for (int i = 0; i < 20; i++) {
num[i] = numbers.nextInt(6) + 1;
// added 1 b/c it starts from 0
}
boolean inRun = false;
for (int i = 0; i < num.length; i++) {
if (inRun) {
if (num[i] != num[i - 1]) {
/*
* System.out.print("|" + count +"|");
* System.out.print(") ");
*/ inRun = false;
}
if (inRun) {
System.out.print("|" + count + "|");
count++;
}
}
if (!inRun) {
if (count > maxCount) {
maxCount = count;
runEndsAt = i;
}
count = 1;
if (i < 19)
// comparing index from i to i+1
if (num[i] == num[i + 1]) {
System.out.print("( ");
inRun = true;
}
}
}
if (inRun) {
/*
* System.out.print("|" + count +"|"); System.out.print(" )");
*/ }
for (int i = 0; i < num.length; i++) {
if (i == runEndsAt - maxCount) {
System.out.println("(");
if (i == runEndsAt) {
System.out.println(")");
}
}
}
}
}
If you are in Java - you may want to use StringBuilder.
Solution:
import java.util.stream.IntStream;
public class LongestRun {
public static void main(String[] args) {
// We are told that die tosses is an Array... so we create one.
int[] tosses = IntStream.range(0, 20)
.map(i -> { return (int) (Math.random() * 6 + 1); } )
.peek(System.out::print)
.toArray();
// Counting and generation of output:
int length = 0, longest = 0, startPos = 0;
StringBuilder sb = new StringBuilder(""+tosses[0]);
for (int i=1; i<tosses.length; i++) {
if (tosses[i-1] == tosses[i]) {
length++;
} else {
length=0;
}
if (longest < length) {
longest = length;
startPos = i-length;
}
sb.append("" + tosses[i]);
}
sb.insert(startPos+longest+1, ")");
sb.insert(startPos, "(");
// Final result:
System.out.println("Result:");
System.out.println(sb.toString());
}
}
Sounds like a fun problem. Here is my solution:
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SO_40307704 {
private final static int NUM_ROLLS = 100;
private final static Pattern PATTERN = Pattern.compile("(\\d)(\\1)+");
public static void main(String... args) {
final Random r = new Random();
final String rolls = Stream.generate(() -> r.nextInt(6) + 1)
.limit(NUM_ROLLS)
.map(i -> Integer.toString(i))
.collect(Collectors.joining());
Matcher m = PATTERN.matcher(rolls);
int start = 1;
int end = 0;
while (m.find()) {
if (m.end() - m.start() > end - start) {
end = m.end();
start = m.start();
}
}
System.out.println(String.format(
"%s(%s)%s",
rolls.substring(0, start),
rolls.substring(start, end),
rolls.substring(end)));
}
}
Hope it helps

Cannot figure out how to get Pascal Triangle In Java

I am supposed to get this series
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
NOTE:The spaces mentioned have to be present it should have the exact same output as i have mentioned
I tried this:
class pattern_19
{
static void main()
{
int i,j;
int s=1;
System.out.println(s);
for(i=1;i<=6;i++)
{
for(j=1;j<=i;j++)
{
s=s*11;
}
System.out.println(s);
s=1;
}
}
}
MY OUTPUT:
11
121
1331
14641
161051
1771561
This did not work any help will be appreciated
Your code would not compile because your main method was not defined correctly. This is one thing but not the main reason why you were getting an unexpected output.
Your s variable represent one integer on each line.
What you'll have to do from there is split your int and print each one of the digits seperately.
Here is a correction, I used an enhanced loop and a charArray to print the digits seperately but there are other ways to achieve this of course (using a loop and integer division works also or modify the way you find s).
Solution
public static void main(String[] args) {
int i, j;
int s = 1;
System.out.println(s + " ");
for (i = 1; i <= 6; i++) {
for (j = 1; j <= i; j++) {
s = s * 11;
}
for (char c : String.valueOf(s).toCharArray()) System.out.print(c + " ");
System.out.println();
s = 1;
}
}
PS : Multiplying by 11 wont work when you'll need numbers with a length of 2. I'll edit my answer right now.
Here is the algorithm solution
public static void main(String[] args) {
int rows = 6;
int[][] triangle = new int[rows][rows];
for (int i = 1; i <= rows; i++) {
for (int j = 0; j < i; j++) {
if (j == 0) triangle[i - 1][j] = 1;
else triangle[i - 1][j] = triangle[i - 2][j - 1] + triangle[i - 2][j];
System.out.print(triangle[i - 1][j] + " ");
}
System.out.println();
}
}
I finally also got an alternative to do the same here it goes
public class PascalTriangle {
public static void main() {
int rows = 6;
for (int i = 0; i < rows; i++) {
int number = 1;
System.out.format("%" + (rows - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
Now this one is working properly .

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

Categories