How can I put an array into a method? - arrays

I have to find the LCM of two integers using the prime factors method and function calls.
I'm up to making a function to find the prime factorization of the first number, but I'm getting errors at int x = first_number; and with System.out.print(primeFactorization).
This is my code so far:
import java.util.Scanner;
public class lcm {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int first_number;
int second_number;
System.out.print("Enter an integer: ");
first_number = reader.nextInt();
System.out.print("Enter another integer: ");
second_number = reader.nextInt();
}
public static int primeFactorization(int[] pfArray) {
int counter = 0;
pfArray = new int[10]; //created array in memory
int x = first_number;
for(int i=2;i<=x;i++){
while(x%i==0){
x=x/i;
pfArray[counter] = i;
++counter;
}
}
for(int i=0;i<counter;i++){
System.out.println(pfArray[i]);
}
}
System.out.println(primeFactorization);
}
I am just starting to learn Java, so please answer in very basic terms!
Thanks so much!

The variable first_number is declared in the first method and so cannot be used within the second method unless you pass it in as a parameter.
The only thing called primeFactorisation is the method. System.out.println requires an object (a variable) as its input. So you can't do it like that.

Related

Passing arrays between methods, and accessing them accordingly

I'm supposed to use two methods to hold arrays, then with the two arrays determine win % of the rockets, average margin of score difference for the games lost by Houston Rockets, and the lowest Houston Rockets’ score and the corresponding game number. I primarily need help with the first one, and I can get the other tasks. I just dont know how to pass arrays from methods very well. Any help would be useful, THanks!
import java.util.Scanner;
public class MorenoJonathonRocketsStatistics
{
public static void main(String[] args)
{
System.out.println("enter rockets game scores");
int[] rockets = rocketsScore();
System.out.println("enter opponents scores");
int[] opponents = opponentsScore();
int per = percent();
System.out.println("game win percent"+per+" %");
}
public static int[] rocketsScore()
{
Scanner sc = new Scanner(System.in);
int[] rocketsScore = new int[8];
for(int i=0;i<rocketsScore.length;i++)
{
rocketsScore[i] = sc.nextInt();
}
return rocketsScore;
}
public static int[] opponentsScore()
{
Scanner sc = new Scanner(System.in);
int[] opponentsScore = new int[8];
for(int i=0;i<opponentsScore.length;i++)
{
opponentsScore[i] = sc.nextInt();
}
return opponentsScore;
}
public static int percent(int[] array, int[] array2)
{
int[] rock = rocketsScore.length();
int[] opp = opponentsScore.length();
double percent=0;
int w=0, l=0;
for(int i=0; i<rocketsScore.length;i++)
{
if(rocketsScore[i]>opponentsScore[i])
{
w++;
}
else{
l++;
}
}
percent = w/l;
return percent;
}
}
To pass array in methods, you don't need to put any brackets beside the variable that is holding the array. So, you may want to do it like below:
int per = percent(rockets, opponents);

Write Point Array

I work on a trainigs code to compare the distance of an unspecific number of points from the zero point.
The error appears when i want to write the input point values into the Point array and i don't know how to handle it:
points[i].setLocation(x,y);
Error says: Exception in thread "main" java.lang.NullPointerException
at minDis.minDis.main(minDis.java:59)
I would be thankful for any advices.
import java.awt.Point;
import java.util.Scanner;
public class minDis {
private static final Point Point = null;
static double dis(Point p){
double dis= Math.sqrt(p.x*p.x+p.y*p.y);
return dis;
}
static double minDist(Point[] points, int anz){
double minimum= dis(points[0]);
for(int z=0; z<anz; z++){
if (dis(points[z]) < minimum)
minimum=dis(points[z]);
}
return minimum;
}
static double minDistPoint(Point[] points, int anz){
double minimum= dis(points[0]);
int DistPoint = 0;
for(int z=0; z<anz; z++){
if (dis(points[z]) < minimum)
minimum=dis(points[z]);
DistPoint=z;
}
return DistPoint;
}
public static void main(String[] args) {
Point points[]=null;
Scanner scan= new Scanner(System.in);
System.out.println("How many Points do you want to compare?");
int anz= scan.nextInt();
for(int i=0; i<anz; i++){
System.out.println("Type in Point "+anz);
System.out.println("X: ");
int x= scan.nextInt();
System.out.println("Y: ");
int y= scan.nextInt();
**points[i].setLocation(x,y);**
}
scan.close();
System.out.println("It is Point "+minDistPoint(points, anz)+" with a distance of "+ minDist(points, anz));
}
}
In your code snippet, you are not allocating memory for the Pointer Object array. That's why you are getting NullPointerException. Therefore, you need to allocate memory to the array of Point objects in your code.
But, remember when you create a array of objects like this,
Object[] arr = new Object[10];
Here you are just creating 10 Object References. Now, to do any operations with individual array elements, you need to allocate memory to each object also, For Example,
arr[i] = new Object();
So, use the following snippet as the corrected version for your code.
public static void main(String[] args) {
Point[] points;
Scanner scan= new Scanner(System.in);
System.out.println("How many Points do you want to compare?");
int anz= scan.nextInt();
points = new Point[anz];
for(int i=0; i<anz; i++) {
points[i] = new Point();
System.out.println("Type in Point "+anz);
System.out.println("X: ");
int x= scan.nextInt();
System.out.println("Y: ");
int y= scan.nextInt();
points[i].setLocation(x,y);
}
scan.close();
System.out.println("It is Point "+ minDistPoint(points, anz)+" with a distance of "+ minDist(points, anz));
}

