Trying to pass an array to a different class in Java [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm creating a lottery program and trying linked lists for the first time. I'm passing the numbers array from the Player class to the Lottery class so that I can display the current players Numbers, but it keeps giving me the error "actual and formal parameters differ in length".
There will be another class which will be made for the winning numbers but I'm trying to fix this issue first. I'm unsure how to fix this as I've been stuck for quite a while now.
Any help would be much appreciated.
This is the piece of code I'm having trouble with, this is in the Lottery class in the displayPlayers() method -
for(int i = 0; i < 6; i++) {
System.out.println(currentPlayer.getNumbers(i));
}
public class LOTTERY
{
Scanner keyboard = new Scanner(System.in);
private PLAYER pHead;
public LOTTERY()
{
pHead = null;
}
public void displayPlayers() {
PLAYER currentPlayer = pHead;
System.out.println("Name: " + currentPlayer.getName());
System.out.println("Age: " + currentPlayer.getAge());
currentPlayer.randNum();
System.out.println("Your Numbers: ");
for(int i = 0; i < 6; i++) {
System.out.println(currentPlayer.getNumbers(i));
}
menu();
}
public void runProg() {
displayPlayers();
}
public static void main(String[] args) {
LOTTERY lottery = new LOTTERY();
lottery.runProg();
}
}

The method getNumbers() does not take an parameters but you are trying to pass it i. Additionally, this method returns an array, so you want to get this before the loop iteration, then iterate through it.
You can do this easily using an enhanced for loop:
for (int currentNum : currentPlayer.getNumbers()) {
System.out.println(currentNum);
}
Or with a standard for loop:
int [] arr = currentPlayer.getNumbers();
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}

The error you are getting says it all, the method you wrote takes no parameters. When you call your getNumbers() method, you pass it the value of i, though java does not expect that, since you declared the method without any parameters.

Related

Sorting a 1d array of Objects from a file in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
Good Afternoon, I have a final project to do and need some help. I would just like to grasp the algorithm of sorting a 1d array of objects from a file. I know how to do it with a regular array using a counter in a for loop or a for each loop. I'm having difficulty reproducing it with with my objects. Thanks in advance.
public static void printFile()throws IOException {
File f = new File("program7b.txt");
Scanner in = new Scanner(f);
int count = 0;
Customer[] obj = new Customer[in.nextInt()];
while(in.hasNext() ){
int id = in.nextInt();
String name = in.next();
String email = in.next();
double balance = in.nextDouble();
in.nextLine();
obj[count] = new Customer (id, name, email, balance);
count++;
}
in.close();
for (int i = 0; i < count; i++){
System.out.println(obj[i]);
if (obj[i] instanceof TaxExempt){
System.out.println("Tax Type: " + ((TaxExempt)obj[i]).getExempt());
}
}
}
public static void sortCust(Customer[] id){
int temp = 0;
for (int i = 1; i < id.length-1; i++){
}
}
In my experience, you would use a compareTo method in the class of the object. Since objects can have multiple instance variables and other objects within them, you have to pick a specific field to sort on.
Say you have an object (Account) with a person's name and bank balance. You would want to sort by bank balance.
public int compareTo(Account a){
if(balance<a.getBalance())
return -1;
if(balance==a.getBalance())
return 0;
else
return 1;
}
Now that you have a compare to, you can bubble sort/quick sort/selection sort (I barely even know what those mean anymore), just like you would with an array of ints.
The biggest difference is that your condition will specify object.compareTo(otherObject) and will be based on if it is <0, ==0, or >0.
Be careful when you are moving objects though. You want to make sure to do a deep copy of all the details in the objects, not just copy the objects. For this reason, I recommend a swap method and a copy method.
Good Luck!

How does one make a method with an Iterable return type in Java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So I am new to coding. I've done web design and smaller projects but they were mostly straightforward. My friend referred me to try asking questions here on Stack Overflow.
I recently came across the following
So I've never studied algorithms to this extent yet alone in java until a few months ago. I am trying to self-teach java and the more theoretical side of computer science. I want to prove myself(and to a certain gaslighting acquaintance of mine) that I can do it. However, I have reached a point where I'm too frustrated with myself to continue trying.
This is what I have so far:
package ColinearPt;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.NoSuchElementException;
public class BruteCollinearPoints {
Point[] pointArray;
ArrayList<PointSequence> pSeqArr = new ArrayList<>();
public BruteCollinearPoints(Point[] points) {
if (points == null)
throw new NullPointerException();
pointArray = points.clone();
Arrays.sort(pointArray);
for (int p = 0; p < pointArray.length - 3; p++) {
for (int q = p + 1; q < pointArray.length - 2; q++) {
for (int r = q + 1; r < pointArray.length - 1; r++) {
for (int s = r + 1; s < pointArray.length; s++) {
Point[] four = { pointArray[p], pointArray[q], pointArray[r], pointArray[s] };
PointSequence pseq = new PointSequence(four);
if (pseq.isCollinear()) {
pSeqArr.add(pseq);
}
}
}
}
}
}
//makes a defensive copy of the array of points
public int numberOfPoints() {
//returns the number of total points in the array
return pointArray.length;
//numberOfPoints();
}
public int numberOfSegments() {
return pSeqArr.size();
//returns the number of segments of length 4
}
public Iterable<PointSequence> segments() {
//returns an iterable of segments of length 4
}
public static void main(String[] args) {
//draws all 4 point segments in file
}
}
I am especially confused with segments(), and since I don't know all the testing details, I'm not even sure what I am looking for. I've been reading up on Iterables but I'm still confused. I would really appreciate any tips on this particular project or even just how to study computer science on one's own.
Because internally Collection<E> extends Iterable<E> so you can simply cast can collection to Iterable
Like below:
public Iterable<PointSequence> segments() {
//returns an iterable of segments of length 4
List<PointSequence> pSeqArr = new ArrayList<>();
//add your logic
return pSeqArr;
}

