I'm new at java and I have to write a code for a multiplication table. I have the multiplication working for a square table but I need it to work for a reverse triangle. What do I need to add to the code to make it print like this following examples?
/*What I have:
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
What I want:
1 2 3 4
4 6 8
9 12
16
*/
import java.util.Scanner;
public class question3{
public static void main(String[] args){
System.out.print("Enter an integer between 1 and 10: ");
Scanner input = new Scanner(System.in);
int value = input.nextInt();
if(value < 0 || value > 10){
while(value < 0 || value > 10){
System.out.print("Enter an integer between 1 and 10: ");
value = input.nextInt();
if(value <= 10){
for(int x=1; x <= value; x++){
System.out.println();
for(int y=1; y<= value; y++){
int z=x*y;
System.out.printf(z + "\t");
}
}
}
}
}
else if (value <=10 && value >=0){
for(int x=1; x <= value; x++){
System.out.println();
for(int y=1; y<= value; y++){
int z=x*y;
System.out.printf(z + "\t");
}
}
}
System.out.println();
}
}
from the given information i assume that you want to make a table which display values
/* 1 2 3 4
4 6 8
9 12
16 */
here is the simple code which i have written , it also display the same table which you want.
int row,column ;
column = row = 4;
String space = " ";
for(int i=0;i<row;++i)
{
for(int x=0;x<2*i;++x )
{
System.out.print(space);
}
for(int y=1; y<=column; ++y)
{
System.out.print(space);
System.out.print((y+i)*(i+1));
}
column = column -1;
System.out.println();
}
Related
Trying to figure out how to print a multiplication table.
The code I have right now is:
Scanner scan= new Scanner(System.in);
System.out.print("Please enter number 1-10:");
int n=scan.nextInt();
if(n<=10)
{
for(int m= 1;m<=n;m++)
{
for(int o= 1;o<=n;o++)
{
System.out.print(m*o+"\t");
}
System.out.println();
}
}
else
System.out.print("INVALID");
It prints out :
I'm trying to get it to print out as :
Please read the comments marked with // CHANGE HERE.
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter number 1-10: ");
int n = scan.nextInt();
// CHANGE HERE - strict checking
if (n >= 1 && n <= 10)
{
// CHANGE HERE - added to print the first (header) row
for (int m = 0; m <= n; m++)
{
if (m == 0)
System.out.print("\t");
else
System.out.print(m + "\t");
}
System.out.println();
for (int m = 1; m <= n; m++)
{
// CHANGE HERE - added to print the first column
System.out.print(m + "\t");
for (int o = 1; o <= n; o++)
{
System.out.print(m * o + "\t");
}
System.out.println();
}
}
else
System.out.println("INVALID");
}
}
Try this.
Scanner scan = new Scanner(System.in);
System.out.print("Please enter number 1-10:");
int n = scan.nextInt();
if (n <= 10) {
for (int i = 1; i <= n; ++i)
System.out.print("\t" + i);
System.out.println();
for (int m = 1; m <= n; m++) {
System.out.print(m);
for (int o = 1; o <= n; o++) {
System.out.print("\t" + m * o);
}
System.out.println();
}
} else
System.out.print("INVALID");
output:
Please enter number 1-10: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
I have been trying to find a way to print an inverted pyramid that has a certain number sequence. The sequence needed is as follows as well as what I currently have.
The prompt asked to write a method that takes two numbers and create an inverted pyramid with the first row having a length of the first integer and starting with the number entered second. Then only have the sequence start at 1 after 9 is reached.
Needed: Currently Have:
1 2 4 7 2 7 4 1 2 3 4 5 6 7
3 5 8 3 8 5 8 9 1 2 3 4
6 9 4 9 6 5 6 7 8 9
1 5 1 7 1 2 3 4
6 2 8 5 6 7
3 9 8 9
1 1
static int plotTriangle(int a, int b){
int num = b;
for (int row = a; row >= 0; row--){
for (int i = a; i - row >= 0; i--){
System.out.print(" ");
num += (num+a-row);
num -= 2;
}
for (int i = 0; i <= row; i++){
num++;
while (num >= 10){
num -= 9;
}
System.out.print(num + " ");
}
System.out.println();
}
return 0;
}
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter length: ");
int l = in.nextInt();
System.out.print("Enter Start: ");
int s = in.nextInt();
int triangle = plotTriangle(l, s);
}
Try this:
public static void main(String[] args) {
int length = 7;
int[][] numbers = new int[length][length];
int count = 1;
for(int i = 0; i < numbers.length; ++i) {
for(int j = 0; j < (i+1); ++j) {
numbers[i][j] = count++;
if(count > 9)
count = 1;
}
}
for(int i = 0; i < numbers.length; ++i) {
for(int j = 0; j < numbers.length; ++j) {
if(numbers[j][i] == 0)
System.out.print(" ");
else
System.out.print(numbers[j][i]);
System.out.print(" ");
}
System.out.println();
}
}
This will give you your result. Note that I didn't include the dynamic part with the scanner. I used the length and the start-number as constants.
Explanation:
In the first loop I am basically just storing the numbers in an array. And in the second loop this array is printed in a different order.
So, I'm trying to create a program that captures 9 numbers in a 2D array, being of size 3 x 3. After capturing all the numbers, they are re-arranged, reversed, and displayed.
So if a user entered:
1 2 3
4 5 6
7 8 9
It should be reversed as this:
9 8 7
6 5 4
3 2 1
So far I have this:
public class Reversenumber {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int[][] array1 = new int[3][3];
int val1 = 0;
int val2 = 0;
int[][] array2 = new int[3][3];
int val3 = 0;
int val4 = 0;
for (val1 = 0;val1<3; val1++){
for (val2 = 0;val2<3; val2++){
System.out.println("Please type number for column "+(val1+1)+" and row "+(val2+1));
array1[val1][val2] = kb.nextInt();
}
}
System.out.println("\nThe inverse of this array is:");
for(val1 = 0;val1<3; val1+=1){
for (val2 = 0;val2<3; val2+=1){
System.out.print(array1[val1][val2]+" ");
}
System.out.println("");
}
}
}
The problem I'm having is outputing the inverse of the array. The first for loop captures the information perfectly, but the second set of for loop displays that same information in a 3x3 array, but not inverted. Help anyone?
I hope you don't mind, I changed the variables around completely since they are confusing. also changed the way you input stuff.
Scanner kb = new Scanner(System.in);
int[][] array1 = new int[3][3];
int[][] array2 = new int[3][3];
for (int y = 0; y < array1.length; y++) {
System.out.println("input 3 numbers for row " + (y + 1));
for (int x = 0; x < array1[y].length; x++) {
array1[y][x] = kb.nextInt();
}
}
System.out.println("\nThe inverse of this array is:");
for (int y = array1.length; --y >= 0;) {
for (int x = array1[y].length; --x >= 0;) {
System.out.printf("%3d", array1[y][x]);
}
System.out.println();
}
output
input 3 numbers for row 1
1 2 3
input 3 numbers for row 2
4 5 6
input 3 numbers for row 3
7 8 9
The inverse of this array is:
9 8 7
6 5 4
3 2 1
So instead of inputting each separately you put 3 on the same line and put a space between them.
Assuming you mean invert like so:
1 2 3
4 5 6
7 8 9
to
1 4 7
2 5 8
3 6 9
It's as simple as keeping the loop the same, but swapping the coordinates between the arrays:
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int[][] array1 = new int[3][3];
int val1 = 0;
int val2 = 0;
int[][] array2 = new int[3][3];
int val3 = 0;
int val4 = 0;
for (val1 = 0; val1 < 3; val1++) {
for (val2 = 0; val2 < 3; val2++) {
System.out.println("Please type number for column " + (val1 + 1) + " and row " + (val2 + 1));
array1[val1][val2] = kb.nextInt();
}
}
System.out.println("\nOriginal array is:");
for (val1 = 0; val1 < 3; val1 += 1) {
for (val2 = 0; val2 < 3; val2 += 1) {
System.out.print(array1[val1][val2] + " ");
}
System.out.println("");
}
System.out.println("\nInverted array is:");
for (int x = 0; x < 3; x += 1) {
for (int y = 0; y < 3; y += 1) {
System.out.print(array1[y][x] + " ");
}
System.out.println("");
}
System.out.println("\nThe Reversed array is:");
for (int x = 2; x >= 0; x -= 1) {
for (int y = 2; y >= 0; y -= 1) {
System.out.print(array1[x][y] + " ");
}
System.out.println("");
}
}
Edit: I added the reversed scenario you asked about in the comment below. You actually expected output like this:
9 8 7
6 5 4
3 2 1
There's this problem from my programming class that I can't get right... The output must be all odd numbers, in odd amounts per line, until the amount of numbers per line meets the odd number that was entered as the input. Example:
input: 5
correct output:
1
3 5 7
9 11 13 15 17
If the number entered is even or negative, then the user should enter a different number. This is what I have so far:
public static void firstNum() {
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
if (num % 2 == 0 || num < 0)
firstNum();
if (num % 2 == 1)
for (int i = 0; i < num; i++) {
int odd = 1;
String a = "";
for (int j = 1; j <= num; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
firstNum();
}
The output I'm getting for input(3) is
1 3 5
1 3 5
1 3 5
When it really should be
1
3 5 7
Can anyone help me?
Try this:
public static void firstNum() {
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt();
}
int odd = 1;
for (int i = 1; i <= num; i += 2) {
String a = "";
for (int j = 1; j <= i; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
}
if (num % 2 == 1) {
int odd = 1;
}
for (int i = 0; i < num; i++) {
String a = "";
for (int j = 1; j <= odd; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
You should assign odd before for loop.
In inner for loop compare j and odd together.
For questions like this, usually there is no need to use and conditional statements. Your school probably do not want you to use String as well. You can control everything within a pair of loops.
This is my solution:
int size = 7; // size is taken from user's input
int val = 1;
int row = (size / 2) + 1;
for (int x = 0; x <= row; x++) {
for (int y = 0; y < (x * 2) + 1; y++) {
System.out.print(val + " ");
val += 2;
}
System.out.println("");
}
I left out the part where you need to check whether input is odd.
How I derive my codes:
Observe a pattern in the desired output. It consists of rows and columns. You can easily form the printout by just using 2 loops.
Use the outer loop to control the number of rows. Inner loop to control number of columns to be printed in each row.
The input number is actually the size of the base of your triangle. We can use that to get number of rows.
That gives us: int row = (size/2)+1;
The tricky part is the number of columns to be printed per row.
1st row -> print 1 column
2nd row -> print 3 columns
3rd row -> print 5 columns
4th row -> print 7 columns and so on
We observe that the relation between row and column is actually:
column = (row * 2) + 1
Hence, we have: y<(x*2)+1 as a control for the inner loop.
Only odd number is to be printed, so we start at val 1 and increase val be 2 each time to ensure only odd numbers are printed.
(val += 2;)
Test Run:
1
3 5 7
9 11 13 15 17
19 21 23 25 27 29 31
33 35 37 39 41 43 45 47 49
You can use two nested loops (or streams) as follows: an outer loop through rows with an odd number of elements and an inner loop through the elements of these rows. The internal action is to sequentially print and increase one value.
a loop in a loop
int n = 9;
int val = 1;
// iterate over the rows with an odd
// number of elements: 1, 3, 5...
for (int i = 1; i <= n; i += 2) {
// iterate over the elements of the row
for (int j = 0; j < i; j++) {
// print the current value
System.out.print(val + " ");
// and increase it
val += 2;
}
// new line
System.out.println();
}
a stream in a stream
int n = 9;
AtomicInteger val = new AtomicInteger(1);
// iterate over the rows with an odd
// number of elements: 1, 3, 5...
IntStream.iterate(1, i -> i <= n, i -> i + 2)
// iterate over the elements of the row
.peek(i -> IntStream.range(0, i)
// print the current value and increase it
.forEach(j -> System.out.print(val.getAndAdd(2) + " ")))
// new line
.forEach(i -> System.out.println());
Output:
1
3 5 7
9 11 13 15 17
19 21 23 25 27 29 31
33 35 37 39 41 43 45 47 49
See also: How do I create a matrix with user-defined dimensions and populate it with increasing values?
Seems I am bit late to post, here is my solution:
public static void firstNum() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the odd number: ");
int num = scanner.nextInt();
if (num % 2 == 0 || num < 0) {
firstNum();
}
if (num % 2 == 1) {
int disNum = 1;
for (int i = 1; i <= num; i += 2) {
for (int k = 1; k <= i; k++, disNum += 2) {
System.out.print(disNum + " ");
}
System.out.println();
}
}
}
I'm attempting to solve a Sudoku puzzle using Java. Currently this class is unable to solve a Sudoku properly.
This class attempts to look for the 0s (blank spaces) within the 9x9 matrix and notes down the position of the 0 in a list for later referencing. Following which it will then use those positions to solve that one 0. Unfortunately, it does not seem to work as I'd hope.
Here is my 9x9 matrix that I used:
0 6 0 1 0 4 0 5 0
0 0 8 3 0 5 6 0 0
2 0 0 0 0 0 0 0 1
8 0 0 4 0 7 0 0 6
0 0 6 0 0 0 3 0 0
7 0 0 9 0 1 0 0 4
5 0 0 0 0 0 0 0 2
0 0 7 2 0 6 9 0 0
0 4 0 5 0 8 0 7 0
There are 51 0s in this 9x9 matrix, however when it solves the puzzle, it appends 66 positions for some weird reason. I can't seem to pinpoint the issue. Any help would be greatly appreciated!
This is the attempted solution that it spits out:
9 6 3 1 8 4 7 5 0
4 7 8 3 9 5 6 2 0
2 5 0 7 6 0 8 9 1
8 9 5 4 3 7 2 1 6
1 2 6 8 5 0 3 0 9
7 3 0 9 2 1 5 8 4
5 8 9 0 7 3 4 6 2
3 1 7 2 4 6 9 0 8
6 4 2 5 1 8 0 7 3
Code:
package com.dc.soduku;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Sudoku {
int[][] grid = new int[9][9];
int emptyCell = 0;
List<String> EmptyCells = new ArrayList<String>();
public Sudoku() {
for (int i = 0; i < 9; i++) {
for (int x = 0; x < 9; x++) {
Scanner scanner = new Scanner(System.in);
System.out.println("Row " + i + " Column " + x + " (Enter values from 1-9): ");
int temp = scanner.nextInt();
grid[i][x] = temp;
}
}
}
public Sudoku(int[][] gridInput) {
grid = gridInput;
}
public void emptyCellsChecker() {
int count = 0;
EmptyCells.clear();
for (int i = 0; i < 9; i++) {
for (int x = 0; x < 9; x++) {
if (grid[i][x] == 0) {
System.out.println("Blank at row " + i + " column " + x + ".");
count++;
EmptyCells.add(i + "," + x);
}
}
}
System.out.println("Total number of empty cells: " + count);
// System.out.print(mm.toString());
System.out.println((EmptyCells.get(1)).substring(0, 1));
System.out.println((EmptyCells.get(1)).substring(2, 3));
}
public void printSudoku() {
for (int i = 0; i < 9; i++) {
for (int x = 0; x < 9; x++) {
System.out.print(grid[i][x] + " ");
}
System.out.println("");
}
}
public void appendCell(int row, int col, int replacement) {
this.grid[row][col] = replacement;
}
public int getCell(int row, int col) {
return grid[row][col];
}
public boolean isEmpty() {
for (int i = 0; i < 9; i++) {
for (int x = 0; x < 9; x++) {
if (grid[i][x] == emptyCell) {
return true;
}
}
}
return false;
}
public boolean checkRow(int row, int guess) {
for (int i = 0; i < 9; i++) {
if (grid[row][i] == guess) {
return false;
}
}
return true;
}
public boolean checkColumn(int col, int guess) {
for (int i = 0; i < 9; i++) {
if (grid[i][col] == guess) {
return false;
}
}
return true;
}
public boolean checkBox(int row, int col, int guess) {
row = (row / 3) * 3;
col = (col / 3) * 3;
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
if (grid[row + r][col + c] == guess) {
return false;
}
}
}
return true;
}
public boolean checkGuess(int row, int col, int guess) {
return (checkRow(row, guess) && checkColumn(col, guess) && checkBox(row, col, guess));
}
public void solve() {
int nEmptyCells = EmptyCells.size();
String tempR, tempC;
int tRow, tCol, counter = 0;
if (isEmpty() == false) {
System.out.println(
"Sudoku has no empty cells, you have either provided a solved sudoku or entered something incorrectly.");
} else {
for (int i = 0; i < nEmptyCells; i++) {
tempR = ((EmptyCells.get(i)).substring(0, 1));
tempC = ((EmptyCells.get(i)).substring(2, 3));
tRow = Integer.parseInt(tempR);
tCol = Integer.parseInt(tempC);
for (int v = 1; v < 10; v++) {
if (checkGuess(tRow, tCol, v) == true) {
this.grid[tRow][tCol] = v;
counter++;
System.out.println("Solved row " + tRow + " column " + tCol + " with " + v);
}
}
}
}
System.out.println("Total appended: " + counter);
}
}
This problem solved already as well by Backtracking algorithms:
Sudoku backtracking algorithm (Java)
Sudoku solving algorithm with back-tracking
Your question in a nutshell "For the given input why do I get 66 appends when there are only 51 empty cells?"
Your current algorithm:
For each empty cell in the grid
Use the current state of the grid
Guess each number 1 to 9
Verify current guess as a possible solution in col, row, and box
Update grid state with possible solution
Continue trying each number to 9
To answer your question you are accepting all possible solutions as solutions for a particular cell given the current state of the grid. According to your algorithm it correctly results in 66 solutions.
What you could do is:
Record all possible solutions for each empty cell in the grid without grid updates
Determine all permutations of possible solutions for the grid
Loop through all permutations and verify each permutation set as a solution to the grid