How do I iterate through an int - java

I get an "int cannot be dereferenced" It might be because .lenght on it, What else can I do to iterate through the int?
int num;
System.out.print("Enter a positive integer: ");
num = console.nextInt();
if (num > 0)
for (int i = 0; i < num.lenght; i++)
System.out.println();

for (int i = 0; i < num; i++)
Your num already is a number. So your condition will suffice like above.
Example: If the user enters 4, the for statement will evaluate to
for (int i = 0; i < 4; i++), running the loop four times, with i having the values 0, 1, 2 and 3
If you wanted to iterate over each digit, you would need to turn your int back to a string first, and then loop over each character in this string:
String numberString = Integer.toString(num);
for (int i = 0; i < numberString.length(); i++){
char c = numberString.charAt(i);
//Process char
}
If you wanted to iterate the binary representation of your number, have a look at this question, it might help you.
Note: though it might not be required, I would suggest you to use {}-brackets around your statement blocks, to improve readability and reduce chance of mistakes like this:
if (num > 0) {
for (int i = 0; i < num; i++) {
System.out.println();
}
}

IntStream.range(0, num).forEach(System.out::println);

Try the following code:
import java.util.Scanner;
public class IntExample {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = console.nextInt();
console.close();
if (num > 0) {
for (int i = 0; i < num; i++) {
System.out.println(i);
}
}
}
}

