How do I make this loop properly? it right now So it loops but it does not loop properly. It does this
Here are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 [1]
How many positions do you want to shift?: 2
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3 [3]
How many positions do you want to shift?: 4
the [] are where its suppose to ask me for my input instead of me just putting in a input
its suppose to run like this:
re are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
How many positions do you want to shift?: 1
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3
How many positions do you want to shift?: 4
System.out.println("Here are the numbers:");
for (i=0; i<numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
while (x != input.nextInt()){
System.out.printf("How many positions do you want to shift?: ");
int shiftTimes=input.nextInt();
for( i = 0; i < shiftTimes; ++i)
shift.Shifter(numberArray);
for(j = 0; j < numberArray.length; j++)
System.out.printf(numberArray[j]+" ");
}
}
}
Also How Do I make it exit the program when I enter in a invalid number and how do I get get it to read a negative value and get it to shift left
Edit: heres my shifter code
public static void Shifter(int[] list)
{
int i;
if (list.length < 2) return;
int last = list[list.length - 1];
for(i = list.length - 1; i > 0; i--) {
list[i] = list[i - 1];
}
list[0] = last;
}
This should work for right shift. It should work with inputs larger then array length as well.
for (int i = shiftTimes%numberArray.length; i > 0; i--) {
System.out.print(numberArray[numberArray.length - i] + " ");
}
for (int i = 0; i < numberArray.length - shiftTimes%numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
Reversing this logic should produce a left shift approach.
An invalid input would be the length of the array (because the result will be the same) or 0 because that doesn't do anything:
if (shiftTimes == numberArray.length || shiftTimes == 0) {
// present error to user
}
UPDATE: Putting the logic in your function. Also updated the invalid input check.
public static void Shifter(int[] list, int input)
{
for (int i = input%list.length; i > 0; i--) {
System.out.print(list[list.length - i] + " ");
}
for (int i = 0; i < list.length - input%list.length; i++) {
System.out.print(list[i] + " ");
}
}
The function call would be:
Shifter(numberArray, shiftTimes);
Related
I am supposed to create a program that prints out the following:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
Here's my current code:
int n = 1,
cols = 4,
rows = 4;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
System.out.print(n+" ");
n++;
}
System.out.println();
}
But the output is as below:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Can someone please help to figure out the solution for this one? I've tried many ways but just can't get the output right. Thanks anyway.
Java can only print in lines and not in columns. So the first line you need to print is:
1 5 9 13
In other words, every successive number is 4 greater than the number preceding it. So start your outer loop with the first number of the first row, i.e. 1 (one). Now each row contains 4 numbers, so your inner loop needs to iterate four times. See the below code:
int rows = 4;
int cols = 4;
for (int row = 1; row <= rows; row++) {
for (int col = 0; col < cols; col++) {
int number = row + (col * cols);
System.out.print(number + "\t");
}
System.out.println();
}
Running the above code produces the following:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
Change inner loop to go from 0 to cols-1 rather than 1 to cols, and make it print outer loop variable + (inner loop variable * 4).
This will surely work:
for(int row=1, num; row<=4; row++)
{
num = row;
for(int col=1; col<=4; col++, num+=4)
{
System.out.print(num + " ");
}
System.out.println();
}
So I've been working on this lab for a while now for my programming class and so far I think I'm on the right track.
However, I'm not quite sure how to mirror the numbers. So pretty much, my code is only printing the top half of the triangle. Anyway here is the actual assignment that was given to us:
Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with n rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console:
1
4 1
9 4 1
16 9 4 1
9 4 1
4 1
1
For full credit, each column should be 3 characters wide and the values should be right justified.
Now here is what I have written for my code so far:
import java.util.Scanner;
public class lab6 {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println(
"Enter a number that is between 1 and 9 (inclusive): ");
// this is the value that the user will enter for # of rows
int rows = kybd.nextInt();
for (int i = rows; i > 0; i--) {
for (int j = rows; j > 0; j--)
System.out.print((rows - j + 1) < i ?
" " : String.format("%3d", j * j));
System.out.println();
}
}
}
And this is what that code PRINTS when I enter 4:
Enter a number that is between 1 and 9 (inclusive):
4
1
4 1
9 4 1
16 9 4 1
As you can see, I can only get the TOP half of the triangle to print out. I've been playing around trying to figure out how to mirror it but I can't seem to figure it out. I've looked on this website for help, and all over the Internet but I can't seem to do it.
Answer is:
public static void main(String... args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows
for (int i = -rows + 1; i < rows; i++) {
for (int j = -rows; j < 0; j++)
System.out.print(abs(i) > j + rows ? " " : String.format("%3d", j * j));
System.out.println();
}
}
Try think of this as how to find points(carthesians) that are betwean three linear functions(area of triangle that lied betwean):
y = 0 // in loops i is y and j is x
y = x + 4
y = -x -4
And here is example result for 4:
And 9:
In the outer loop or stream you have to iterate from 1-n to n-1 (inclusive) and take absolute values for negative numbers. The rest is the same.
If n=6, then the triangle looks like this:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
25 16 9 4 1
16 9 4 1
9 4 1
4 1
1
Try it online!
int n = 6;
IntStream.rangeClosed(1 - n, n - 1)
.map(Math::abs)
.peek(i -> IntStream.iterate(n, j -> j > 0, j -> j - 1)
// prepare an element
.mapToObj(j -> i > n - j ? " " : String.format("%3d", j * j))
// print out an element
.forEach(System.out::print))
// start new line
.forEach(i -> System.out.println());
See also: Output an ASCII diamond shape using loops
Another alternative :
public static void main(String args[]) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows
int row = rows, increment = -1;
while (row <= rows){
for (int j = rows; j > 0; j--) {
System.out.print(rows - j + 1 < row ? " " : String.format("%3d", j * j));
}
System.out.println();
if(row == 1) {
increment = - increment;
}
row += increment;
}
}
The outer loop from 1-n to n-1 inclusive, and the inner decrementing loop from n to 0. The if condition is the absolute value of i should not be greater than n - j.
Try it online!
int n = 6;
for (int i = 1 - n; i <= n - 1; i++) {
for (int j = n; j > 0; j--)
if (Math.abs(i) > n - j)
System.out.print(" ");
else
System.out.printf("%3d", j * j);
System.out.println();
}
Output:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
25 16 9 4 1
16 9 4 1
9 4 1
4 1
1
See also: Invert incrementing triangle pattern
I want my output to be like this e.g. if the user inputs 3:
without using 2d array
1 2 3
1 1 2 3
2 1 4 6
3 3 6 9
My code so far
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
int[] cloumnarray = new int[i];
int[] rowarray = new int[i];
for (int z = 0; z <= i - 1; z++) {
cloumnarray[z] = z + 1;
rowarray[z] = z + 1;
}
for (int j = 0; j < i; j++) {
System.out.println(cloumnarray[j] * rowarray[j]);
}
}
I tried different options and can't get this to work properly.
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
// top corner, don't print nothing
if (a == 0 && b == 0) System.out.print("\t");
// top row 0-1, 0-2, 0-3 etc... just 1,2,3...
else if (a == 0) {
System.out.print(b + "\t");
// last line, print extra line break
if (b == i)
System.out.print("\n");
}
// first column 1-0, 2-0, 3-0... just a + space (tabulator)
else if (b == 0) System.out.print(a + "\t");
// any other cases, are candidates to multiply and give result
else System.out.print(a*b + "\t");
}
//look this is out of scope of nested loops, so,
// in each a iteration, print line break :)
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (3)
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
OUTPUT (5)
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
But problem (for me) is the numbers are not padded in the natural order, so, to achieve your goal, exactly as in your demo, will need a bit of padding like this
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
if (a == 0 && b == 0) System.out.print("\t");
else if (a == 0) {
System.out.print(String.format("%3s", b));
if (b == i)
System.out.print("\n");
}
else if (b == 0) System.out.print(a + "\t");
else System.out.print(String.format("%3s", a*b));
}
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (7)
1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 4 6 8 10 12 14
3 3 6 9 12 15 18 21
4 4 8 12 16 20 24 28
5 5 10 15 20 25 30 35
6 6 12 18 24 30 36 42
7 7 14 21 28 35 42 49
What looks quite good :)
So this should be pretty simple.
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a < i; a++) {
for (int b = 0; b < i; b++) {
System.out.print(a*b + "\t");
}
System.out.print("\n");
}
}
Whenever you're working with a matrix involving two arrays (especially if you're trying to a solve a problem that deals with patterns), you want to have a nested for loop like so:
for(int row = 0; row < numSelected; row++) {
for(int col = 0; col < numSelected; col++) {
...
}
}
That way, each cell in the matrix will be covered. Now using that, you can try multiplying the row index and the col index and storing that to the correct cell.
I need my matrices to look exactly like this.
Here are the two matrices, and the result when added:
2 2 7 4 3 4 3 3 5 6 10 7
4 4 8 8 6 8 5 5 10 12 13 13
1 9 3 7 6 8 6 9 7 17 9 16
2 3 2 9 + 4 4 7 1 = 6 7 9 10
2 9 1 1 9 8 2 5 11 17 3 6
6 1 8 4 4 8 2 2 10 9 10 6
Each number should use 4 positions in the output, and the + and = should be in the middle row, but I can not get the + and = signs to stay for smaller arrays. My problem may be with my if (i == 3 && j == 3) statements.
My code for this part is as follows.
public static void printResult(int [][]array1, int [][]array2, int[][]sum, char arithmetic)
{
// Declares 2-dimensional array the same size as one in parameters
int [][]arraySum = new int [array1.length][array1[0].length];
// Arithmetic characters to be printed when asked for
String add = "+";
String subtract = "-";
String multiply = "*";
String divide = "/";
String remainder = "%";
String equals = "=";
// If arithmetic is addition to print matrices and add them to show result
if (arithmetic == '+') {
// Text for two matrices when added
System.out.print("Here are the two matrices, and the result when added:\n");
// For loop to print array1 + array2 = sum with format
for (int i = 0; i < arraySum.length; i++) {
// For loop to print out array 1 and add string
for (int j = 0; j < arraySum[i].length; j++) {
System.out.printf("%3s", array1[i][j] + " ");
if (i == 3 && j == 3) {
System.out.printf("%2s", add);
}
}
System.out.print("\t");
// For loop to print out array2 and equals string
for (int k = 0; k < arraySum[i].length; k++) {
System.out.printf("%3s", array2[i][k] + " ");
if (i == 3 && k == 3) {
System.out.printf("%2s", equals);
}
}
System.out.print("\t");
// For loop to print out sum of array1 + array2
for (int l = 0; l < arraySum[i].length; l++) {
System.out.printf("%3s", sum[i][l] + " ");
}
System.out.print("\n");
}
}
else if (arithmetic == '-') {
}
else if (arithmetic == '*') {
}
else if (arithmetic == '/') {
}
else if (arithmetic == '%') {
}
}
Example of what I get for 3x3 arrays. (should still print + or =).
5 3 5 6 7 4 11 10 9
8 2 9 1 5 5 9 7 14
9 7 3 2 5 1 11 12 4
Try if (i == arraySum.length/2 && j == arraySum[i].length-1).
i and j are never 3 if your matrix is 3x3. If you want + and = in the middle then write something like this:
if (i == arraySum.length / 2 && j == arraySum[i].length - 1)
Replace if (i == 3 && j == 3) { with if (i == (array1 / 2) && j == (array1 / 2)) {
Your problem is that in the for loop, you are adding the addition sign and the equals sign in the 4th row (0,1,2,3). When you only have three rows, it won't print. What you can do to make it in the middle is something like this:
for (int i = 0; i < arraySum.length; i++) {
// For loop to print out array 1 and add string
for (int j = 0; j < arraySum[i].length + 1; j++) {
System.out.printf("%3s", array1[i][j] + " ");
if (i == Math.ceil(arraySum.length/2) && j == arraySum.length) {
System.out.printf("%2s", add);
}
}
It will print the sign in the middle (height) and at the end (lengthwise) of the array. Just to be careful, it also uses the ceiling function to round up to the next integer.
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
I need to make this pyramid using nested for loops,
so far all I have figured out is that I need three for loops.
I know how for loops work and have a pretty good grasp on the fundamentals of java, but I have no earthly idea on how this works.
Just wrote this without debug but it should produce this pyramid:
0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
int pyramidHeight = 4;
for(int i = 0; i < pyramidHeight;i++){
for(int j = 1; j < pyramidHeight*2;j++){
if( j < pyramidHeight - i || j > pyramidHeight + i ){
System.out.print(" ");
}
else{
System.out.print(i - Math.abs(pyramidHeight - j));
}
System.out.print(" ");
}
System.out.println();
}
With two simple changes you should get your pyramid.
This should work! Note that you have each row counting total 2*i+1 elements where i is your current row number.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int lim = 5;
int spaceLim = lim*2;
for (int i=0; i < lim; i++){ // Number of rows is the key here (pow 2)
String s = "%" + spaceLim + "s";
System.out.printf(s, "");
if (i == 0){
System.out.print(1);
}
else{
for (int j=0; j<i; j++) {
System.out.printf("%1.0f ",(Math.pow(2.0, (double)(j))));
}
for (int j=i; j>=0; j--){
System.out.printf("%1.0f ", (Math.pow(2.0, (double)(j))));
}
}
System.out.println();
spaceLim -= 2;
}
}
}
The demo of working solution is here - http://ideone.com/J2fcQw