Working with integer array in Java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
The output of this array shows a compilation error, if only the a2.SumOfArray({12}, 12);
is commented, it compiles. How do I put it in an array form and get a working output?
Thank you.
import java.util.Scanner;
class Calculation
{
Scanner myScanner = new Scanner(System.in);
int total, I;
int SumOfArray(int data[], int size){
System.out.print("Enter size of array: ");
size = myScanner.nextInt();
for(i=0; i<=size; i++){
System.out.println("Enter number: ");
data[i]=myScanner.nextInt();
total=total+data[i];
}
System.out.println("Sum of Array: "+ total);
return total;
}
public class Main
{
public static void main(String args[]){
Calculation a2 = new Calculation();
**a2.SumOfArray({12}, 12);**
}
}
Simply replace :
a2.SumOfArray({12}, 12);
With
a2.SumOfArray(new int[]{12}, 12);
However, your code has compilation issue try to find those and fix that.
With first glance at your code, there are couple mistakes: (they are not specific to Java8 btw)
your SumOfArray is taking two int for input not array. Change SumOfArray(int data[], int size) to SumOfArray(int[] data, int size) to take a int[] array for input. In java int[] means an int array.
then you need to pass in your array like this a2.SumOfArray(new int[]{1,2,3}, 12); you need the keyword new so the java compiler knows to reserve memory for this new array and you need the int[] to tell the compiler this is an int array.

How to reason about the complexity of my code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i did some coding in java to find a missing number know my code is working. i have basic knowledge about how to check the complexity of the program and i have keen interest to learn about how can i do that please any one help me or suggest me to read some good tutorial. or help me to know somthing about asymptotic complexity related to my code. Thank You.
here is my code
Scanner s1=new Scanner(System.in);
System.out.println("Enter No:");
int length=s1.nextInt();
boolean isExit=false;
int []a=new int[length-1];
System.out.println("Enter all no");
for(int i=0;i<length-1;i++){
a[i]=s1.nextInt();
}
for (int i = 1; i<=length; i++) {
for (int j = 0; j < a.length; j++) {
if(i==a[j]){
isExit =true;
break;
}
}
if (!isExit) {
System.out.println(i);
//break;
}
isExit = false;
}
}
}
I'm not sure if you're specifically trying to learn to do it all by hand? If not it's relatively easy to use streams to find the missing number:
Arrays.sort(array);
IntStream.range(0, array.length).filter(n -> !n.equals(array[n])).findAny();
That returns an Optional<Integer> which can then be tested to see if any missing number is present.
Read this : http://en.wikipedia.org/wiki/Big_O_notation
What you are looking to learn for is called asymptotic complexity.
A good video : Youtube
Also check out this answer
What is a plain English explanation of "Big O" notation?
In relation to your post :
for (int i = 1; i<=length; i++) {
for (int j = 0; j < a.length; j++) {
if(i==a[j]){
isExit =true;
break;
}
}
if (!isExit) {
System.out.println(i);
//break;
}
isExit = false;
}
Assuming that the operations inside your inner loop take constant time O(1).
If you think about this chunk of code in terms of code complexity you can notice that the outer loop will execute at most N(length) times and you can notice that the inner loop will execute N times too.Thus at most N^2 operations will be executed thus the upper bound of your algorithm is O(N^2) which means that the function N^2 will always be above the operations you make.

Comparing elements of two arrays in a for loop (java)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
It seems to be a very common question relating with arrays and comparing in java, however I couldn't find the right answer in all of these for my case.
In this application I am trying to make a program which 'encrypts' text given by the user. For example: user gives characters 'a b c' and the program returns it as '# # $'. But as you may notice I am having some issues in the code
"pozita[i] = j;".
Why won't this code work? It doesn't give me an error? Or is there anyway of doing it as "new pozita[i]" or anything like that?
Well, I'd be glad if someone could help me through. I am stuck for a while. Thanks in advance! :)
import java.util.*;
import javax.swing.*;
import java.awt.*;
public class TestPerProgram extends JFrame
{
char[] alfabeti = {'a','b','c','r','n','t'};
char[] kodimi = {'#','#','%','*','^','$'};
int[] pozita;
//Scanner merr = new Scanner(System.in);
String fn = JOptionPane.showInputDialog("Jepe tekstin:");
char[] input = fn.toCharArray();
void numro()
{
for (int i=0; i<=input.length; i++)
{
for(int j=0; j<=input.length; j++)
{
if(alfabeti[j] == input[i])
{
pozita[i] = j;
System.out.println(pozita[i]);
}
}
}
/*
for (int k=0; k<=input.length; k++)
{
System.out.println(pozita[k]);
}
*/
}
public static void main(String[] args)
{
TestPerProgram pjesa = new TestPerProgram();
pjesa.numro();
}
}
I'm not 100% clear on how your algorithm is supposed to work, but it seems you may want to replace the line
pozita[i] = j;
with
pozita[i] = kodimi[j];
Right now, you are only writing the matching index to pozita, not a replacement character.
If my assumption is correct, you would also change
int[] pozita;
to
char[] pozita;
and initialize it to an array of length input.Length.
You never instantiated the array pozita. After you instantiate pozita, you can then start overriding the values in pozita. You are assigning j to posita[i] , posita is null.
Do something like:
int posita[] = new int[20]
and if you don't want to set size then just use an arraylist.
You have not requested memory to be allocated for your variable pozita or otherwise instantiated it. The way you are currently using it, you would write pozita[] = new int[input.length]; at some point after retrieving your input from the user.

Categories