How do I print out factors of an input using loops? - java
Here is my mess of a code. I have to write a program that inputs a positive integer greater than 3. Validate that the integer is in fact greater than 3. Then print all possible pairs of positive integers great than whose product is less than or equal to the number entered.
ex. If 24 is the input.
It would print:
4 = 2 x 2
6 = 2 x 3
8 = 2 x 4
10 = 2 x 5
12 = 2 x 6
14 = 2 x 7
16 = 2 x 8....
9 = 3 x 3
12 = 3 x 4..
24 = 3 x 8...
all the way to
24 = 4 x 6
import java.util.Scanner;
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int j = 0;
int k = 2;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
while (product < i) {
if (product == i) { j++; k = 2;
for (j = 2; product < i; k++) {
product = j * k;
System.out.println(product + " = " + j + " x " + k);
if (product == i) { j++; k = 2;
}
}
}
}
}
}
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
for (int j = 2; j < i / 2; j++) {
for (int k = 2; k < i / 2; k++) {
if (j <= k && j * k <= i)
System.out.println(j * k + " = " + j + "*" + k);
}
}
// while (product < i) {
// if (product == i) {
// j++;
// k = 2;
// for (j = 2; product < i; k++) {
// product = j * k;
// System.out.println(product + " = " + j + " x " + k);
// if (product == i) {
// j++;
// k = 2;
// }
// }
// }
// }
}
}
Related
How to print a 2D array in java
Hello so am trying to create a 2D array of int with random number of rows and columns and a random starting and ending points using java to apply the A* algorithm on it. When i add {S} and {E} to define the tow points and print it there are numbers outside of the 2D array printed. `Random rand = new Random(); int min = 2, max = 10; // a random number of rows and columns int a = (int)(Math.random() * (max - min + 1)) + min; // the location of the starting point. int row_start = rand.nextInt(a); int col_start = rand.nextInt(a); // the location of the ending point. int row_end = rand.nextInt(a); int col_end = rand.nextInt(a); int [][] M = new int [a][a]; public void create() { //empty: 0; grass: 1; sand: 2; water: 3; wall: 4. for (int i = 0; i < a; i++) { for (int j = 0; j < a; j++) { M[i][j] = rand.nextInt(5); } } for (int i = 0; i < a; i++) { for (int j = 0; j < a; j++) { System.out.print(" " +M[i][j] + "\t"); if(row_start == i && col_start == j) { System.out.print("{S}" + "\t"); } if(row_end == i && col_end == j) { System.out.print("{E}" + "\t"); } } System.out.print("\n"); } }` the output looks like this: 1 0 4 0 2 {S} 1 2 2 4 4 {E} 0 3 2 0 3 3 the 2 and 3 shouldn't appear there.
The problem is that you always print m[i][j]. What you need is to only print m[i][j] when i and j are not S and E positions. When i and j are S and E positions, print S or E. Otherwise, print m[i][j]. if(row_start == i && col_start == j) { System.out.print("{S}" + "\t"); } else if(row_end == i && col_end == j) { System.out.print("{E}" + "\t"); } else { System.out.print(" " +M[i][j] + "\t"); }
How to determine how many times a character is repeated in a string?
I am having some trouble with writing a method that when prompted with a number returns how many times each value is repeated. For example, if the number 7846597 is entered the method would return: 0 - 0 1 - 0 2 - 0 3 - 0 4 - 1 5 - 1 6 - 1 7 - 2 8 - 1 9 - 1 I know this would be most easily done with a loop, but I am not sure how to write the actual code. I also know that I need to convert the number value I get as an input into a string so I can use char methods. This is my attempt: public double countOccurences(int num) { String str = num + ""; int goneThrough = 0; int count0 = 0; int count1 = 0; int count2 = 0; int count3 = 0; int count4 = 0; int count5 = 0; int count6 = 0; int count7 = 0; int count8 = 0; int count9 = 0; while(goneThrough <= str.length()) { int value = 0; if(value >= 10){ value = value * 0; } if(str.charAt(0) == 0) count0++; if(str.charAt(0) = 1) count1++; } return count0; return count1; return count2; return count3; return count4; return count5; return count6; return count7; return count8; return count9; }
countOccurences(int num) should return the number of occurrences of each digit as int[10]. static int[] countOccurences(int num) { int[] result = new int[10]; for ( ; num > 0; num /= 10) ++result[num % 10]; return result; } public static void main(String[] args) { int input = 7846597; int[] output = countOccurences(input); for (int i = 0; i < 10; ++i) System.out.println(i + " - " + output[i]); } output: 0 - 0 1 - 0 2 - 0 3 - 0 4 - 1 5 - 1 6 - 1 7 - 2 8 - 1 9 - 1
This is my code where I used HashTable and stored number as string and count as value. This is optimized code where time complexity is O(n). // code import java.util.*; class Main { public static void main(String args[]) { String number = "7846597"; Hashtable<String, Integer> result = new Hashtable<String, Integer>(); for(int i=0; i<number.length(); i++){ String current = "" + number.charAt(i); if(result.contains(current)) { int val = result.get(current); result.put(current, ++val); } else { result.put(current, 1); } } System.out.print(result); } }
Using int array of size 10 and increment value at index that maps to digit of 0-9. public static void digitFrequencies(int number) { int[] arr = new int[10]; for (char ch : String.valueOf(number).toCharArray()) { int digit = Character.digit(ch, 10); arr[digit] = arr[digit] + 1; } for (int i = 0; i < arr.length; i++) { System.out.print(i + " - " + arr[i] + " "); } }
How can I test credit numbers with hyphens (" -" ) to get it as INVALID . When I tried 4003-6000-0000-0014 i am getting errors
I cant get credit card numbers containing hymens as INVALID such as 4003-6000-0000-0014 must give me INVALID but its giving me errors of string. public class prog { public static void main(String[] args) { Scanner userInput = new Scanner(System.in) ; System.out.println("How many credit card you want to check?"); int numOfCredit = userInput.nextInt() ; int creditnumbers[] = new int[numOfCredit] ; for (int i = 0 ; i<numOfCredit ; i++) { System.out.println("Enter credit card number "+(i+1)+": ") ; String creditNumber = userInput.next() ; validateCreditCardNumber(creditNumber); } } private static void validateCreditCardNumber(String str) { // function to check credit numbers int[] ints = new int[str.length()]; for (int i = 0; i < str.length(); i++) { ints[i] = Integer.parseInt(str.substring(i, i + 1)); } for (int i = ints.length - 2; i >= 0; i = i - 2) { int j = ints[i]; j = j * 2; if (j > 9) { j = j % 10 + 1; } ints[i] = j; } int sum = 0; for (int i = 0; i < ints.length; i++) { sum += ints[i]; } if (sum % 10 == 0) { System.out.println("VALID"); } else { System.out.println("INVALID"); } } } I get these errors after running with hymens : Exception in thread "main" java.lang.NumberFormatException: For input string: "-" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68) at java.base/java.lang.Integer.parseInt(Integer.java:642) at java.base/java.lang.Integer.parseInt(Integer.java:770) at testing/testing.prog.validateCreditCardNumber(prog.java:33) at testing/testing.prog.main(prog.java:22)
you can replace in your string "-" with "" (blank) and then apply this function: String card = "4003-6000-0000-0014"; Boolean t = check(card.replace("-","")); public static boolean check(String ccNumber) { int sum = 0; boolean alternate = false; for (int i = ccNumber.length() - 1; i >= 0; i--) { int n = Integer.parseInt(ccNumber.substring(i, i + 1)); if (alternate) { n *= 2; if (n > 9) { n = (n % 10) + 1; } } sum += n; alternate = !alternate; } return (sum % 10 == 0); }
Printing integer from 2D array using nested FOR Loops
I'm having a bit of a problem with a piece of Java code, part of an AI project. The programm is supposed to take a 11x13 2d array representing a maze. The printed maze we are given uses characters for each cell, but for ease of use I've converted it to integers using a mnemonic code. My problem is when I try to print the 2d integer array to the screen, to check eveything is OK, I get zeros at every cell, even though I have a check function in place which parses the array cell-by-cell checking for incorrect values. The project is currently composed of 2 files. The main file - function (AISemesterProject.java) and a file that will implement the UCS algorithm in the future (UCS.java) AISemesterProject.java package aisemesterproject; public class AISemesterProject { public static void main(String[] args) { UCS a = new UCS(); a.checkArrayInt(); a.printInt(); } } UCS.java package aisemesterproject; import java.util.Arrays; public class UCS { int row = 11; int col = 13; int[][] array_int = new int[row][col]; public UCS() { // Lets assume // x = 0 // e = 1 // d = 2 // s = 8 // g = 9 int[][] array_int = new int[][] { {0,1,0,1,1,1,1,0,0,1,0,9,0}, {1,1,1,2,0,1,1,0,0,1,2,1,0}, {0,1,0,1,1,1,1,0,0,1,0,0,0}, {8,1,2,0,1,2,0,1,1,2,1,1,1}, {0,0,1,1,0,1,1,1,0,0,0,0,0}, {1,2,1,0,1,0,1,1,0,0,1,1,1}, {0,1,2,0,1,0,0,2,1,1,2,1,9}, {1,0,1,1,2,1,1,1,0,1,1,1,1}, {1,1,2,1,1,0,0,1,0,0,0,0,0}, {0,0,1,1,1,0,0,1,1,1,1,1,2}, {0,0,1,0,0,1,1,1,0,9,0,1,1} }; } public void checkArrayInt() { int i = 0, j = 0; boolean checker = false; for(i = 0; i < row; i++) { for(j = 0; j < col; j++) { if(!(array_int[i][i] == 0 || array_int[i][j] == 1 || array_int[i][j] == 2 || array_int[i][j] == 8 || array_int[i][j] == 9)) { checker = true; System.out.print("Error at Row:" + i + " Column:" + j + "\n"); } } } if(checker == false) { System.out.print("Array OK... \n"); } } public void printInt() { int i = 0, j = 0; //System.out.println(Arrays.deepToString(array_int)); for(i = 0; i < row; i++) { System.out.print("Row " + (i + 1) + ":"); for(j = 0; j < col; j++) { System.out.print(" " + String.valueOf(array_int[i][j])); //System.out.print(" " + Integer.toString(array_int[i][j])); //System.out.printf(" %d", array_int[i][j]); //System.out.print(" " + array_int[i][j]); } System.out.print("\n"); } } } Output As you can see the output is not what I expected and I have tried 4 different methods for the print (1 active, 3 commented) but the result is always the same. Anyone have an idea what am I missing or doing wrong? Thanks for your time.
It looks like you have a scope issue... int[][] array_int = new int[row][col]; public UCS() { // Lets assume // x = 0 // e = 1 // d = 2 // s = 8 // g = 9 array_int = new int[][] { {0,1,0,1,1,1,1,0,0,1,0,9,0}, {1,1,1,2,0,1,1,0,0,1,2,1,0}, {0,1,0,1,1,1,1,0,0,1,0,0,0}, {8,1,2,0,1,2,0,1,1,2,1,1,1}, {0,0,1,1,0,1,1,1,0,0,0,0,0}, {1,2,1,0,1,0,1,1,0,0,1,1,1}, {0,1,2,0,1,0,0,2,1,1,2,1,9}, {1,0,1,1,2,1,1,1,0,1,1,1,1}, {1,1,2,1,1,0,0,1,0,0,0,0,0}, {0,0,1,1,1,0,0,1,1,1,1,1,2}, {0,0,1,0,0,1,1,1,0,9,0,1,1} }; you already created the array as a class level variable
Your constructor is setting the local variable array_int. This local variable overshadows the field with the same name, and thus it never sees the array you're assigning to it. You should make sure that you're assigning to the field, which can most easily be done by removing the int[][] word from your constructor.
Thank you everyone. I moved the declatarion from the constructor to the variable at the beggining and it worked. package aisemesterproject; import java.util.Arrays; public class UCS { int row = 11; int col = 13; // Lets assume // x = 0 // e = 1 // d = 2 // s = 8 // g = 9 int[][] array_int = new int[][] { {0,1,0,1,1,1,1,0,0,1,0,9,0}, {1,1,1,2,0,1,1,0,0,1,2,1,0}, {0,1,0,1,1,1,1,0,0,1,0,0,0}, {8,1,2,0,1,2,0,1,1,2,1,1,1}, {0,0,1,1,0,1,1,1,0,0,0,0,0}, {1,2,1,0,1,0,1,1,0,0,1,1,1}, {0,1,2,0,1,0,0,2,1,1,2,1,9}, {1,0,1,1,2,1,1,1,0,1,1,1,1}, {1,1,2,1,1,0,0,1,0,0,0,0,0}, {0,0,1,1,1,0,0,1,1,1,1,1,2}, {0,0,1,0,0,1,1,1,0,9,0,1,1} }; public UCS() { // Lets assume // x = 0 // e = 1 // d = 2 // s = 8 // g = 9 // Array initialization outside the constructor scope } public void checkArrayInt() { int i = 0, j = 0; boolean checker = false; for(i = 0; i < row; i++) { for(j = 0; j < col; j++) { if(array_int[i][j] == 0) //Check for 0 = x { checker = false; } else if(array_int[i][j] == 1) //Check for 1 = e { checker = false; } else if(array_int[i][j] == 2) //Check for 2 = d { checker = false; } else if(array_int[i][j] == 8) //Check for 8 = s { checker = false; } else if(array_int[i][j] == 9) //Check for 9 = g { checker = false; } else //All other integers, which are false { checker = true; System.out.print("Error at Row:" + i + " Column:" + j + "\n"); } } } if(checker == false) { System.out.print("Array OK... \n"); } } public void printInt() { int i = 0, j = 0; //System.out.println(Arrays.deepToString(array_int)); for(i = 0; i < row; i++) { System.out.print("Row " + (i + 1) + ":"); for(j = 0; j < col; j++) { System.out.print(" " + String.valueOf(array_int[i][j])); //System.out.print(" " + Integer.toString(array_int[i][j])); //System.out.printf(" %d", array_int[i][j]); //System.out.print(" " + array_int[i][j]); } System.out.print("\n"); } } }
Pascal's triangle positioning
I made a Java program that prints out a pascal triangle, however I can't figure out how to correctly position it. Program 1 public class Triangle { public static void main() { System.out.println("\nTriangle: "); int row = 11; long[][] triangle = new long[row][row]; triangle[1][1] = 1; System.out.print(triangle[1][1] + "\n"); for (int i = 2; i < row; i++) { for (int n = 1; n < row; n++) { triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n]; if (triangle[i][n] > 0) { System.out.print(triangle[i][n] + " "); } } System.out.println(); } } } Output: 1 1 1 1 2 1 1 3 3 1 Program 2 public class Triangle { public static void main() { System.out.println("\nTriangle: "); int row = 11; long[][] triangle = new long[row][row]; int x = 1; while (x < row - 1) { System.out.print(" "); x++; } triangle[1][1] = 1; System.out.print(triangle[1][1] + "\n"); for (int i = 2; i < row; i++) { x = i; while (x < row - 1) { System.out.print(" "); x++; } for (int n = 1; n < row; n++) { triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n]; if (triangle[i][n] > 0) { System.out.print(triangle[i][n] + " "); } } System.out.println(); } } } Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 //(Notice this line is incorrectly positioned) When the triangle approaches multiple digit numbers, it starts to break down and makes it ugly. Can someone explain how I can display a normal triangle instead of this ugly one?
Dynamic Pascal Triangle generator is here: import java.io.IOException; import java.util.Scanner; public class Main { static double fact(int n) { double result = 1; for (double i = 1; i <= n; i++) result *= i; return result; } static double combine(int n, int r) { return ((fact(n)) / (fact(n - r) * fact(r))); } static void pascalTriangle(int n) { int n2 = n; for (int i = 0; i < n; i++) { for (int space = 8 * (n2 - 1); space >= 0; space--) { System.out.printf(" "); } for (int j = 0; j <= i; j++) { System.out.printf("%14.0f", combine(i, j)); System.out.printf(" "); } System.out.println(); n2--; } } public static void main(String[] args) throws IOException, InterruptedException { #SuppressWarnings("resource") Scanner sc = new Scanner(System.in); System.out.print("Enter Number of Lines(n): "); int n = sc.nextInt(); pascalTriangle(n); System.out.println("Press any key to exit! "); sc.nextByte(); } }
Try this ... Results: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 import java.util.*; public class HelloWorld { static int binCoeff(int n, int k) { int res = 1; if (k > n - k) k = n - k; for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } static void pascalTriangle(int lines) { for (int i = 0; i < lines; i++) { for (int j = 0; j <= i; j++) System.out.print(HelloWorld.binCoeff(i, j) + " "); System.out.println(); } } public static void main(String[] args) { System.out.println("Results: "); HelloWorld.pascalTriangle(8); } }
/** * #author Ranjith */ public class JavaApplication2 { /** * #param args the command line arguments */ public static void main(String[] args) { int i; int x; int n = 15; //number of rows String newLine = System.getProperty("line.separator"); for (i = 0; i < n; i++) { //loop to adjust spacing x = i; while (x < n - 1) { System.out.print(" "); x++; } fib(i); //fibonacci function is called System.out.print(newLine); } } public static void fib(int num) { //fibonacci function int[] febo = new int[100]; febo[0] = 0; febo[1] = 1; for (int i = 2; i < num; i++) { febo[i] = febo[i - 1] + febo[i - 2]; } for (int i = 0; i < num; i++) { System.out.print(febo[i] + " "); } } } Output: 0 0 1 0 1 1 0 1 1 2 0 1 1 2 3 0 1 1 2 3 5 0 1 1 2 3 5 8 0 1 1 2 3 5 8 13 0 1 1 2 3 5 8 13 21 0 1 1 2 3 5 8 13 21 34 0 1 1 2 3 5 8 13 21 34 55 0 1 1 2 3 5 8 13 21 34 55 89 0 1 1 2 3 5 8 13 21 34 55 89 144 0 1 1 2 3 5 8 13 21 34 55 89 144 233
You can represent such a triangle as a 2d array, where the elements of the first row and column are equal to one, and all other elements are the sum of the previous element in the row and column. arr[i][j] = arr[i][j-1] + arr[i-1][j]; Then you can position it in the upper left corner as follows: 1 1 1 1 1 1 1 1 1 1 2 3 4 5 6 7 8 1 3 6 10 15 21 28 1 4 10 20 35 56 1 5 15 35 70 1 6 21 56 1 7 28 1 8 1 Try it online! public static void main(String[] args) { int n = 9; // an array of 'n' rows int[][] arr = new int[n][]; // iterate over the rows of the array for (int i = 0; i < n; i++) { // a row of 'n-i' elements arr[i] = new int[n - i]; // iterate over the elements of the row for (int j = 0; j < n - i; j++) { if (i == 0 || j == 0) { // elements of the first row // and column are equal to one arr[i][j] = 1; } else { // all other elements are the sum of the // previous element in the row and column arr[i][j] = arr[i][j - 1] + arr[i - 1][j]; } } } // formatted output for (int[] row : arr) { for (int el : row) { // formatting as a number with a trailing space System.out.printf("%2d ", el); // two-digit number // System.out.printf("%3d ", el); // three-digit number // System.out.printf("%4d ", el); // four-digit number } System.out.println(); } } See also: • Pascal's triangle 2d array - formatting printed output • Print Pascal's Triangle
class pascal { static void main(int n) { int a[][] = new int[n][n + 1]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = 0; } } a[0][1] = 1; int k = 5; int p = 0; for (int i = 1; i < n; i++) { for (int j = 1; j < n + 1; j++) { a[i][j] = a[i - 1][j] + a[i - 1][j - 1]; } } for (int i = 0; i < a.length; i++) { for (p = n + -i; p > 0; p--) { System.out.print(" "); } for (int j = 0; j < a[i].length; j++) { if (a[i][j] != 0) { System.out.print(a[i][j] + " "); } else { System.out.print(" "); } } System.out.println(); } } }