Creating a random generated array in method and printing it - java

So I'm pretty sure I've correctly created a random integer generator that will put the integers into an array, although I am having trouble with my second method, that is supposed to print out the array.
My code:
import java.util.Random;
import java.util.Scanner;
public class Engine {
public int numDigits, numDigitsSet;
public int i;
public int[] secretNumber;
public Random randomNumberGenerator;
Scanner sc = new Scanner(System.in);
public void setNumDigits()
{
numDigitsSet = numDigits;
}
public int getNumDigits()
{
System.out.print("Enter the number of digits to use: ");
return numDigits = sc.nextInt();
}
public void generateNewSecret()
{
Random rand = new Random();{
for (int i=0; i<numDigitsSet; i++)
{
secretNumber[i]= rand.nextInt(10);
System.out.println("" + secretNumber[i]);
}
}
}
public int[] getSecretNumber()
{
for (int j=0; j<secretNumber.length; j++)
{
System.out.println("" + secretNumber[j]);
}
return secretNumber;
}
public void convertNumtoDigitArray()
{
String[] userGuessSplit = Player.userGuess.split(",");
int[] userGuessArray = new int[userGuessSplit.length];
for (int j=0; j<userGuessSplit.length; j++)
{
userGuessArray[j] = Integer.parseInt(userGuessSplit[j]);
}
}
}

For printing out the array, you can use the seriously convenient
Arrays.toString(array);
JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(int[])

Related

To find the single digit sum of palindrome numbers in array

I tried to check the palindrome number and find the single digit sum of the palindrome numbers, but my code is not returning the proper value (I am finding it difficult to return the value of sum from the loops). Can anyone help me getting the mistake. Any help will be appriciated.
import java.util.Scanner;
public class SumOfPalindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
System.out.println(SumOfPalindromeNumber(inp));
}
private static int SumOfPalindromeNumber(int[] inp )
{
int sumpal =0;
for(int i = 0; i<inp.length;i++)
{
int rem =0;
int sum = 0;
while(inp[i]!=0)
{
rem = inp[i]%10;
sum=(sum*10)+rem;
inp[i]/=10;
}
if(inp[i]==sum)
{
sumpal+=inp[i];
if(sumpal>9)
{
sumpal=singledigitsum(sumpal);
}
}
}
return sumpal;
}
private static int singledigitsum(int sumpal)
{
int rem1 = 0;
int sum1 = 0;
while(sumpal!=0)
{
rem1=sumpal%10;
sum1+=rem1;
sumpal/=10;
}
if(sum1>9)
{
sum1=singledigitsum(sum1);
}
return sum1;
}
}
Enter numbers
Check which numbers are palindromes.
If that number is a palindrome then find sum of its digits.
Code:
import java.util.Scanner;
public class SumOfPalindrome {
public static void main(String[] args) {
SumOfPalindrome sumOfPalindrome=new SumOfPalindrome();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
for(int i=0;i<n;i++)
{
if(sumOfPalindrome.isPallindrone(inp[i]))
{
System.out.println("No -> "+inp[i]+" Sum->"+sumOfPalindrome.sumOfDigits(inp[i]));
}
}
}//
public boolean isPallindrone(int no)
{
int r,sum=0,temp;
temp=no;
while(no>0){
r=no%10; //getting remainder
sum=(sum*10)+r;
no=no/10;
}
if(temp==sum)
{
return true;
}
else
{
return false;
}
}
public int sumOfDigits(int no)
{
int sum = 0;
while (no != 0)
{
sum = sum + no % 10;
no = no/10;
}
return sum;
}
}
I did not understand the purpose of sumpal in your code. You wanted a method which return sumOfPalindromes in an array. I commented the part which was wrong.
import java.util.Scanner;
public class SumOfPalindrome_1
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
//System.out.println(SumOfPalindromeNumber(inp));
SumOfPalindromeNumber(inp);
}
private static void SumOfPalindromeNumber(int[] inp )
{
int sumpal =0;
for(int i = 0; i<inp.length;i++)
{
int rem =0;
int sum = 0;
while(inp[i]!=0)
{
rem = inp[i]%10;
sum=(sum*10)+rem;
inp[i]/=10;
}
if(inp[i]==sum)
{
// sumpal+=inp[i];
/*if(sumpal>9)
{
sumpal=singledigitsum(sumpal);
}
*/
System.out.println(singleDigitSum(inp[i]));
}
}
}
private static int singleDigitSum(int sumpal)
{
int rem1 = 0;
int sum1 = 0;
while(sumpal!=0)
{
rem1=sumpal%10;
sum1+=rem1;
sumpal/=10;
}
if(sum1>9)
{
sum1=singleDigitSum(sum1);
}
return sum1;
}
}
Apologies if this is not the case but this seems like you are looking for answers to a coding test.

