Java Programming nested loops - java

So I have most of my code written, but there's one part of the assignment that I don't understand.
Write a program that will accept a number (n) from the user to represent the size of a board (nxn). If the user does not enter a number greater than 1, prompt the user over and over until he/she gives valid input.
Once valid input is obtained, print a board with every other column filled with 1s along with the last row filled with 1s. Zeros everywhere else. Your board will have an equal number of rows and columns based on the users input.
I have it to do the pattern with the 0's and 1's but I don't understand how I can get the last row to have all 1's. Here is my code posted below
import java.util.Scanner;
public class question1 {
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Please input a value for the board greater than 1.");
n= input.nextInt();
while(n<1)
{
System.out.println("Error, please enter a value greater than 1");
n=input.nextInt();
}
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(j%2==0)
{
System.out.print(0);
}
else
{
System.out.print(1);
}
if(i==n)
{
System.out.print(1);
}
}
System.out.println(' ');
}
}
}

Change your loops to:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == n - 1) {
System.out.print(1);
} else {
System.out.print(j % 2);
}
}
System.out.println();
}

if(i==n)
{
System.out.print(1);
}
you should just change to (i == n-1)

Related

Can you use charAt();'s to compare values in a string?

I'm writing a java code currently for class and I'm trying to figure out how to implement a run length encoding on a user input. The main problem I'm having it with comparing the first letter with the next and that letter with the next and so on to see if they're the same letter. Currently I have:
System.out.print("Enter a string: ");
String s1 = reader.nextLine();
int sum = 0;
char ast = '*';
//System.out.println("Run length encoded version of string: ");
for (int counter = 0; s1.charAt(counter) <= s1.length()-1; counter++) {
for (int j = 0; s1.charAt(counter) == s1.charAt(j)+1; j++) {
sum++;
counter++;
}
if (sum >= 4) {
System.out.print(ast + s1.charAt(counter) + sum);
}
else {
System.out.print(s1.charAt(counter));
}
}
I know where the big problem comes from in this and why it doesn't work but, namely from the
for (int j = 0; s1.charAt(counter) == s1.charAt(j)+1; j++) {
sum++;
counter++;
}
segment as it just goes infinitely. Is there a proper way to do this? The professor mentioned it can be done without loops and while I can see it being possible I can't see it being short. Any help would be appreciated, thanks!
String str="ayyusaab";
char[] ch=str.toCharArray();
for(int i=0;i<ch.length-1;i++){
for(int j=i+1;j<ch.length-1;j++){
if(ch[i]==ch[j]) {
System.out.println(ch[i]+" at Index "+i +"with j at "+j);
}
}
}

How do I let my program print a complete right angle triangle for certain values?

I tested the program out with 88 and it was left with one star to complete the triangle. 87, two stars 86 three stars. This went on for certain numbers.
These are the two options for programming generate function
• One is to compute the length of the last line, say maxLen, and use a double for-loop to generate a line of one star, a line of two stars, a line of three starts, and so on, ending with a line of maxLen stars. The value of maxLen is the smallest integer that is greater than or equal to the
larger solution of the quadratic equation x ( x + 1 ) = 2 * num.
• The other is to use one for-loop to print num stars while executing System.out.println()wherever the newline is needed. The point at which the newline is needed can be computed using two accompanying integer variables, say len and count. Here the former is the length of the line being generated and the count is the number of stars yet to be printed in the line. We start by setting the value of 1 to both integer variables. At each round of the iteration, we decrease the value of count, if the value of count becomes 0, we insert the newline, increase the value of len and then copy of the value of len to count. When the loop terminates, if the value of count is neither equal to 0 nor equal to count, we extend the present line by adding more stars.
import java.util.*;
public class TriangleSingle
{
public static void generate(int x) //Generates the Triangle
{
int len, count;
len = 1;
count = 1;
for (int k = 1; k <= x; k++)
{
System.out.print("*");
count --;
if (count == 0)
{
System.out.println();
len ++;
count = len;
}
}
if (count!= 0 || count != len)
{
System.out.println("*"); //Completes the triangle if needed
// This is the **problem spot**
}
Try this:-
public static void generate(int x) //Generates the Triangle
{
int len, count;
len = 1;
count = 1;
for (int k = 1; k <= x; k++)
{
for (int i = 1; i <= k; i++) {
System.out.print("*");
}
System.out.println();
}
}
The trick is to increment the count c of printed stars in the inner loop, which prints each row, but check it against the desired number n in the outer loop, which determines how many rows to print. This way we're sure to print complete rows, but we stop as soon as we've printed at least n stars.
public static void generate(int n)
{
for(int c=0, i=0; c<n; i++)
{
for(int j=0; j<=i; j++, c++)
System.out.print('*');
System.out.println();
}
}
Try this out !!!
public class pyramid {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Input Length of pyramid : ");
int length = s.nextInt();
for (int i = 1; i <= length; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*\t");
}
System.out.println("\n");
}
}
Check this out :
public static void generate(int x) //Generates the Triangle
{
int len, count;
len = 1;
count = 1;
for (int k = 1; k <= x;)
{
System.out.print("*");
count --;
if (count == 0)
{
System.out.println();
len ++;
k++;
count = len;
}
}

Output displayed automatically without doing anything

So , I am trying to create a program which calculates the score of an exam . What we have to do is give a pattern as a string consisting X's and 0's i.e 000XXX000XXX, where the value of 'X' is 0 and the value of each zero is 1 and for every consecutive '0' the value increases by 1 . If suppose there are 2 or more consecutive 0's and then an 'X' the value of '0' is reset to 1.if the program seems common to you , then , yes this is a problem from an OJ and it was given to me by a senior from my university to solve.Now the thing is I have figured out how the code works and solved the problem.But there seems to be an issue in the code.
package javaapplication4;
import java.util.Scanner;
public class JavaApplication4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T, score = 0, f = 0, g = 0;
String str;
int len;
T = sc.nextInt();
for (int i = 1; i <= T; i++) {
str = sc.nextLine();
len = str.length();
for (int j = 0; j < len; j++) {
if (str.charAt(j) == '0') {
f++;
score = score + f;
}
else if(str.charAt(j) == 'X')
{
f = 0;
score = score + g;
}
}
System.out.println(score);
}
}
}
As you can see from the code , I first give an Input for the number of test cases and as soon as I press enter , the code displays the value of score (which is 0) automatically without doing any think inside the for loop.
I have rechecked all the curly braces, but I cannot find the bug in the code. I would be happy if I could get some help.
Output:
4
0
The sc.nextInt() causes the sc.nextLine() to be triggered so you get the output of a empty string that's why it's zero, by using sc.nextLine() for input of your test case number you can prevent this:
int score = 0;
System.out.println("Enter test case:");
int testCase= Integer.parseInt(sc.nextLine());
for (int i = 1; i <= testCase; ++i)
{
System.out.println("Enter pattern:");
String str = sc.nextLine();
for (int j = 0; j < str.length(); j++)
{
if (str.charAt(j) == '0')
{
score += 1;
}
else if (str.charAt(j) == 'X')
{
score += 0;
}
}
System.out.println(score);
score = 0; // reset score to zero for the next test case
}
See this link regarding the sc.nextInt() issue : Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