Libgdx - How to get a specific item from an array?

I have a Player class which has
int number;
In main, I store them in Array.
Array<Player> players;
How can I get a player which has for example number=2?
This question is programming in general, and has several ways to do what you say, I recommend you look for OOP.
a solution, general, would encapsulate the variable, "creating getter and setter, you need, eg:
this a simple class;
private int number;
public Player(int num){
this.number = num;
}
public int getNumber (){
return number;
}
public void setNumber (int n){
this.number = n;
}
.
In your code for search you can use the solution, using a for, or an iterator
for (int a = 0; a < players.size(); a++){
int tmpNumber = players.get(a).getNumber();
if(tmpNumber == 2){
players.get(a); //the object array with index equal to
//the value of 'a', have, number 2 stored
//in the variable 'number'
}
}
but this question I think is a little matter of taste or needs you have
I'm going to make some assumptions to demonstrate it:
Let's assume you have a constructor in your Player class:
public Player(int num){
this.number = num;
}
And you have added some players in your arraylist:
players.add(new Player(1));
players.add(new Player(2));
players.add(new Player(3));
Now loop through your array and find the one where number == 2
for (int i = 0; i < players.size(); i++){
Player tmp = players.get(i);
if(tmp.number == 2){
System.out.println("Index of player number 2: " + players.indexOf(tmp));
}
}
I realised that I'd misunderstood the question with my previous answer. Here's a better one...
Those recommending you iterate through the Array are correct, but if you have a lot of Players this will be ineffeicient. In that case, it would be better to use a Map where the key was the player number, and the value is the player itself.
Here's some sample code showing the approach (most of it is just setting up some test data)...
import java.util.HashMap;
import java.util.Map;
public class Temp {
public static void main(String[] args) {
// Create a map instead of an array
Map<Integer, Player> players = new HashMap<>();
// Quick hack just to put some data in it.
for(int i = 0; i < 1000; i++) {
players.put(i, new Player(i));
}
// Once they're in a map, retrieving them is simple...
Player playerFromMap = players.get(537);
// Check we got it right
System.out.println(playerFromMap.getNumber()); // 537
}
private static class Player {
private int number;
private Player(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
}

Calculate the number of different digits in the integer

I'm practicing learning Java and I found this exercise online to input a long integer (ex 2827) and then calculate how many different digits there is in the integer (2,8 and 7) = 3 in this case.
I'm considering using a for loop and then with subString, comparing if the number equals each others and they (tutorial) suggest that I should use an array "used" to register which numbers appear, nonetheless
This is what I've got so far:
import java.util.Scanner;
public class UniqueInteger {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean[] used = new boolean[10];
int uniqueNbr = 0;
System.out.print("Input an integer: ");
String nbrString = String.valueOf(scan.nextLong());
for (int i = 0; i < nbrString.length(); i++) {
String bigI = String.valueOf(i);
if(nbrString.substring(i,(i+1)).equals(bigI)){
uniqueNbr++;
}
}
System.out.println("Amount of unique digits: " + uniqueNbr);
}
}
My problem is now that this code does not work, and I'm not sure I'm taking the right approach here. I've also not found a reason or purpose to include the boolean array "used".
What's wrong with my code?
How do I in a smart way use the boolean array and make my code more efficient?
You need to check if the current number in the string has been used (using your boolean array). If it hasn't been used, set used[num] to true and increment uniqueNbr.
import java.util.Scanner;
public class UniqueInteger {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean[] used = new boolean[10];
int uniqueNbr = 0;
System.out.print("Input an integer: ");
String nbrString = String.valueOf(scan.nextLong());
for (int i = 0; i < nbrString.length(); i++) {
int num = Character.getNumericValue(nbrString.charAt(i));
if(!used[num]) {
uniqueNbr++;
used[num] = true;
}
}
System.out.println("Amount of unique digits: " + uniqueNbr);
}
}

Random Array Sorting

Is it possible to sort (ascending) the randomly generated integer array for the following code? If, so how?
import java.util.Random;
public class RandomArraySorter {
public static void main(String args[]){
Random random = new Random();
int array[] = new int[10];
//number of integer spaces within the array:
for(int i = 0; i < 10; i++){
//random numbers from 1 to 100:
array[i] = random.nextInt(100) + 1;
System.out.print(array[i] + " ");
}
} //end of main
} //end of class
You can sort with:
Arrays.sort(array);

Resources