I have a question about the third for loop, how does it work please ?
public void outputBarChart()
{
System.out.println("Grade Distribution: \n");
int frequency[] = new int[11];
for(int oneGrade : grade)
{
++frequency[oneGrade / 10];
}
for (int count = 0; count < frequency.length; count++)
{
if (count == 10) {
System.out.println("100");
}
else {
System.out.printf("%02d-%02d: ",
count*10, count*10 + 9);
}
//the third for loop here !
for (int star = 0; star < frequency[count]; star++){
System.out.print("*");
}
System.out.println();
}
}
The problem is I don't know the mechanics how it print out stars.
Well lets go through the code then:
The second for loop which contains the third for-loop will loop 11 times since thats the length of frequencey. Okay that was easy.
Now the third for-loop iterates frequency[count] times, we don't know this value, but we know that it is an integer. So what third loop will do is simply to print out a star frequency[count] times. After that we're done with the third loop and a newline is printed by the second loop.
System.out.println("*" * frequency[count]);
The loop will take the variable star and loop and increment until it reaches the value of frequency[count]. So it will run the loop the same number of times as the value stored in frequency[count].
Each loop iteration it prints a star. At the end it prints a blank line.
The result is printing the number of stars as frequency[count] on a line.
Related
I have this task to display a pyramid as follows:
I wrote the code but unfortunately, the digits are displayed with spaces and order.
public class DisplayPyramid {
//main method declaration. Program entry point which begins its execution
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Prompt the user to enter an integer (number of lines)
System.out.print("Enter the number of lines: ");
int numbers = input.nextInt(); //Read value from keyboard and assign it to numberOfLines
String padding = " ";
//Display pyramid
//for loop to produce each row
for (int rows = 0; rows < numbers ; rows++) {
for (int k = numbers - rows; k >= 1; k--){
System.out.print(k + " ");
}
for (int l = 2; l <= numbers - rows; l++){
System.out.print(" " + l);
}
//Advance to the next line at the end of each rows
System.out.print("\n");
}
} }
And this is my output:
Can you help me figure out what is wrong with code ?
Anyone's help will be much appreciated.
Consider the 1st pass of the outer loop which produces
If we color hint your code, which the first inner loop in red, the second inner loop in green
This will be their corresponding output for each pass
The last pass of the red loop print "1 " and the first pass of green loop print " 2". They combine and become "1 2", which has 2 spaces in between.
The solution as Osama A.R point out, just reverse the printing order of number and space for the green loop and make if follow the red loop pattern. That will make the sequence neat.
Your second for loop prints the spaces first and then the number, however, the spaces have already been added by the first for loop, so just update the second for loop to print the spaces after printing the number.
E.g. your second loop should be like this:
for (int l = 2; l <= numbers - rows; l++){
System.out.print(l + " ");
}
//programme of insertion sort i am checking how many times the value is printing
//when i enter the 2 and 1 the value of i is printing 3 times but it should have to print 1 times when i enter 2 value
public class Insertionsort {
static void insertsort(int arr[]){
for(int i=1;i<arr.length;i++) {
for(int j=i-1;j>=0;) {
System.out.println("i is"+i);
if(arr[j]>arr[i] ) {
int temp=arr[j]; //for swapping
arr[j]=arr[i];
arr[i]=temp;
i--;
}else {
j--;
}
}
}
for(int i=0;i<2;i++) {
System.out.println(arr[i]);
}
}
public static void main(String args[]) {
int arr[]=new int[2];
System.out.println("please Enter the value");
Scanner sc= new Scanner(System.in);
for(int i=0;i<2;i++) {
arr[i]=sc.nextInt();
}
insertsort( arr);
}
}
Output
please Enter the value
2
1
i is1
i is0
i is1
1
2
The println should be before the inner loop.
for(int i=1;i<arr.length;i++) {
System.out.println("i is"+i);
for(int j=i-1;j>=0;) {
You only want the value of i to be printed once each time i is updated. If you put it in the inner loop, then each value of i will be printed multiple times since the inner loop can iterate multiple times for each value of i.
For value 2,1 it's printing 3 times, because
for i = 1, j= 0 it prints 1 times then goes inside if condition and makes value of i=0 and no change in value of j and now the value is 1 2 of the array as it is swap.
Again it check condition for j>=0 which satisfies the for loop condition, it enter print 2nd times but this time it goes to else condition decreasing the value of j making it equal to j=-1, checks the condition and loop exit from inner loop.
At this point we have value of i =0, now it goes to outside loop increases value of i, i.e. makes value of i = 1, checks condition and then goes inside inside inner loop, with j= 0,check condition and then print 3rd times goes to else condition decreasing the value of j, breaking inner loop and then outer loop.
Try doing dry run or using debugger it will help!
I am yet again stuck at the answer. This program prints the unique values but I am unable to get the sum of those unique values right. Any help is appreciated
public static void main(String args[]){
int sum = 0;
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for (int x : numbers) {
setUniqueNumbers.add(x);
}
for (Integer x : setUniqueNumbers) {
System.out.println(x);
for (int i=0; i<=x; i++){
sum += i;
}
}
System.out.println(sum);
}
This is a great example for making use of the Java 8 language additions:
int sum = Arrays.stream(numbers).distinct().collect(Collectors.summingInt(Integer::intValue));
This line would replace everything in your code starting at the Set declaration until the last line before the System.out.println.
There's no need for this loop
for (int i=0; i<=x; i++){
sum += i;
}
Because you're adding i rather than the actual integers in the set. What's happening here is that you're adding all the numbers from 0 to x to sum. So for 23, you're not increasing sum by 23, instead, you're adding 1+2+3+4+5+....+23 to sum. All you need to do is add x, so the above loop can be omitted and replaced with a simple line of adding x to sum,
sum += x;
This kind of error always occures if one pokes around in low level loops etc.
Best is, to get rid of low level code and use Java 8 APIs:
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sum = Arrays.stream(numbers)
.distinct()
.mapToInt(Integer::intValue)
.sum();
In this way there is barely any space for mistakes.
If you have an int array, the code is even shorter:
int[] intnumbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sumofints = Arrays.stream(intnumbers)
.distinct()
.sum();
So this is my first time commenting anywhere and I just really wanted to share my way of printing out only the unique values in an array without the need of any utilities.
//The following program seeks to process an array to remove all duplicate integers.
//The method prints the array before and after removing any duplicates
public class NoDups
{
//we use a void static void method as I wanted to print out the array without any duplicates. Doing it like this negates the need for any additional code after calling the method
static void printNoDups(int array[])
{ //Below prints out the array before any processing takes place
System.out.println("The array before any processing took place is: ");
System.out.print("{");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
if (i != array.length - 1)
System.out.print(", ");
}
System.out.print("}");
System.out.println("");
//the if and if else statements below checks if the array contains more than 1 value as there can be no duplicates if this is the case
if (array.length==0)
System.out.println("That array has a length of 0.");
else if (array.length==1)
System.out.println("That array only has one value: " + array[0]);
else //This is where the fun begins
{
System.out.println("Processed Array is: ");
System.out.print( "{" + array[0]);//we print out the first value as it will always be printed (no duplicates has occured before it)
for (int i = 1; i < array.length; i++) //This parent for loop increments once the all the checks below are run
{
int check = 0;//this variable tracks the amount of times an value has appeared
for(int h = 0; h < i; h++) //This loop checks the current value for array[i] against all values before it
{
if (array[i] == array[h])
{
++check; //if any values match during this loop, the check value increments
}
}
if (check != 1) //only duplicates can result in a check value other than 1
{
System.out.print(", " + array[i]);
}
}
}
System.out.print("}"); //formatting
System.out.println("");
}
public static void main(String[] args)
{ //I really wanted to be able to request an input from the user but so that they could just copy and paste the whole array in as an input.
//I'm sure this can be done by splitting the input on "," or " " and then using a for loop to add them to the array but I dont want to spend too much time on this as there are still many tasks to get through!
//Will come back and revisit to add this if I remember.
int inpArray[] = {20,100,10,80,70,1,0,-1,2,10,15,300,7,6,2,18,19,21,9,0}; //This is just a test array
printNoDups(inpArray);
}
}
the bug is on the line
sum += i;
it should be
sum += x;
I'm writing a for-loop for an assignment in school. The loop will write the min number, ex. 26 and will increase with 7 every turn in the loop until it reaches max, ex. 112.
Between every number, the will also be written a comma - ",". But not after the last number.
Right now my code looks like this:
int min=26;
int max=112;
for(int i=min; i<=max; i+=7)
{
if(i!=max)
{
System.out.print(i+", ");
}
else
{
System.out.print(i);
}
}
Right now the last number will have a comma... Where's my problem?
Others have explained that i may not ever be equal to max. For a case like this, it's easier to wait until the next loop iteration to print the comma:
for(int i=min; i<=max; i+=7)
{
if(i!=min)
{
System.out.print(", "+i);
}
else
{
System.out.print(i);
}
}
(Often I'll set up a separate boolean named first to see if I'm going through the first iteration; it's set to true before the loop and false at the end of the loop.)
P.S. There are other ways to solve the problem, such as changing the i==max condition or computing the actual maximum. However, the above approach can be applied in lots of cases that don't have anything to do with stepping by a fixed amount, and where it might not be as easy to figure out ahead of time when the loop will stop.
It never enters else loop, because in your code max = 112, but your for loop won't reach that value. (It reaches 110 after increments of 7). So it will only execute the `if' loop and print the strings with comma, and then exit.
Since 'i' will never be equal to 'max', the else clause is not executed.
If 'min' is always less than 'max', then you can also do:
int min=26;
int max=112;
System.out.print(min);
for(int i=min+7; i<=max; i+=7)
{
System.out.print("," + i);
}
After 12 loops: 26+7*12 = 110. It will exit the loop and the second condition will never be met.
int min=26;
int max=112;
for(int i=min; i<=max; i+=7) {
if(i <= max-7)
System.out.print(i+", ");
else
System.out.print(i);
}
Chances are that in the last iteration of the loop, i is not equal to max, given that your increment step y 7. Actually, your loop runs from 26 to 112, that's 86 which is not multiple of 7.
You should be fine if you calculate your max value based on min and step, something like.-
int step = 7;
int min = 26;
int max = min * step;
for(int i = min; i <= max; i += step)
Your max value is 112 and your min value is 26. You're incrementing 7 at each iteration. If you subtract 26 from 112, you will see that the result is not multiple of 7, which means your loop is not stopping when i is exactly 112. Rather, your loop ends before i reaches value 112. That's why you see a comma in the end of the printed string.
I have to write a java program where the solution will include the printing of the arrow tip figure depending on the number of rows. Below are example of how the result should look. However, I cannot do this until I understand for loops. I know I have to work with the rows and columns and possibly nested loops. I just dont know how to connect the row with the columns using for loops. Please help me in understanding these loops. Thanks!
Example #1 (odd number of rows)
>
>>>
>>>>>
>>>>>>>
>>>>>
>>>
>
Example #2 (even number of rows)
>
>>>
>>>>>
>>>>>>>
>>>>>>>>>
>>>>>>>>>>>
>>>>>>>>>>>
>>>>>>>>>
>>>>>>>
>>>>>
>>>
>
a for loop will loop through a collection of data, such as an array. The classic for loop looks like this:
for(counter=0;counter <= iterations;counter++){ }
the first param is a counter variable. the second param expresses how long the loop should last, and the 3rd param expresses how much the counter should be incremented by after each pass.
if we want to loop from 1 - 10, we do the following:
for(counter=1;counter<=10;counter++){ System.out.println(counter); }
if we want to loop from 10 - 1, we do the following:
for(counter=10;counter>=1;counter--){ System.out.println(counter); }
if we want to loop through a 2 dimensional collection, like...
1 2 3
4 5 6
7 8 9
int[][] grid = new int[][] {{1,2,3},{4,5,6},{7,8,9}};
we need 2 loops. The outer loop will run through all the rows, and the inner loop will run through all the columns.
you are going to need 2 loops, one to iterate through the rows, one to iterate through the columns.
for(i=0;i<grid.length;i++){
//this will loop through all rows...
for(j=0;j<grid[i].length;j++){
//will go through all the columns in the first row, then all the cols in the 2nd row,etc
System.out.println('row ' + i + '-' + 'column' + j + ':' + grid[i][j]);
}
}
In the outer loop, we set a counter to 0 for the first parameter. for the second, to calculate how many times we will loop, we use the length of the array, which will be 3, and for the third param, we increment by one. we can use the counter, i, to reference where we are inside the loop.
We then determine the length of the specific row by using grid[i].length. This will calculate the length of each row as they are being looped through.
Please feel free to ask any questions you may have regarding for loops!
EDIT: understanding the question.....
You are going to have to do several things with your code. Here we will store the number of lines in a variable, speak up if you need to pass in this value to a method.
int lines = 10; //the number of lines
String carat = ">";
for(i=1;i<=lines;i++){
System.out.println(carat + "\n"); // last part for a newline
carat = carat + ">>";
}
The above will print out carats going all the way up. We print out the carat variable then we make the carat variable 2 carats longer.
.... the next thing to do is to implement something that will decide when to decrease the carats, or we can go up half of them and down the other half.
Edit 3:
Class Test {
public static void main(String[] args) {
int lines = 7;
int half = lines/2;
boolean even = false;
String carat = ">";
int i;
if(lines%2==0){even = true;} //if it is an even number, remainder will be 0
for(i=1;i<=lines;i++){
System.out.println(carat + "\n");
if(i==half && even){System.out.println(carat+"\n");} // print the line again if this is the middle number and the number of lines is even
if(((i>=half && even) || (i>=half+1)) && i!=lines){ // in english : if the number is even and equal to or over halfway, or if it is one more than halfway (for odd lined output), and this is not the last time through the loop, then lop 2 characters off the end of the string
carat = carat.substring(0,carat.length()-2);
}else{
carat = carat + ">>"; //otherwise, going up
}
}
}
}
Explanation and commentary along shortly. Apologies if this is over complicated (i'm pretty sure this is not even close to the best way to solve this problem).
Thinking about the problem, we have a hump that appears halfway for even numbers, and halfway rounded up for the odd numbers.
At the hump, if it is even, we have to repeat the string.
We have to then start taking off "<<" each time, since we are going down.
Please ask if you have questions.
I had the same question for a homework assignment and eventually came to a correct answer using a lot of nested if loops through a single for loop.
There is a lot of commenting throughout the code that you can follow along to explain the logic.
class ArrowTip {
public void printFigure(int n) { //The user will be asked to pass an integer that will determine the length of the ArrowTip
int half = n/2; //This integer will determine when the loop will "decrement" or "increment" the carats to String str to create the ArrowTip
String str = ">"; //The String to be printed that will ultimately create the ArrowTip
int endInd; //This integer will be used to create the new String str by creating an Ending Index(endInd) that will be subtracted by 2, deleting the 2 carats we will being adding in the top half of the ArrowTip
for(int i = 1; i <= n; i++) { //Print this length (rows)
System.out.print(str + "\n"); //The first carat to be printed, then any following carats.
if (n%2==0) { //If n is even, then these loops will continue to loop as long as i is less than n.
if(i <= half) { //This is for the top half of the ArrowTip. It will continue to add carats to the first carat
str = str + ">>"; //It will continue to add two carats to the string until i is greater than n.
}
endInd = str.length()-2; //To keep track of the End Index to create the substring that we want to create. Ultimately will determine how long the bottom of the ArrowTip to decrement and whether the next if statement will be called.
if((endInd >= 0) && (i >= half)){ //Now, decrement the str while j is greater than half
str = str.substring(0, endInd); //A new string will be created once i is greater than half. this method creates the bottom half of the ArrowTip
}
}
else { //If integer n is odd, this else statement will be called.
if(i < half+1) { //Since half is a double and the integer type takes the assumption of the one value, ignoring the decimal values, we need to make sure that the ArrowTip will stick to the figure we want by adding one. 3.5 -> 3 and we want 4 -> 3+1 = 4
str = str + ">>"; //So long as we are still in the top half of the ArrowTip, we will continue to add two carats to the String str that will later be printed.
}
endInd = str.length()-2; //Serves the same purpose as the above if-loop when n is even.
if((endInd >= 0) && (i > half)) { //This will create the bottom half of the ArrowTip by decrementing the carats.
str = str.substring(0, endInd); //This will be the new string that will be printed for the bottom half of the ArrowTip, which is being decremented by two carats each time.
}
}
}
}
}
Again, this was for a homework assignment. Happy coding.
Here is a simple answer for you hope it helps! Cheers Logan.
public class Loop {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int count = i;
int j = 0;
while (j != count) {
System.out.print(">");
j++;
}
System.out.println();
}
for (int i = 10; i > 0; i--) {
int count = i;
int j = 0;
while (j != count) {
System.out.print(">");
j++;
}
System.out.println();
}
}
}
For making a 'for' loop:
public class Int {
public static void main(String[] args) {
for (Long num = 1000000L; num >= 9; num++) {
System.out.print("Number: " + num + " ");
}
}
}
Output:
Number: 1008304 Number: 1008305 Number: 1008306 Number: 1008307 ...