Using Integer.toString Method
int num = 110102;
String strNum = Integer.toString(num);
for (int i = 0; i < strNum.length(); i++) {
System.out.println(strNum.charAt(i));
}
Using Modulo Operator
`
int num = 1234;
while(num>0) {
int remainder = num % 10;
System.out.println(remainder);
num = num / 10;
}

Related

How many times a number occurs

I need to write a program that reads an array of ints and an integer number n. The program must check how many times n occurs in the array.
Input:
The first line contains the size of the input array.
The second line contains elements of the array separated by spaces.
The third line contains n.
Output:
The result is only a single non-negative integer number.
My code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
int n = scanner.nextInt();
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int counter = 0;
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);
}
}
Test input:
6
1 2 3 4 2 1
2
My result: 1
My question is why int n = scanner.nextInt();read "1". It should "2".
Reading the n variable was in the wrong place. The solution:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int counter = 0;
int n = scanner.nextInt();
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);
}
}
You should read n after you read the array like so:
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int n = scanner.nextInt();
int counter = 0;
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);

2D Array: Magic Square

The question I am working on is:
A square with the side length n is filled with numbers 1,2,3,...n2 is a magic square if the sum of elements in each row, column, and two diagonals is the same value.
Write a program that reads in a value of 16 values from the keyboard and tests whether they form a magic square when put into a 4 x 4 array. You need to test the following 2 features:
Does each number of 1,2,...16 occur in user input? Tell the user to try again if they enter a number that they've already entered.
When the numbers are put into a square, are the sums of rows, columns, and diagonals equal to each other?
It must be done using two-dimensional array
I am having trouble with asking the user to try again if they enter a number that they have previously entered. And, numbers in 4 x 4 do not print.
What am I doing wrong? How can I fix it?
This is the code I have so far:
Scanner in = new Scanner (System.in);
int n =4;
int[][] square = new int[n][n];
int number = 0;
int num = 0;
for (int i = 0; i <16; i++){
number = num;
System.out.print ("Enter a number: ");
num = in.nextInt();
int num_2 = 0;
if (number==num || number==num_2) {
System.out.println ("Try again.");
System.out.println ("Enter a number: ");
num_2 = in.nextInt();
}
if (num > 16){
System.out.println ("Try again.");
break;
}
}
for (int i= 0; i < n; i++){
for (int j = 0; j < n; j++) {
num+=square [i][j];
System.out.print(square[i][j] + "\t");
}
}
}
}
You can try this code for 1st feature and add code for 2nd one.
int ar[][] = new int[4][4];
System.out.println("Enter Numbers");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
boolean flag = false;
int num = sc.nextInt();
if (num > 16 || num < 1) {
System.out.println("Please Enter number between 1 to 16");
flag=true;
j--;
} else {
for (int k = 0; k <= i; k++) {
for (int l = 0; l <= j; l++) {
if (ar[k][l] == num) {
System.out.println("This number already inserted...Please give another");
j--;
flag = true;
}
}
}
}
if (!flag) {
ar[i][j] = num;
}
}
}
If you can't understand anything please ask.
Hope this help.

JAVA: Passing an array to a method

I can't seem to pass my array to a secondary method. It only sees one of the 10 inputs, so I can't properly use it in the secondary method.
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter some numbers: ");
double [] numbers = new double [10];
int n = 0;
int i = 0;
while(n < numbers.length) {
numbers[i] = input.nextDouble();
n+=1;
}
System.out.println(min(numbers));
}
public static double min(double[] array) {
System.out.println(array[1]);
double smallest = array[0];
for (int l = 1; l < array.length; l++) {
if (array[l] < smallest) {
smallest = array[l];
System.out.println("Your smallest = " + smallest);
}
}
return 0;
}
In the first while loop, the variable i does not change.
while (n < numbers.length) {
numbers[i] = input.nextDouble();
n+=1;
}
variable i is never being changed so you are assigning each new number to the same spot in the array overwriting the previous number.
Just use your n variable instead:
while (n < numbers.length) {
numbers[n] = input.nextDouble();
n += 1;
}

Printing a triangle of prime numbers using for loop

I am trying to make a triangle of prime numbers .. the number of rows will be user defined
for example if user gives "4" as number of rows then the program should show a triangle of prime numbers containing 4 rows
input :4
output :
2
3 5
7 11 13
17 19 23 29
These are two tasks: get the list of primes (or just something like nextPrime(int)) and get the triangle, both are very simple.
For the implementation of first, you may look at Next Prime number Java only working with certain numbers
For the implementation of second, just do something like:
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
nextPrime = ...
System.out.print (nextPrime + " ");
}
System.out.println ();
}
Let say you already have your primes (sufficient amount).
int[] primes = ...;
Then for N strings create array is StringBuilders and fill them up with your numbers:
StringBuilder[] builders = new StringBuilder[N];
int count = 0;
for(int row = 0; row < N; row++) {
int size = row + 1;
builders[row] = new StringBuilder();
for(int i = 0; i < size; i++) {
builders[row].append(primes[count++]);
builders[row].append(' ');
}
}
And then you may print them
for(StringBuilder sb : builders)
System.out.println(sb);
//please try these
import java.util.*;
public class primePtt1
{
public static boolean isPrimeNumber(int num) {
int c=0;
for (int i = 1; i <= num; i++) {
if (num % i == 0)
c++;
}
if (c==2)
return true;
else
return false;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter no. of rows : ");
int rows = sc.nextInt();
int counter = 2;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
/* Try to find next prime number by incrementing counter and testing it for primality */
while(!isPrimeNumber(counter)){
counter++;
}
System.out.print(counter+" ");
counter++;
}
System.out.println();
}
}
}

Iterate through a number starting at the end and adding every other digit

I am working on a school assignment, so I am looking for guidance on what I am doing wrong. This is part of a larger program, but I am trying to work on loop before I implement the rest of the program. Basically, my loop is suppose to iterate through all the number and then add every other number, for example:
if the number entered is 48625, then return the sum of 5+6+4. I figured that I would have to combine my loop with an if statement to iterate through each nth number, so this is what I worked out so far:
class testLoop{
public static void main (String args[]){
int num = 12345;
int sum = 0;
for(int i = 0; num > 0; i++)
{
if(i%num == 0)
{
sum += num % 10;
}
num /= 10;
System.out.println(sum);
}
}
}
Unfortunately, this is not working. It returns 6,5,5,5,5. It is not adding the nth values as planned.
I also tried the following:
int num = 12345;
int sum = 0;
while(num > 0) {
sum += num % 10;
num /= 10;
}
But that did not work either, it returned 15, which is basically the sum of all digits in variable num. I know I am close to a solution, it's somewhere between my two codes, but I can't seem to get it right.
Simply divide by 100. That will skip the even numbers.
int num = 12345;
int sum = 0;
while(num > 0) {
sum += num % 10;
num /= 100;
}
int num = 12345;
int sum = 0;
int pos = 0;
while(num > 0) {
int digit = num % 10; // make it really blatantly clear what the DIGIT is
if (pos % 2 == 0)
sum += digit;
num /= 10;
pos++;
}
You needed a checking mechanism to ensure you're skipping half the digits. [You're trying to add digits of the number, not numbers. Editor.]
This would also fix your first solution:
if(i%2 /*not num*/ == 0)
int num = 12345;
int sum = 0;
String str = String.valueOf(num);
for (int i = str.toCharArray().length - 1, j = 0; i >= 0; i--, j++) {
if (j % 2 == 0) {
int number = Character.digit(str.charAt(i), 10);
sum += number;
}
}
System.out.println(sum);

Categories

Resources