I have an assignment due for class and the objective is to take an Array and run it through a method that will print the array out in reverse order, then run it through a second method to test if the number is prime then print the still reversed order array out without the prime numbers. I can get the reverse the order part fine, I am running into trouble with the prime numbers part:
public class Driver {
public static void main(String[] args) {
// CTORs
int[] MyArray = { 10, 8, 7, 14, 22, 11 };
int[] myArray2 = new int[7];
// METHOD CALLING
MyArray = reverseOrder(6, MyArray);
MyArray = primeCheck(MyArray, 6);
for (int i = 0; i < myArray2.length; i++)
System.out.println(myArray2[i] + " ");
}// MAIN
/*--------------------ARRAY PRIME TEST---------------------*/
private static int[] primeCheck(int[] myArray, int num) {
//prime
boolean prime = true;
int[] myArray2 = new int[10];
//test all components of an array
for (int i = num + 1 ; i >= 0; i++) {
if (num % i > 0) {
prime = false;
System.arraycopy(myArray, 0, myArray2, 0, 4);
return myArray2;
}
}
return myArray2;
}// ISPRIME REMOVE
}// CLOSE CLASS
my output is as follows:
11 22 14 7 8 10 0
0
0
0
0
0
I feel really rusty because this is the first assignment back after a long break, so any guidance or help would be greatly appreciated.
myArray2 is defined and never filled with values. So every element is 0.
I think
for (int i = 0; i < myArray2.length; i++)
must be
for (int i = 0; i < myArray.length; i++)
There's definitely something wrong about for (int i = num + 1 ; i >= 0; i++). Below is one way to achieve the objective.
public static void main(String[] args) {
int[] arr = { 10, 8, 7, 14, 22, 11 };
for(int i = 0; i < arr.length; i++) {
if(!isPrime(arr[i])) {
System.out.print(arr[i] + " ");
}
}
}
public static boolean isPrime(int num) {
if(num < 2) return false;
if(num == 2) return true;
int remainder, divisor;
divisor = num - 1;
do {
try {
remainder = num % divisor;
} catch (ArithmeticException e) {
return false;
}
if(remainder == 0) return false;
divisor--;
} while (divisor > 1);
return true;
}
Related
public class Nodigeven {
static int even=0;
static int count=0;
static int findnodigeven(int[] arr) {
for(int i=0;i<arr.length;i++) {
while(arr[i]!=0) {
arr[i]= arr[i]/10;
count++;
}
if(count%2==0) {
even++;
}
}
return even;
}
public static void main(String[] args) {
int[] arr = {122,255,133,14,15,16};
System.out.println(findnodigeven(arr));
}
}
am getting wrong output i.e : 1 .. can you tell me where i am going wrong here in the code
As far as I can tell you have two errors. The first is that you did not reset count to 0 for each iteration of the loop. The second is that you did not check the special case of 0 in the array. 0 is a single digit and thus odd. But since you never enter the while loop, count will remain 0 and even will be incremented.
public class Nodigeven {
static int findnodigeven(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int count = 0;
// check for 0 value and skip.
if (arr[i] == 0) {
continue;
}
while (arr[i] != 0) {
arr[i] = arr[i] / 10;
count++;
}
if (count % 2 == 0) {
even++;
}
}
return even;
}
public static void main(String[] args) {
int[] arr = { 122, 255,0, 133, 14, 15, 16 };
System.out.println(findnodigeven(arr));
}
}
If you're interested you and do this without explicitly counting the digits. Use Math.log10() to get the count, again skipping 0 since the log of 0 is undefined. The number of digits in a decimal number N is Math.log10(N)+1. You can use the conditional operator to add 1 or 0 as appropriate to the parity count.
public class Nodigeven {
static int even = 0;
static int findnodigeven(int[] arr) {
int even = 0;
for (int i = 0; i < arr.length; i++) {
even += arr[i] != 0 &&
(int) (Math.log10(arr[i])+1) % 2 == 0
? 1 : 0;
}
return even;
}
public static void main(String[] args) {
int[] arr = { 122, 255,0, 133, 14, 15, 16 };
System.out.println(findnodigeven(arr));
}
}
I am stuck on an issue that I cannot seem to resolve. I cannot seem to to test my code correctly. My code is as follows
public static int sum13( int[] nums) {
int sum = 0;
for(int i = 0; i <= nums.length - 1; i++){
if( nums[i] != 13){
sum += nums[i];
if(i > 0 && nums[i-1] == 13)
sum -= nums[i];
}
}
return sum;
}
public static void main(String[] args) {
}
If I try to put System.out.println(sum13([1,2,2,1]) I am met with several errors relating to the [] as well as the ,. I cannot figure out, what it is that I've done wrong.
Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13, also do not count. sum13([1, 2, 2, 1]) →6
sum13([1, 1]) →2
I decided to add flag to know when the previous value was 13. In that way, you don't have to deal with edge cases.
public static int sum13(int[] nums) {
int sum = 0;
boolean was13 = false;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 13) {
was13 = true;
} else {
if(!was13)
sum += nums[i];
was13 = false;
}
}
return sum;
}
A possible solution with some test cases:
public static int sum13(int[] numbers)
{
int sum = 0;
int prev = 0;
for (var number : numbers)
{
if (number != 13 && prev != 13)
{
sum += number;
}
prev = number;
}
return sum;
}
public static void main(String[] args)
{
System.out.println(sum13(new int[]{}));
System.out.println(sum13(new int[]{1, 2, 3, 4, 5}));
System.out.println(sum13(new int[]{13, 1, 13, 13, 2, 3, 4, 5}));
}
I was given an assignment that made me create 3 methods that created an array, print an array, and count all the numbers divisible by 10 in a array. The part that is giving me the most trouble is counting the numbers divisible by 10. the is the code I have so far:
public int[] createArray(int size) {
Random rnd = new Random();
int[] array = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = rnd.nextInt(101);
}
return array;
}
public void printArray() {
Journal5a call = new Journal5a();
int[] myArray = call.createArray(10);
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
System.out.println("There are " + call.divideByTen(myArray[i]) + " numbers that are divisable by 10");
}
public int divideByTen(int num) {
int count = 0;
if (num % 10 == 0) {
count++;
}
return count;
}
public static void main(String[] args) {
Journal5a call = new Journal5a();
Random rnd = new Random();
call.printArray();
}
Pass an array to the method, and use that for determining the count. Your algorithm looks reasonable. Something like,
public int divideByTen(int[] nums) {
int count = 0;
for (int num : nums) {
if (num % 10 == 0) {
count++;
}
}
return count;
}
or, in Java 8+, use an IntStream and filter like
return (int) IntStream.of(nums).filter(x -> x % 10 == 0).count();
Then you can call it like
System.out.println("There are " + call.divideByTen(myArray)
+ " numbers that are divisible by 10");
or with printf and inline like
System.out.printf("There are %d numbers that are divisible by 10.%n",
IntStream.of(nums).filter(x -> x % 10 == 0).count());
You can do it this way. Pass full array and then check for division by 10. Skipped other part for simplicity.
public void printArray() {
Journal5a call = new Journal5a();
int[] myArray = call.createArray(10);
divideByTen(myArray);
}
public int divideByTen(int[] num) {
int count = 0;
for(i=0;i<num.length;i++)
{
if (num[i] % 10 == 0) {
count++;
}
}
return count;
}
I have an array of numbers in Java and need to output the ones that consist of only duplicated digits. However, my code throws an ArrayIndexOutOfBoundsException. Where is the problem?
int[] inputValues= {122, 2, 22, 11, 234, 333, 000, 5555, 8, 9, 99};
for (int i = 0; i < inputValues.length; i++) {
int numberLength = Integer.toString(inputValues[i]).length();
// System.out.println(numberLength);
if (numberLength > 1) { //more than one digit in the number
String s1 = Integer.toString(inputValues[i]);
String[] numberDigits = s1.split("");
for (int j = 1, k = 1; j < numberDigits.length; k++) {
if (numberDigits[j].equals(numberDigits[k + 1])) {
System.out.println("Duplicate values are:");
//I need to print 22,11,333,000,5555,99
}
}
}
}
There is no condition to stop the inner loop when k gets too big. j never changes in the inner loop, so j < numberDigits.length will either always be true or always be false.
public static void main(String[] args) {
int[] inputValues={122,2,22,11,234,333,000,5555,8,9,99,1000};
System.out.println("Duplicate values are:");
for (int i = 0; i < inputValues.length; i++) {
String strNumber = new Integer(inputValues[i]).toString();// get string from array
if(strNumber.length()>1) // string length must be greater than 1
{
Character firstchar =strNumber.charAt(0); //get first char of string
String strchker =strNumber.replaceAll(firstchar.toString(), ""); //repalce it with black
if(strchker.length()==0) // for duplicate values length must be 0
{
System.out.println(strNumber);
}
}
}
/*
* output will be
* Duplicate values are:
22
11
333
5555
99
*
*
*/
}
This is what you want.....
This line is the culprit here -
for (int j = 1, k = 1; j < numberDigits.length; k++) {
if (numberDigits[j].equals(numberDigits[k + 1])) {
System.out.println("Duplicate values are:");//i need to print 22,11,333,000,5555,99,etc.
}
}
The loop has a condition that's always true as value of j is always 1. Since k keeps on increasing by 1 for each iteration ( which are infinite btw ), the index goes out of array bounds.
Try -
for (int j = 0, k = 1; k < numberDigits.length; k++) {
boolean isDuplicate = true;
if (!numberDigits[j].equals(numberDigits[k])) {
isDuplicate = false;
break;
}
}
if( isDuplicate ) {
System.out.println("Duplicate values are:"+inputValues[i]);
}
Sorry for joining the party late. I think following is the piece of code you’re are looking for
private int[] getDuplicate(int[] arr) {
ArrayList<Integer> duplicate = new ArrayList<Integer>();
for (int item : arr) {
if(item > 9 && areDigitsSame(item)) {
duplicate.add(item);
}
}
int duplicateDigits[] = new int[duplicate.size()];
int index = 0;
for (Integer integer : duplicate) {
duplicateDigits[index ++] = integer;
}
return duplicateDigits;
}
public boolean areDigitsSame(int item) {
int num = item;
int previousDigit = item % 10;
while (num != 0) {
int digit = num % 10;
if (previousDigit != digit) {
return false;
}
num /= 10;
}
return true;
}
Now , use it as below
int[]inputValues={122,2,22,11,234,333,000,5555,8,9,99};
int[] duplicates = getDuplicate(inputValues);
That's all
Enjoy!
public static void main(String[] args) {
String[] inputValues={"122","2","22","11","234","333","000","5555","8","9","99"};
System.out.println("Duplicate values are:");
for (int i = 0; i < inputValues.length; i++) {
String strNumber = inputValues[i];// get string from array
if(strNumber.length()>1) // string length must be greater than 1
{
Character firstchar =strNumber.charAt(0); //get first char of string
String strchker =strNumber.replaceAll(firstchar.toString(), "0"); //repalce it with 0
if(Integer.parseInt(strchker)==0) //if all values are duplictae than result string must be 0
{
System.out.println(strNumber);
}
}
}
}
// /// result will be
/* Duplicate values are:
22
11
333
000
5555
99
*/
if you want int array then you will not able to get "000" as duplicate value.
# line 13: the s1.split("") results to [, 1, 2, 2] for 122 . Hence your numberDigits.length is 4. The loop runs from j = 1 to 3 ( j < numberDigits.length); hence the numberDigits[k + 1 ] is evaluated for index 4 which is unavailable for [, 1, 2, 2].
Another point is worth noting is int[]inputValues will always store 000 as 0 only.
The below mentioned method will take a integer number and will return true and false based on your requirement. It will use xor operator to check repetitive digits.
private static boolean exorEveryCharacter(int currentValue) {
int result = 0;
int previousNumber = -1;
while (currentValue != 0) {
int currentNumber = currentValue % 10;
if(previousNumber == -1){
previousNumber = currentNumber;
}
else{
result = previousNumber ^ currentNumber;
}
currentValue /= 10;
}
return result == 0;
}
I need to write a function that recieve from the user a number(n), and the function return an array with all the prime numbers until the user number(n).
I know how to write the function that check if number is prime, but i dont know how to enter the numbers to an array.. for example if the user entered 53, it will return [2 ,3 ,5 ,7 ,11 ,13 ,17 ,19 ,23 ,29 ,31 ,37 ,41 ,43 ,47 ,53].
I forgot to tell that the language is java.. my bad!
Here is the code
private ArrayList getPrimeNumbers(int number)
{
ArrayList primeNumbers = new ArrayList();
for (int i = 0; i <= number; i++)
{
if(isPrime(i))
{
primeNumbers.add(i);
}
}
return primeNumbers;
}
private boolean isPrime(int n)
{
for(int i=2;i<n;i++)
{
if(n%i==0)
return false;
}
return true;
}
Usually, you can't change array length, so you should use the appropriate
collection where you can add items; that is List<> in C#, ArrayList<> in Java etc.
Technically, you can implement separate IsPrime method and then check the integers in 2..max range, but here it can just be inlined.
Possible code in C#
public static int[] GetPrimes(int max) {
if (max <= 1)
return new int[0];
else if (max == 2) // <- let's process the only even prime (2) separately
return new int[] { 2 };
List<int> primes = new List<int>() { 2, 3 };
// Sieve through odd numbers:
for (int i = 5; i <= max; i += 2) {
int sqrt = (int) Math.Sqrt(i + 1);
Boolean isPrime = true;
// There's no need to check if (i % primes[0] == 0):
// primes[0] == 2, and loop is for odd numbers - 5, 7, 9,...
for (int j = 1; primes[j] <= sqrt; ++j)
if ((i % primes[j]) == 0) {
isPrime = false;
break;
}
if (isPrime)
primes.Add(i);
}
return primes.ToArray();
}
// ....
// Test will return the string
// "2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53"
String result = String.Join(", ", GetPrimes(53).Select(x => x.ToString()));
Here is one way to do it (you did not specify language, so I'm using Python):
def GetPrimes(n):
array = []
for i in range(2,n+1):
if IsPrime(i):
array.append(i)
return array
def IsPrime(n):
for i in range(2,n/2+1):
if n % i == 0:
return False
return True
print GetPrimes(53)
The following code will work, Give it a try
package CoreJava;
public class prime {
public static void main(String[] args) {
int a [] ={1, 2, 3, 7, 23,7,10};
int flag=0;
for(int i=0;i<a.length-1;i++)
{
if((a[i]!=0) &&(a[i]!=1))
{
for(int j=2;j<a[i];j++)
{
if(a[i]%j==0)
{
flag=1;
break;
}
}
if(flag==0)
{
System.out.println(a[i]);
}
}
}
}
}