why am I getting the cannot find symbol when passing an array into a method

can someone please tell me why I am getting this error when compiling?
import java.util.*;
import java.io.*;
public class StatsCalculator
{
public static void main (String[]args)
{
programHeader();
randomNo(random);
printArray(random);
}
public static void programHeader()//writes program header
{
System.out.println("****************");
System.out.println("Stats calculator");
System.out.println("****************");
}
public static int[] randomNo(int[] random)// fills an array with 10 random numbers
{
random = new int[10];
for (int i=0; i< random.length; i++){
int randomNumber= (int) (Math.random()*10)+1;
random[i] = randomNumber;
}
return random;
}
public static int[] printArray (int[] random)//prints array
{
System.out.println("Your ten random values are: ");
for (int i=0; i<random.length; i++){
System.out.print(Arrays.toString(random));
}
return random;
}
}
I am writing a simple program to fill and array with 10 random numbers 1-10 and then calculate the sum, mean, mode and median of all the random numbers but i can get the methods to work just to fill the array and to print the array.
any help is appreciated.
You should get return value of randomNo() then pass it to next method. This may help you:
import java.util.Arrays;
public class StatsCalculator {
public static void main(String[] args) {
programHeader();
int[] random = randomNo();
printArray(random);
}
public static void programHeader()//writes program header
{
System.out.println("****************");
System.out.println("Stats calculator");
System.out.println("****************");
}
public static int[] randomNo()// fills an array with 10 random numbers
{
int[] random = new int[10];
for (int i = 0; i < random.length; i++) {
int randomNumber = (int) (Math.random() * 10) + 1;
random[i] = randomNumber;
}
return random;
}
public static int[] printArray(int[] random)//prints array
{
System.out.println("Your ten random values are: ");
for (int i = 0; i < random.length; i++) {
System.out.print(Arrays.toString(random));
}
return random;
}
}

Array not printing or going into array?

So I have to generate an array (size inputed by User) with a limit of 0-9; but each time I try to
Array.toString()
it compiles with error. Even when I imported arrays that the compiler states that I can't import or resolve.
Start
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Frequency
{
int var1,var2,var3,var4,max,min,var5,var6,var7,var8;
int [] a;
Scanner dab = new Scanner(System.in);
public void rand()
{
Random rande = new Random();
System.out.println("How many Random Values ");
var1 = dab.nextInt();
for (int k = 0; k > var1; k++)
{
a[k] = (int)(Math.random() * 10);
}
System.out.println(Arrays.toString(a));
}
}
Tester:
public class FrequencyTester
{
public static void main(String[]args)
{
Frequency yeet = new Frequency();
yeet.rand();
System.out.println("test");
}
}
Your first mistake is in For loop k must be less than var1
for (int k = 0; k < var1; k++)
try this
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
class Frequency
{
int var1,var2,var3,var4,max,min,var5,var6,var7,var8;
int [] a;
Scanner dab = new Scanner(System.in);
public void rand()
{
Random rande = new Random();
System.out.println("How many Random Values ");
var1 = dab.nextInt();
a=new int[var1];
for (int k = 0; k < var1; k++)
{
a[k] = (int)(Math.random() * 10);
}
System.out.println(Arrays.toString(a));
}
}
public class FrequencyTester
{
public static void main(String[]args)
{
Frequency yeet = new Frequency();
yeet.rand();
System.out.println("test");
}
}