Java - Incrementing Numbers using for loop

I have attempted to complete the following exercise however the output isn't as expected.
You should print a number of pluses equal to the number entered by the user, followed by a list of numbers, so that in total exactly 20 characters are printed. The numbers printed should be the last digit of the current position in the list. Example: +++++678901234567890 if the number entered by the user was 5.
Here's my code:
package interact;
import java.util.Scanner;
public class Interact {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
{int value,k
for (int i=0; i<num1; i++) {
System.out.print("+");}
for (int j=0; j<20-num1; j++) {
if (num1>9) {k=num1-10;}
else k=num1+1;
System.out.print(k);
}
}
The output if 6 is entered is ++++++77777777777777. The numbers aren't incrementing - why not?
You aren't incrementing k or num1, so k becomes whatever number the user enters + 1, and keeps printing that out. You need to update k. First set k=num1. Then change your loop to:
if (k>9) {k=0;}
else k++;
System.out.print(k);
Since, your num1 remains same throughout the below loop.
for (int j=0; j<20-num1; j++) {
if (num1>9) {k=num1-10;}
else k=num1+1;
System.out.print(k);
}
But if you do like this it'll work
k=num1+1;
for (int j=0; j<20-num1; j++) {
if (k>9) {k=0;}
System.out.print(k);
k++;
}
This should fix it for you :)
i can answer any questions you got on the modification :)
good luck :)
int value, k;
for (int i = 0; i < num1; i++) {
System.out.print("+");
}
k=num1;
for (int j = 0; j < 20 - num1; j++) {
if (k >= 9) {
k = 0;
}
else
k++;
System.out.print(k);
}

pyramid sequence in Java

I am new to Java. Just now I'm practing. If I give input as 6, output should be like this:
1
2 3
4 5 6
Here I'm posting code that I tried:
import java.util.Scanner;
public class Number {
public static void main(String args[]){
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
in.close();
int k = 1;
for (int i = 1; i <= n; i++)
{
// k=i;
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
break;
}
k++;
}
System.out.println("\n");
}
}
}
If I input n=4,i t show the output as:
1
2 3
4
4
Your break will only exit the inner loop (the one that loops over j). The outer loop will continue to run, leading to extra numbers being printed.
You need to either replace it with a return; or System.exit(0), or put a label in front of your outer loop (the one that loops over i) and use a labeled break.
Properly indent your code. It helps your brain to understand.
That said, the solution is two loops with three variables.
You need a loop that goes from 1 to n.
An inner loop that goes from 1 to the number of elements per line.
And you need the number of elements per line. This variable increases every time the inner loop is executed.
It's a badly worded question, but I'm going to guess you want to know why the extra 4?
The reason is you have nested loops, so the break only breaks one loop. Here's how you break out of the outer loop:
outer: for (int i = 1; i <= n; i++) {
...
break outer;
The label outer is arbitrary - you can call it fred is you want.
int n = 6; // target
int i = 0;
int nextRowAt = 2;
int currentRow = 1;
while (++i <= n) {
if (i == nextRowAt) {
System.out.println();
nextRowAt = ++currentRow + i;
}
System.out.print("" + i + " ");
}
But unless you understand it and can properly explain the code, you will probably get a fail on your assignment.
My suggestion is to start by creating/understanding on pen and paper. Write out the sequences and figure out how the algorithm should work. THEN you start coding it.
int sum =0;
int n =10;
// n------> number till where you want to print
boolean limtCrossed = false;
for (int i = 0; i < n &&!limtCrossed; i++) {
for(int j=0;j<=i;j++) {
sum++;
if (sum>n) {
limtCrossed = true;
break;
}
System.out.print(+ sum +" " );
}
System.out.println("\n");
}
public static void main(String[] args)
{
int n = 10;
int k = 1;
boolean breakOuter = false;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
breakOuter = true;
break;
}
k++;
}
if(breakOuter) break;
System.out.println("\n");
}
}

Categories

Resources