I'm writing this program with numbers, but I am stuck and need some help.
Code so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Oppgi øvre grense: ");
int Number = in.nextInt();
int tall = 1;
for(int t = 0; tall <=45; tall++){
System.out.println(" " + tall);
}
}
The objective: to get the first line to contain one number, the second to contain two numbers, third line contain three numbers, etc.
The output should look like a pyramid, with different spacing between the numbers on each line.
If anybody can help me with the solution code. Thank you.
Oppgi øvre grense: 45
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
outer loop{
decides number of numbers in one line
inner loop{
prints actual numbers.
Please keep track of the numbers you have printed so far
Inner loop starts at numbers printed so far
It will have passes = number of numbers to print
}
}
You have two distinct tasks here:
1. Decide how many numbers to print in one line
2. Actually print the numbers
Since that is the case, one loop decides how many numbers to print: the outer loop. The Reason it is outer loop is because you need to have a clear picture of how many numbers you need to print before you actually print.
The other loop: inner loop does the actual printing.
So, once you start with the outer loop, your inner loop will begin printing.
It will then see if it has printed the maximum number of numbers for that pass.
If yes, stop. Then, you increment the outer loop. Come back in, print, check and then do the same.
Easy enough ?
public class RareMile {
public static void main (String[] args){
printNum(5);
}
public static void printNum (int n){
int k=1, sum=0;
for (int i=1; i<=n; i++){
sum=0;
for(int j=1; j<=i; j++){
System.out.print(k);
sum = sum+k;
k++;
}
System.out.print(" =" + sum);
System.out.println();
}
}
}
The real question is that how to do it with only one for loop?
Keep track of the line number
e.g.
int line = 1; // line number
int count = 0; // number of numbers on the line
for(int x = 0; x <= 45; x++){
if (count == line){
System.out.println(""); // move to a new line
count = 0; // set count back to 0
line++; // increment the line number by 1
}
System.out.print(x); // keep on printing on the same line
System.out.print(" "); // add a space after you printed your number
count++;
}
Related
I have an assignment where I would have to print a 2d array (8 rows and 7 columns) that resembles a seating chart with an aisle going down the middle that cannot have any seats (these elements would be left blank). The chart would have to have a number for each seat, and continue in ascending order (as seen below).
1 2 3 x 4 5 6
7 8 9 x 10 11 12
13 14 15 x 16 17 18
19 20 21 x 22 23 24
The program would continue until there would be 48 total seats.
I have to print the array with for loops (which I have no problem doing), but I do not know how to make a blank column (the column with xs), or how to make each number increase as you progress through the cells.
Right now, I have only the for loops that would print out the array.
I think what you need there is a nested loop. Your code should look like this:
public static void main(String []args){
print_2d_array(8, 7);
}
public static void print_2d_array(int rows, int columns) {
int x = rows/2;
int y = columns - 1;
for(int i = 0; i < x; i++) { // number of rows
for(int j = 0; j < y; j++) { // number of columns
System.out.print((j + y*i + 1) + " "); // That's the formula I was talking about
if(j == (y/2)-1) System.out.print("x ");
}
System.out.println();
}
}
In this problem the user has to input the starting number and the size of the triangle.if starting number is 5 and size of the triangle is 6 the output must be like this.
5
19 6
18 20 7
17 25 21 8
16 24 23 22 9
15 14 13 12 11 10
I have already tried this problem and their is a error with my code. Can someone help me to find the error with this.
public class MyClass {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//first number
int n=in.nextInt();
//size of the triangle
int k=in.nextInt();
int [][]arr=new int[k][k];
int sizec=k,sizer=k,rstart=0,cstart=0,rend=k-2,cend=k-2,p=0;
while(sizer>1&&sizec>1){
int g=cstart;
for(int i=rstart;i<sizer;i++){
arr[g][i]=n;
n++;
g++;
}
for(int i=rend;i>=rstart;i--){
arr[cend+1][i]=n;
n++;
}
for(int i=cend;i>cstart;i--){
arr[i][rstart]=n;
n++;
}
rstart++;
cstart+=2;
rend-=2;
sizec-=2;
sizer-=2;
}
for(int j=0;j<k;j++){
for(int h=0;h<j+1;h++){
System.out.print(arr[j][h]+" ");
}
System.out.println();
}
}
}
You forgot a
cend--;
Put it there:
sizer-=2;
cend--;
}
I would also recommend that you change your variable names into words so that it is possible for other people to read your code. For example, cend could be "columnEnd".
Currently, I am doing an assignment on displaying all odd numbers up to a user inputted specific odd number. The requirement is to include the input number, however, I don't understand why does the code always goes to the next Odd number compared to what user inputted. Please help.
import java.util.Scanner;
public class OddNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pls enter an odd number you want to finish to: ");
int capp_number = input.nextInt();
int startingNumber = 1;
for(int i = 0; i < capp_number; i+= 2){
startingNumber += 2;
System.out.println(startingNumber);
}
This is because i starts at 0 (It is even), and you are checking to see if it is less than capp_number (which should be odd), and then adding two to i. startingNumber starts at 1, so it is odd. So if the user enters 5 it will go like:
Iteration 1:
i (0) < 5 ? Yes:
print startingNumber+2
output: 3
i == 2
Iteration 2:
i (2) < 5 ? Yes:
print startingNumber +2
output: 5
i == 4
Iteration 3:
i (4) < 5 ? Yes:
print startingNumber +2
output: 7
i == 6
Iteration 4
i (6) < 5 No:
end loop
To fix this, start i at one:
for(int i = 1; i < capp_number; i+= 2)
Sorry, but why did you write this ?
while(startingNumber < capp_number);
i agree with a previous answer and think that there is no reason for this line. And also you should correct your loop as it was also mentioned in previous answer:for(int i = 0; i < capp_number; i+= 2)
Try this. You needed to initialise i to 1 within the for-loop. 1 is an odd number so instead of starting with an even number (0), you look for every odd number.
For example, if you start at 1: 1+2=3, 3+2=5, 5+2=7.... and so on.
For example, if you start at 0: 0+2=2, 2+2=4, 4+2=6.... and so on.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pls enter an odd number you want to finish to: ");
int capp_number = input.nextInt();
int startingNumber = 1;
for(int i = 1; i < capp_number; i += 2){
startingNumber += 2;
System.out.println(startingNumber);
}
This Java program is for finding the data from a txt file that consists a number of integers. I have figured out the codes for the maximum, average to run the program. For a lot of you it should be simple but I am relatively in-experienced in programming so bear with me.
There are three codes that I am having trouble are as follows.
number of numbers above average
number of prime numbers
finding the total sum
Does anyone know a way to do this?
Thanks. Any advice helps.
Here is the txt file sample of 20 numbers
1
12
34
54
36
76
67
86
45
44
33
22
2
4
7
87
89
99
432
543
List item
package Assignment1;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Define two arrays - local variables
// Declaring 10 integers
int[] myIntArray = new int[20];
// Declaring 10 strings
//File
File f = new File ("inputassignment1.txt");
try {
Scanner sc = new Scanner(f); //Scanner
for (int i=0; i < myIntArray.length; i++) {
myIntArray[i] = sc.nextInt();
}
// Closing the file
sc.close();
} catch (IOException e) {
System.out.println("Unable to create : "+e.getMessage());
}
System.out.println("Highest number: " + maxNum(myIntArray));
System.out.println("Average number: "+aveNum(myIntArray));
// System.out.println(allNum(myIntArray));
// System.out.println(avgPlus(myIntArray));
}// end of main
Let's break your task down:
There are 3 overall tasks:
Count how many numbers are above average
Find the total sum
Find all the prime numbers
Each of these requires you to:
Read in numbers from a text file (into an array probably)
Perform some checks on them (e.g. if isPrime(number) { primes[numPrimes] = number; numPrimes++; })
Count how many there are (numNumbers++, for each number)
Sum them up (totalSum += number, for each number)
For the first one you will need to add another loop after you have the count/sum, the the other two should be doable by modifying the first loop (I have shown an example below).
I think you should be able to google for how to do each of those. Your code above looks like a good starting point.
int numNumbers = 0;
int totalSum = 0;
for (int i=0; i < myIntArray.length; i++) {
myIntArray[i] = sc.nextInt();
numNumbers++;
totalSum += myIntArray[i];
}
I'm supposed to write a program that asks for the number of rows the user wants. For example is the user entered 5 it will display all numbers from 25 to 1 arranged in 5 columns and 5 rows. Something like this should be the output if 5 is entered:
25 24 23 22 21
16 17 18 19 20
15 14 13 12 11
6 7 8 9 10
5 4 3 2 1
As you can see there is a pattern. the first number to appear is the square of the number. then the next number is number squared minus 1. Until it reached 21, 5 will be subtracted bringing 16. Then it will add by 1 until it reach 20. As you can see it is like a snake.
The problem is it works for any number EXCEPT when 1 is entered. 0 is the current result when 1 is entered.
Here's my current codes: please help me thanks
import java.util.*;
public class ArrayOutput2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number = 0;
System.out.print("Enter number of rows: ");
number = input.nextInt();
int[][] num = new int[number][number];
int k=1, i, j;
while(k< (number*number))
{
for(i=number; i>=1; i--)
{
if (i%2==1)
{
for(j=number-1; j>=0; j--)
{
num[i-1][j]=k;
k++;
}
}
else
for(j=0; j<=number-1; j++)
{
num[i-1][j]=k;
k++;
}
}
}
for(i=0;i<number;i++)
{
for(j=0;j<number;j++)
System.out.print(num[i][j]+"\t");
System.out.println();
}
}
}
Suppose that the user inputs 1 as a value, therefore number == 1.
You allocate an array num[1][1], that is an array with only one possible cell, number[0][0]
Then the loop is initiated
k=1;
while (k<(number*number)); // which is like while(1<1*1)==FALSE
therefore the loop is never used. You can use:
1) Either a do-while loop to run the loop at least once
2) or add an if statement just after while() loop ends:
// Using an IF statement immediately after the unmodified while()
if (number==1)
{
num[0][0]=1;
}
// or with a loop DO-WHILE
do
{
for(i=number; i>=1; i--)
{
if (i%2==1)
{
for(j=number-1; j>=0; j--)
{
num[i-1][j]=k;
k++;
}
}
else
for(j=0; j<=number-1; j++)
{
num[i-1][j]=k;
k++;
}
}
}while(k<(number*number));
when number = 1, the 2D array int[][] num does not get populated as it does not enter the loop while(k<(1*1)), hence bottom for loop which prints the 2D values prints only 0 because array itself does not get initialized.
num[0][0] has not been initialized since you didn't enter the loop. Try this before the loop:
if (number == 1)
num[0][0] = 1;
if(number == 1 ) {
System.out.println("1");
return;
}