Implementing merge sort in java 7

I have a problem with implementation of merge sort in java. I am looking for the error almost week unfortunately without result. ArrayList at the entrance is the same as the output.
import java.util.ArrayList;
import java.util.Scanner;
public class MergeSort
{
private ArrayList<Integer> basicArrayList = new ArrayList<Integer>();
ArrayList<Integer> arrayListA = new ArrayList<Integer>();
ArrayList<Integer> arrayListB = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
private int firstIndexOfArrayList = 0;
private int lastIndexOfArrayListA;
private int lastIndexOfArrayListB;
public void Scal(ArrayList<Integer> basicArrayList, int p, int q, int r) {
this.firstIndexOfArrayList = p;
this.lastIndexOfArrayListA = q;
this.lastIndexOfArrayListB = r;
int numberOfElementsArrayListA = lastIndexOfArrayListA
- firstIndexOfArrayList + 1;
int numberOfElementsArrayListB = lastIndexOfArrayListB
- lastIndexOfArrayListA;
for (int i = 0; i < numberOfElementsArrayListA; i++) {
arrayListA.set(i, basicArrayList.get(firstIndexOfArrayList + i));
}
for (int j = 0; j < numberOfElementsArrayListB; j++) {
arrayListB.set(j, basicArrayList.get(lastIndexOfArrayListA + j));
}
arrayListA.add(Integer.MAX_VALUE);
arrayListB.add(Integer.MAX_VALUE);
int i = 0;
int j = 0;
for (int k = firstIndexOfArrayList; k <= lastIndexOfArrayListB; k++) {
if (arrayListA.get(i) <= arrayListB.get(j)) {
basicArrayList.set(k, arrayListA.get(i));
i = i + 1;
} else {
basicArrayList.set(k, arrayListB.get(j));
j = j + 1;
}
}
}
public void MergeSort(ArrayList basicArrayList, int p, int r) {
this.firstIndexOfArrayList = p;
this.lastIndexOfArrayListB = r;
if (firstIndexOfArrayList < lastIndexOfArrayListB) {
int lastIndexOfArrayListA = (firstIndexOfArrayList + lastIndexOfArrayListB) / 2;
MergeSort(basicArrayList, firstIndexOfArrayList,
lastIndexOfArrayListA);
MergeSort(basicArrayList, lastIndexOfArrayListA + 1,
lastIndexOfArrayListB);
Scal(basicArrayList, firstIndexOfArrayList,
lastIndexOfArrayListA,
lastIndexOfArrayListB);
}
}
public void setSize() {
System.out.println("Enter the number of elements to sort: ");
this.lastIndexOfArrayListB = input.nextInt();
}
public int getSize() {
return lastIndexOfArrayListB;
}
public void setData() {
System.out.println("Enter the numbers: ");
for (int i = 0; i < lastIndexOfArrayListB; i++) {
int number;
number = input.nextInt();
basicArrayList.add(number);
}
}
public void getTable() {
System.out.println(basicArrayList.toString());
}
public static void main(String[] args) {
MergeSort output = new MergeSort();
output.setSize();
output.setData();
output.MergeSort(output.basicArrayList,
output.firstIndexOfArrayList, (output.getSize() - 1));
output.getTable();
}
}
In terms of fixing your code I had a crack at it and as far as I can tell this seems to work. To do this a lot of your code had to be changed but it does now sort all Integers properly
import java.util.ArrayList;
import java.util.Scanner;
public class MergeSort
{
private ArrayList<Integer> basicArrayList = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
private int numbersToSort;
public void doMergeSort(int firstIndexOfArrayList,int lastIndexOfArrayListB, ArrayList<Integer> arrayList)
{
if(firstIndexOfArrayList<lastIndexOfArrayListB && (lastIndexOfArrayListB-firstIndexOfArrayList)>=1)
{
int mid = (lastIndexOfArrayListB + firstIndexOfArrayList)/2;
doMergeSort(firstIndexOfArrayList, mid, arrayList);
doMergeSort(mid+1, lastIndexOfArrayListB, arrayList);
Scal(firstIndexOfArrayList,mid,lastIndexOfArrayListB, arrayList);
}
}
public void Scal(int firstIndexOfArrayList,int lastIndexOfArrayListA,int lastIndexOfArrayListB, ArrayList<Integer> arrayList)
{
ArrayList<Integer> mergedSortedArray = new ArrayList<Integer>();
int leftIndex = firstIndexOfArrayList;
int rightIndex = lastIndexOfArrayListA+1;
while(leftIndex<=lastIndexOfArrayListA && rightIndex<=lastIndexOfArrayListB)
{
if(arrayList.get(leftIndex)<=arrayList.get(rightIndex))
{
mergedSortedArray.add(arrayList.get(leftIndex));
leftIndex++;
}
else
{
mergedSortedArray.add(arrayList.get(rightIndex));
rightIndex++;
}
}
while(leftIndex<=lastIndexOfArrayListA)
{
mergedSortedArray.add(arrayList.get(leftIndex));
leftIndex++;
}
while(rightIndex<=lastIndexOfArrayListB)
{
mergedSortedArray.add(arrayList.get(rightIndex));
rightIndex++;
}
int i = 0;
int j = firstIndexOfArrayList;
while(i<mergedSortedArray.size())
{
arrayList.set(j, mergedSortedArray.get(i++));
j++;
}
}
public void setSize()
{
System.out.println("Enter the number of elements to sort: ");
this.numbersToSort = input.nextInt();
}
public int getSize()
{
return numbersToSort;
}
public void setData()
{
System.out.println("Enter the numbers: ");
for (int i = 0; i < numbersToSort; i++)
{
int number;
number = input.nextInt();
basicArrayList.add(number);
}
}
public void getTable()
{
System.out.println(basicArrayList.toString());
}
public void runSort(ArrayList<Integer> arrayList)
{
doMergeSort(0, this.numbersToSort-1, arrayList);
}
public static void main(String[] args)
{
MergeSort output = new MergeSort();
output.setSize();
output.setData();
output.runSort(output.basicArrayList);
output.getTable();
}
}
Try this code. The following code takes an ArrayList input and outputs an ArrayList as well so it still works along the same basis of your code. The actual sort is handled in a different class MergeSort and is passes into ForMergeSort. Hope this helps
MergeSort.java
public class MergeSort
{
private int[] array;
private int[] tempMergArr;
private int length;
public void sort(int[] inputArr)
{
}
public int[] getSortedArray(int[] inputArr)
{
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
for(int i=0;i<length;i++)
{
int correctNumber = i+1;
System.out.println("Value "+correctNumber+" of the sorted array which was sorted via the Merge Sort is: "+inputArr[i]);
}
return inputArr;
}
private void doMergeSort(int lowerIndex, int higherIndex)
{
if (lowerIndex < higherIndex)
{
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
doMergeSort(lowerIndex, middle);
doMergeSort(middle + 1, higherIndex);
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex)
{
for (int i = lowerIndex; i <= higherIndex; i++)
{
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex)
{
if (tempMergArr[i] <= tempMergArr[j])
{
array[k] = tempMergArr[i];
i++;
}
else
{
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle)
{
array[k] = tempMergArr[i];
k++;
i++;
}
}
}
ForMergeSort.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ForMergeSort
{
ArrayList<Integer> arrayList = new ArrayList<Integer>();
ArrayList<Integer> sortedArrayList = new ArrayList<Integer>();
MergeSort mS = new MergeSort();
public void buildArrayList()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements to sort: ");
int toSort = input.nextInt();
System.out.println("Enter the numbers: ");
for(int i =0; i<toSort; i++)
{
int number = input.nextInt();
arrayList.add(number);
}
}
public void runMergeSort(ArrayList<Integer> arrayList)
{
int[] arrayOfValues = new int[arrayList.size()];
int i = 0;
for(int a:arrayList)
{
arrayOfValues[i] = a;
i++;
}
MergeSort mS = new MergeSort();
for(int intOfArray:mS.getSortedArray(arrayOfValues))
{
sortedArrayList.add(intOfArray);
}
System.out.println(sortedArrayList.toString());
}
public static void main(String[] args)
{
ForMergeSort fMS = new ForMergeSort();
fMS.buildArrayList();
fMS.runMergeSort(fMS.arrayList);
}
}

Adding results from loop into Array?

I am currently just mocking about with Java. To get some learning in, and of course the easiest way to learn is by asking.
In this section I've created a loop to give me 50 random numbers. What I want to do, is to compare these numbers later on. That's why I want to move all the numbers into an array. I have no clue how. I've tried different stuff, but my syntax is wrong. Can somebody tell me how to do this?
Code:
package project.main;
import java.util.Random;
public class Main {
public static int numbers[];
public static final void main(String []args) {
getRandom();
recheckNumbers();
}
public static void getRandom() {
Random RandomNumber = new Random();
for(int i = 1; i <= 50; ++i){
int randomInt = RandomNumber.nextInt(100);
System.out.println("Generated : " + randomInt);
}
}
public static void recheckNumbers() {
if(numbers[0] < numbers[1]) {
System.out.println("numbers[0] is biggest");
} else {
System.out.println("numbers[1] is biggest");
}
}
}
I just rewrote it a bit. Im now running into another issue at line 14. which is the numbers[i] = randomInt part.
Heres the new code..
package project.main;
import java.util.Random;
public class Main {
public static int numbers[];
public static final void main(String []args) {
Random RandomNumber = new Random();
for(int i = 0; i <= 49; ++i){
int randomInt = RandomNumber.nextInt(100);
numbers[i] = randomInt;
}
}
}
for(int i = 0; i <= 49; ++i){
int randomInt = RandomNumber.nextInt(100);
numbers[i] = randomInt;
System.out.println("Generated : " + randomInt);
}
After that you can loop through to get number
for(int i = 0; i <= 49; ++i){
System.out.println("Generated : " + numbers[i]);
}
Solution to new question
import java.util.Random;
public class Main {
public static int[] numbers = new int[50];
public static void main(String[] args) {
Random RandomNumber = new Random();
for(int i = 0; i <= 49; ++i){
int randomInt = RandomNumber.nextInt(100);
numbers[i] = randomInt;
}
}
}
The solution lemon provided is correct.
Additionally I want to point you to a mistake you did in your recheckNumbers method. You check if numbers[0] is smaller than numbers[1] and print out that numbers[0] is the biggest in the if block. You should switch the output from the if and else block to return the correct answer.
You need to say the size of the array. Here is my solution to your problem:
public class Main {
public static int numbers[] = new int[50];
public static void main(String[] args) {
getRandom();
recheckNumbers();
}
public static void getRandom(){
Random randomNumber = new Random(); // variables should start with lower case
for(int i = 0; i < 50; i++){
int randomInt = randomNumber.nextInt(100); // generate a random integer in the (0-99) interval
System.out.println("Generated: " + randomInt); // print the generated number
numbers[i] = randomInt; // put it in the array
}
}
public static void recheckNumbers(){
if(numbers[0] > numbers[1]){
System.out.println("numbers[0] is bigger");
} else {
System.out.println("numbers[1] is bigger");
}
}
}
Hope it helps :)

Categories

Resources