Here is the question. I have to print this pattern eg For n = 5
For n = 5
****1
***232
**34543
*4567654
567898765
I have written logic for this problem but I am not able to solve it.
I can't make the last pattern print i.e. the decrease one 2 4,3 5,4
Here's my pattern For n = 5
****1
***232
**34544
*4567666
567898888
Can anyone help me out and tell what's wrong with my logic. How to fix it
My code down below
import java.util.Scanner;
import java.lang.*;
public class Main {
public static void main(String[] args) {
solve();
}
public static void solve(){
int n;
Scanner obj = new Scanner(System.in);
n = obj.nextInt();
for(int row =1;row<=n;row++){
int ans1 = row;
int spaces =1;
for( spaces = 1;spaces<=n-row;spaces++){
System.out.print("*");
}
for (int pattern01 = 1; pattern01<=row;pattern01++){
System.out.print(ans1);
ans1 = ans1 +1;
}
for ( int pattern2 = 1 ; pattern2<=row-1; pattern2++){
ans1= 2*row-2;
System.out.print(ans1);
ans1--;
}
System.out.println();
}
}
}
The issue you are having is that you are not decrementing 'ans1' correctly. If you are not sure how to use the debugger then observe your output through the console with print-out statements. Specifically the 3rd loop when 'ans1' is supposed to count backwards. Also, keep in mind the value of 'ans1' after you exit the second for-loop.
This is your second loop when you start to count up from row number variable.
You increment 'ans1' by 1 each iteration.
for (int pattern01 = 1; pattern01 <= row;pattern01++) {
System.out.print(ans1);
ans1 = ans1 + 1;
}
One thing to consider is that you are incrementing 'ans1' and what is the value of it before you enter your third loop to decrement? You need to do something here before you enter the loop and start printing.
Also, in your third loop you are not decrementing correctly. You should be counting backwards, or rather just decrementing by 1.
for(int pattern2 = 1;pattern2 <= row-1; pattern2++){
ans1= 2*row-2; // Your focus should be here, does this look right? Do you need it?
System.out.print(ans1); // You should decrement first and then print
ans1--; // this is correct, but in the wrong spot
}
I know you can pull it off :) You got this.
Related
My friend gave me this code and i cant seem to find the error in it. I am attaching the code below:
import java.util.*;
public class prg {
public static void main(String[] args) {
int n;
int count;
int a=0,b=1;
int c=0;
Scanner kb=new Scanner(System.in);
n=kb.nextInt();
int ar[]=new int[100];
ar[1] = 2;
for(int i=3;i<=n;i+=2)
{
count=0;
for (int j = 2; j < i ;j++ ) {
if (i % j == 0) {
count++;
break;
}
}
if(count==0)
ar[i]=i;
}
for(int i=0;i<=n;i+=2)
{
a = b;
b = c;
c = a + b;
ar[i]=c;
}
for(int i=0;i<14;i++)
System.out.print(ar[i]+" ");
}
}
So, the even index is storing the fibonacci series and the odd index is storing prime number.
Problem: the rest of the code is working fine but the 9th index of 'ar' array is printing 0 i dont know why and because of it the output is showing wrong.
Take input n as 14 and check the code please.
Thankyou in advance.
PS: i have solved this question in one other way so i request you to not give answers like 'try my method, its not efficient'. I just want to know what is going wrong at INDEX 9 of the array.
Edited: facing problem with the Prime Number loop.
When i is 9, your code correctly identifies that it is not a prime number, so count is not 0. This causes this line to not run:
ar[i]=i;
And then you increase i by 2 to check the next odd number. This means that you never set index 9 of the array to anything, so it remains at its default value - 0.
To fix this, you should introduce a new variable possiblePrime to keep track of which number you are checking. Increase this variable every iteration of the outer for loop, and increase i only when possiblePRime is prime. Also, change the above line to:
ar[i] = possiblePrime;
9 is not a prime number, so it sets nothing in the array. 0 is the default value so it gets printed.
I want to...
create an asterisk triangle, using Java, that matches the length of whatever number (Between 1-50) the user enters.
Details
The first line would always start with an asterisk.
The next line would increment by one asterisk until it matches the
user's input.
The following lines would then decrement until it is back to one
asterisk.
For instance, if the user was to enter 3, then the output would have one asterisk on the first line, two asterisks on the second line, three asterisks on the third line, and then revert back to two asterisks on the following line before ending with an asterisk on the last line.
What I've tried so far
I am required to use nested for loops. So far, I tried to test it out using this practice example I made below. I was only able to create on output of the numbers. I also have some concepts of outputting asterisk triangles. How can I apply the concept of this code to follow along the user's input number?
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int count, index = 0, value, number;
System.out.println("This program creates a pattern of numbers " );
System.out.println("Based on a number you enter." );
System.out.println("Please enter a positive integer. " );
count = keyboard.nextInt();
value = count;
for (index = 1; index <= count; index++)
{
for (number = value; number >= 1; number--)
{
System.out.println(number);
}
value--;
System.out.println();
}
}
}
Here's how i would proceed
write a method printAsterisks that takes an int N as parameter and writes a line of N asterisks. You wil need a for loop to do so.
call printAsterisks in a for loop that counts from 1 to COUNT
call printAsterisks in a second loop that counts down from COUNT-1 to 1
That should do the trick.
Also, as a side note, you should close your scanner. The easy way to do so is enclose ot in a try-with-resource like so :
try (Scanner keyboard = new Scanner(System.in);) {
// your code here
}
Let us know the version of the program taht works (or the question you still have) :)
HTH
Here is what you want:
public class Asterisk {
private static final String ASTERISK = "*";
private static final String SPACE = "";
private static int LENGTH;
public static void main(String[] args) {
try{
readLength();
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
}catch (Exception e) {
System.out.println("You must enter a number between 1 and 50.");
}
}
static void readLength(){
System.out.println("Enter asterisk's length (1-50)");
LENGTH = Integer.parseInt(System.console().readLine());
if (LENGTH<=0 || LENGTH>50)
throw new NumberFormatException();
}
static void drawLine(int asterisks){
StringBuilder line = new StringBuilder();
int spacesLeft = getLeftSpaceCount(asterisks);
int spacesRight = getRightSpaceCount(asterisks);
for (int i=0; i<spacesLeft; i++) {
line.append(SPACE);
}
for (int i=0; i<asterisks; i++) {
line.append(ASTERISK);
}
for (int i=0; i<spacesRight; i++) {
line.append(SPACE);
}
System.out.println(line.toString()+"\n");
}
static int getLeftSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
int mod = spaces%2;
return spaces/2 + mod;
}
static int getRightSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
return spaces/2;
}
}
I am required to use nested for loops
Yes, the main logic lies there...
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
The triangle using 5 as input.
*
**
***
****
*****
****
***
**
*
Tip:
There is an easier way to get input from the user usingSystem.console().readLine().
In regards to the printing part, I wanted to clean up the answers a little:
int input = 3; //just an example, you can hook in user input I'm sure!
for (int i = 1; i < (input * 2); i++) {
int amount = i > input ? i / 2 : i;
for (int a = 0; a < amount; a++)
System.out.print("*");
}
System.out.println();
}
For our loop conditions, a little explanation:
i < (input * 2): since i starts at 1 we can consider a few cases. If we have an input of 1 we need 1 row. input 2, 3 rows. 4: 5 rows. In short the relation of length to row count is row count = (length * 2) - 1, so I additionally offset by 1 by starting at 1 instead of 0.
i > input ? i / 2 : i: this is called a ternary statement, it's basically an if statement where you can get the value in the form boolean/if ? value_if_true : value_if_false. So if the row count is bigger than your requested length (more than halfway), the length gets divided by 2.
Additionally everything in that loop could be one line:
System.out.println(new String(new char[i > input ? i / 2 : i]).replace('\0', '*'));
And yeah, technically with a IntStream we could make this whole thing a one-line, though at that point I would be breaking out newlines for clarity
Keep in mind, I wouldn't call this the "beginner's solution", but hopefully it can intrigue you into learning about some other helpful little things about programming, for instance why it was I replaced \0 in my one-line example.
So I am counting votes from an input file, sample.txt:
3
Homer REP
Moe IND
Barney DEM
0 1 0 2 2 0
My code looks like this:
public static void main(String[] args) {
int numCans = StdIn.readInt();//Number of candidates
String[] cans = new String[numCans];//Array containing the candidates
String[] parts = new String[numCans];//Array that contains the parties.
int[] votes = new int[numCans];
int voteCount = 0;
for (int i = 0; i < numCans; i++){
cans[i] = StdIn.readString();
parts[i] = StdIn.readString();
}
while (!StdIn.isEmpty()){//for counting votes
for(int i = 0; i < votes.length; i++){
if(StdIn.readInt() == i){
votes[i]++;
StdOut.println(i);
}
}
voteCount++;
}
}
So what ends up happening is it counts about 2 votes. Thanks for your help!
readInt() will read a new integer from the input every time it's called. So here's what your loop does:
if(StdIn.readInt() == i){
votes[i]++;
StdOut.println(i);
}
First, i is 0. The program reads an integer and sees if it's 0.
Suppose the integer isn't 0. Now your for loop loops back, and executes this statement again with i = 1. Your if statement now reads another integer from the input. It doesn't use the same integer it read before. You told it to read an integer, so it reads one.
I think you can see this isn't what you want to do. Your readInt() must be outside the for loop. I think that once you make this change, you'll see that you don't need the for loop at all.
This is the version I'm working right now, where the loop does end but it just doesn't loop through each letter, instead it only repeats the first occurrence of the first letter.
For example, if sourcetext was the ugly and password was ugly it would repeat 4 (the position of u) four times (the length of ugly). Where as what I want it to do is repeat the loop four times (the length of ugly) but give back each position, not just the first (instead of 4444, I'm getting 4 5 6 7).
Am I using the wrong kind of loop to achieve this? I've tried a few different ways and at this point I am stuck. Also if the answer is really obvious please don't burn me at the stake, I've only been programming for three months and have really given it a go on my own.
import java.util.Scanner;
public static void main(String[] args) {
String letter, sourcetext;
Scanner sc;
int temp;
sc = new Scanner(System.in);
sourcetext = sc.nextLine();
letter = sc.nextLine();
for (int i= 0; i < letter.length(); i++) {
temp = sourcetext.indexOf(letter);
System.out.print(temp);
}
}
You always use the same index: indexOf(letter). I guest what you want is:
for (int i= 0; i < letter.length(); i++) {
temp = sourcetext.indexOf(letter.charAt(i));
System.out.print(temp);
}
I have a task about incremental values in a loop based on user input.
The task is that the following lines are generated in the console
*
**
***
****
*****
And the amount of lines are decided by user input. I.e. if the user types in 2 it gives the following output:
*
**
My current code is:
import static javax.swing.JOptionPane.*;
public class loop1 {
public static void main(String[] args){
int current_line = 0;
String input_line = showInputDialog("type here ");
int target_line = Integer.parseInt(input_line);
while (current_line != target_line){
String sign = "*";
System.out.println(sign);
current_line ++;
}
}
}
But I can't seem to get the number of asterisks (*) to increase for every time it runs. How can I accomplish this?
You need a nested loop. Each iteration of the outer loop (which is the loop you already have) would print a single row, and each iteration of the inner loop would print a single asterisk for the current row.
You actually need two loops here, but you only have one. You have a while loop to print out the asterisks, but you also need a loop to increment the number of asterisks printed out each time.
Some pseudocode might look like:
For (int i = 1 to whatever value the user entered):
For (int j = 1 to i):
Print an asterisk
Actual code would look like:
int numLines = Integer.parseInt(showInputDialog("type here "));
for(int numAsterisks = 0; numAsterisks < numLines; numAsterisks++) {
for(int i = 0; i < numAsterisks; i++) {
System.out.print("*");
}
System.out.println(); // Start a new line
}
You can make it simpler by using nested for loops. Modify your loop to:
for (int i=0;i<target_line;i++) {
for (int j=0;j<=i;j++) {
System.out.print("*");
}
System.out.println();
}
You print everytime one '*'-sign.
You don't necessarily need two loops. You can place the sign outside of the loop and you can add an asterisk every iteration with string.concat("*"). Concatenating actually means combining two strings into one, so you actually combine the sign from the previous iteration with a new sign.
int current_line = 0;
String input_line = showInputDialog("type here ");
int target_line = Integer.parseInt(input_line);
String sign = "*";
while (current_line != target_line){
sign.concat("*");
System.out.println(sign);
current_line ++;
}