Calling method from another class that's an array - java

I am calling a method from another class. The method contains an integer array. I am trying to stay away from inputting the index manually.
I am trying to search for numbers within a range.
example:
ArrayList: {1,5}, {5,10}, {10,15}
Input: enter 3
Process: search for number within range
output: 1,5
The driver class is storing the objects from the main class called Numbers into ArrayList. The main class have an accessor call getNumbers. getNumbers contains an integer array with 2 elements. The driver is calling getNumbers to validate the entry that users input.
The code below works but I'm told it's consider bad coding to code entering the indexes. I want to know how to output the array from getNumber method without knowing the array length of getNumber?
example of what I have:
for(int i = 0; i < example.size(); i++)
//number is the integer that is inputted.
if(example.get(i).getNumbers()[1] > number &&
example.get(i).getNumbers()[0] <= numbers)
System.out.println(example.get(i));
Should I add another for loop?
example of what I am thinking of:
for(int i = 0; i < example.size(); i++)
for(int j = 0; j < example.get(i).getNumbers.length; j++){
if(example.get(i).getNumbers()[j] > number &&
example.get(i).getNumbers()[j] <= numbers)
System.out.println(example.get(i));
}
}
Edit: Changed how I worded some things and fixed the code of what I think I should do.

The code below works but I'm told it's consider bad coding to code
entering the indexes. I want to know how to output the array from
getNumber method without knowing the array length of getNumber ?
If you don't want to do the validations with array indexes for your first element and second element in the array, then you can solve the problem by modifying your Numbers class as shown below:
(1) Define two int variable members (currently you have only one)
(2) Add a method isInLimits(int input) to validate the range
(3) Override toString() which can be used to print the object as String
Numbers class (modified):
public static class Numbers {
private int firstElement;
private int secondElement;
public int getFirstElement() {
return firstElement;
}
public void setFirstElement(int firstElement) {
this.firstElement = firstElement;
}
public int getSecondElement() {
return secondElement;
}
public void setSecondElement(int secondElement) {
this.secondElement = secondElement;
}
//checks the input is in the range of this object elements
public boolean isInLimits(int input) {
if(input >= firstElement && input < secondElement) {
return true;
} else {
return false;
}
}
#Override
public String toString() {
return "{"+firstElement+","+secondElement+"}";
}
}
Usage of Numbers Class:
public static void main(String[] args) {
int userInput = 10; //get it from user
List<Numbers> example = new ArrayList<>();
//Add Numbers objects to example list
for(int i=0;i< example.size();i++) {
Number numberTemp = example.get(i);
//call Numbers object's isInLimits
if(numberTemp.isInLimits(userInput)) {
System.out.println(numberTemp);
}
}
}

Related

trying to print arrays in 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 2 years ago.
Improve this question
I had a code I needed to submit and every time I try to run it, I get the same errors over and over again.
Here's the question
Write the following Java methods:
(a). readValues to input ten integer values into an array of integers
TAB from a text file “Values.txt”. This array TAB is passed to the
method as parameter. Assume that the number of students in the file is
equal to the length of the array.
(b). oddValues that takes the array TAB as parameter and returns the
number of odd values found in TAB.
(c). replaceOdd that takes the array TAB as a parameter. It should
replace every odd value in TAB by the sum of all odd values.
Hint: your method must first compute the sum of all odd values.
(d). printValues that takes the array TAB as a parameter and prints
its content on the screen.
(e). main that declares the array TAB and calls the above four
methods.
N.B.: In your program, use the methods and variable names as mentioned
above.
And this is the code:
import java.util.*;
import java.io.*;
public class Finalexam
{
public static void main (String [] args ) throws FileNotFoundException
{
int sum=0;
int [] TAB=new int [10];
ReadValues(TAB);
oddValues(TAB);
replaceOdd(TAB);
printValues(TAB);
System.out.println("The sum is" + sum);
}
public static void ReadValues (int [] TAB)
{
{ int i;
for(i=0; i<10; i++){
Scanner s = new Scanner ("Values.txt") ;
TAB[i]=s.nextInt();
}
}
s.close();
}
public static double oddValues(int[] TAB)
{
int i;
double odd=0;
int fn=0;
for(i=1; i<odd; i++){
while(odd % 2 !=0)
{
odd = fn;
}
break;
}
return fn;
}
public static int replaceOdd(int[] TAB)
{
int re=0;
for(int i=0; i<TAB.length; i++){
re = re/TAB.length;
}
return re;
}
public static void printValues(int[] TAB)
{
int i;
for(i=0; i<10; i++){
System.out.println(TAB[i]+"\t");
}
System.out.println();
}
}
In which part I'm doing wrong? I cant even run it.
Firstly there is a compilation error in your code.
In your method
public static void ReadValues (int [] TAB)
{
{ int i;
for(i=0; i<10; i++){
Scanner s = new Scanner ("Values.txt") ;
TAB[i]=s.nextInt();
}
}
s.close();
}
You have too many extra brackets, well thats not the problem though, the problem is the scanner object s is declared inside the for loop where as you are closing it later outside the loop, since the scope of the variable is not outside the loop, hence the error.
The correct way should be
public static void readValues (int [] tab){
int i;
Scanner s = new Scanner ("Values.txt") ;
for(i=0; i<10; i++){
tab[i]=s.nextInt();
}
s.close();
}
Also there are many thing that will work in your code but is a bad practice or is not following conventions.
Variable names (e.g tab) should always be in camel case. It should only be a capital if it is a constant, which is not in your case.
The method names starts with small letter.
Also you are calling the two methods replaceOdd(TAB) and oddValues(TAB) But the return value is not being used anywhere.
FileNotFoundException will never be thrown
If you closely look at this method below
public static double oddValues(int[] TAB) {
int i;
double odd = 0;
int fn = 0;
for (i = 1; i < odd; i++) {
while (odd % 2 != 0) {
odd = fn;
}
break;
}
return fn;
}
The loop will never execute as odd is 0 so i<odd will always be false. Also the logic for odd is wrong.
public static int replaceOdd(int[] TAB){
int re=0;
for(int i=0; i<TAB.length; i++){
re = re/TAB.length;
}
return re;
}
This method will always return zero, the logic is wrong.
There are many more logical errors. I would suggest you to look into them as well

Java: How to create a sorted string ArrayList based on Custom object ArrayList without using Sort()

I have a class called Word in which each instance has String, ArrayList<Character>, and a double. Let's say there are 3 instances of this class. I would like to create a new ArrayList<String> in which all 3 word strings are contained. However, the order of the Strings must go from high to low of the doubles from their original instances. The major stipulation of this project is that the Collections.sort method cannot be used. Please see the code below and let me know if you can think of a way to write this loop (a loop is needed because there is actually +50,000 words):
import java.awt.List;
import java.util.ArrayList;
import java.util.Arrays;
public class WordRecommender {
String fileName;
public WordRecommender(String fileName) {
this.fileName = fileName;
}
public static void main(String[] args) {
ArrayList<Word> objectArray = new ArrayList<Word>();
objectArray.add(new Word("people", null ,0.8));
objectArray.add(new Word("dogs", null ,0.4));
objectArray.add(new Word("cats", null ,0.6));
ArrayList<String> outputArray = new ArrayList<String>();
for (int i = 0; i < finalArray.size(); i++) {
// code here to find the value of each double and place the
// associated strings into output Array from highest to lowest
}
// ideal outputArray order = ["people", "cats", "dogs"]
}
import java.util.ArrayList;
public class Word {
String wordName;
ArrayList<Character> uniqueLetters;
double percent;
public Word(String string, double percent) {
ArrayList<Character> tempArray = new ArrayList<Character>();
for (int i = 0; i < string.length(); i++) {
tempArray.add(string.charAt(i));
}
this.wordName = string;
this.uniqueLetters = tempArray;
this.percent = percent;
}
}
The result you need to achieve can be broken in 2 major steps:
Describing how, giving 2 Words, which of them will be put before the other in the List
Using the comparing method to actually sort your list of Words.
Step 1: How can we decide which word comes first?
Java has an interface called Comparable. The name is pretty self-explanatory. When you implement this interface in your Word class, you are telling Java that instances of this class can be compared against each other.
public class Word implements Comparable<Word>{
When you edit this line in your Word class, your IDE will probably complain about a "missing compareTo() method". The compareTo() method is defined in the Comparable interface and its job is deciding, from 2 instances, which one should be considered "larger" (or in our case, should be put first in the List).
An example of a usage is: "apple".compareTo("banana");. This method call should return a positive number if the first instance ("apple") is "larger", a negative number if the second instance ("banana") is "larger", or zero if both are of the same "value". By the way, the compareTo() method implemented by Strings in Java evaluates instances by alphabetical order.
So let's implement our version of the compareTo() method for our Word class.
#Override
public int compareTo(Word anotherWord) {
if(this.percent > anotherWord.percent) {
return 1;
} else if (this.percent < anotherWord.percent) {
return -1;
} else {
return 0;
}
}
Keep in mind that this implementation returns a positive value if the first instance is greater than the second, and a negative value in the other way around.
Now that we have a way of comparing our Words, we can move on to the sorting part.
Step 2: Sorting algorithms
There are a huge variety of sorting algorithms available on the internet. Some are less efficient, some are easier to implement. You can research some of them here.
For me, the easiest sorting algorithm is called BubbleSort. It is not very efficient, though.
ArrayList<Word> objectArray = new ArrayList<Word>();
objectArray.add(new Word("people", 0.8));
objectArray.add(new Word("dogs", 0.4));
objectArray.add(new Word("cats", 0.6));
for(int i = 0; i < objectArray.size() - 1; i++) {
for(int j = 0; j < objectArray.size() - i - 1; j++) {
// Remember: a compareTo() call returning a negative number
// means that the first instance is smaller than the second.
if(objectArray.get(j).compareTo(objectArray.get(j + 1)) < 0) {
Word auxiliary = objectArray.get(j);
objectArray.set(j, objectArray.get(j + 1));
objectArray.set(j + 1, auxiliary);
}
}
}
These two nested for loops will sort objectArray in descending order of percent.
I implemented a solution that involves a sorting algorithm and usage of java.util.Comparable both.
First, you need to implement Word class with java.util.Comparable so that you can define how to compare Word class in order to determine which one is greater or lower than the other. In this case, it will be the percent field.
public class Word implements Comparable<Word> {
String wordName;
ArrayList<Character> uniqueLetters;
double percent;
public Word(String string, double percent) {
ArrayList<Character> tempArray = new ArrayList<Character>();
for (int i = 0; i < string.length(); i++) {
tempArray.add(string.charAt(i));
}
this.wordName = string;
this.uniqueLetters = tempArray;
this.percent = percent;
}
#Override
public int compareTo(Word o) {
// It is better to delegate to built-in Double compare
// because all we need to compare doubles
return Double.compare(this.percent, o.percent);
}
#Override
public String toString() {
return this.wordName;
}
}
Second, the most important part is to implement a sorting algorithm. It can be challenging to implement them on your own so I suggest study them first.
For my solution it will be a regular implementation of Quick Sort algorithm as follows:
public class QuickSort {
private Word[] array;
public QuickSort(Word... words) {
this.array = words;
}
public Word[] sort(){
this.sort(this.array, 0, this.array.length-1);
return this.array;
}
private void sort(Word[] array, int begin, int end) {
//exit condition
if (begin >= end)
return;
Word pivot = array[end];
int sortIndex = begin;
for (int i = begin; i < end; i++) {
// instead of > we use compareTo to externalize comparison logic
// greater than (>) means we sort in descending order
if (array[i].compareTo(pivot) > 0) {
Word swap = array[sortIndex];
array[sortIndex] = array[i];
array[i] = swap;
sortIndex++;
}
}
//placing pivot to the sort index
Word swap = array[sortIndex];
array[sortIndex] = pivot;
array[end] = swap;
this.sort(array, begin, sortIndex-1);
this.sort(array, sortIndex+1, end);
}
}
Finally, you just use QuickSort helper class to sort your collection of Word and get the sorted output:
public class WordRecommender {
String fileName;
public WordRecommender(String fileName) {
this.fileName = fileName;
}
public static void main(String[] args) {
ArrayList<Word> objectArray = new ArrayList<Word>();
objectArray.add(new Word("people" ,0.8));
objectArray.add(new Word("dogs", 0.4));
objectArray.add(new Word("cats" ,0.6));
QuickSort quickSort = new QuickSort(objectArray.toArray(new Word[]{}));
Word[] sortedWordArray = quickSort.sort();
//output: [people, cats, dogs]
System.out.println(Arrays.asList(sortedWordArray));
}
}

array required but [ClassName] found java

I'm trying to write a function checking if 2 arrays are equal.
public class DynamicArray {
private int size; // stores the number of “occupied” elements in the array
private int[] array;
...
boolean equals(DynamicArray obj) {
boolean keepChecking = true;
int objSize = 1;
for (int i = 0; i < obj.length; i++) {
if (obj[i] == 0 && keepChecking) {
keepChecking = false;
objSize = obj[i];
}
}
if (size != objSize)
return false;
for (int i = 0; i < size; i++) {
if (array [i] != obj [i]) {
return false;
}
}
return true;
}
}
The thing is that array might be partially filled array, not filled elements will be just zeros. So, to check if 2 arrays are equal, first, I find the size of the occupied array and then I do all the checkings.
So, every time I'm trying to get the value of obj[i] or obj.length it keeps showing the error "array required, but DynamicArray found." for obj[i] and "cannot find symbol \n symbol: variable length \n location: variable obj of type DynamicArray" which I don't understand because the other array is also DynamicArray type
public class ArrayDemo {
public static void main(String[] args) {
DynamicArray ar1 = new DynamicArray(1);
DynamicArray ar2 = new DynamicArray(1);
System.out.println("equals() is " + ar1.equals(ar2));
}
}
Your parameter obj in the equals method is not an array but an instance of DynamicArray. Therefore you cannot access the values with the [] on the identifier obj. You need to rewrite that method. You also need to include methods for setting and getting the elements of the array in your DynamicArray object. For example:
val = ar1.get(0);
and
ar1.set(0, value);
So this means your Dynamic array needs the following two methods (I am assuming the values of your array are ints, but this could be anything). I'll let you figure out what goes in them as I see you must be learning the language.
public void set(int index, int value){
}
public int get(int index){
}
That way you can then use your methods in your rewritten equals function to access the elements of the array.
Another tip. You would be better sorting both arrays. Compare the first element or each, then the next, and then the next until such time you find a mismatch. At that point you can return false. If you find no mismatch return true.
The thing is , DynamicArray is not an array, its a class, you have to define a length function of it.you can just call obj.length wich is DynamicArray class which has no method length

Object in ArrayList is changing

I made a test program because I am trying to get back into Java after working in PL/SQL. I created a class Numbers that contains an integer, a getter and a setter. I have another class Test that is creating an instance of Numbers, and also adds that instance to a List. I created a for loop that loops two times and sets the value of the integer in Numbers equal to i. I then add that instance of Numbers to the List numbersList. I then do a print screen of the value that was added to the List. I do a total of 3 prints, one print the first time through the loop that prints the first position in the List, then I print two times during the second time through the loop,the first position in the List again, and the second position in the List. I was expecting to get 0,0,1 as the result. I am getting instead 0,1,1 as the result and I cannot figure out why. I am not changing anything in the first position in the List (numbersList[0]) during the second time through the loop, all I am doing is adding an instance of Numbers into the second position in the list (numbersList[1]).
import java.util.ArrayList;
import java.util.List;
public class Tests {
static int x;
public static void main(String[] args) {
List<Numbers> numbersList = new ArrayList<Numbers>();
Numbers numbers = new Numbers();
Numbers numbers2 = new Numbers();
for (int i = 0; i < 2; i++) {
if (i == 0) {
numbers.setVariable(i);
numbersList.add(numbers);
System.out.println(numbersList.get(0).getVariable());
}
if (i > 0) {
numbers2.setVariable(i);
numbersList.add(numbers2);
System.out.println(numbersList.get(0).getVariable());
System.out.println(numbersList.get(1).getVariable());
}
}
}
}
public class Numbers {
public static int a = 5;
public static void setVariable(int b) {
a = b;
}
public static int getVariable() {
return a;
}
}
public static int a = 5 means that all instances of Numbers share the same variable because of the static keyword.
Therefore, when you do numbers2.setVariable(i);, the variable is also changed for numbers. Hence the 0,1,1
If you want instance variables remove the static keywords from Numbers.
Your class Numbers has no instance fields (everything is static, or class level).
It should look something like (and overriding toString() is a good idea),
public class Numbers {
public int a = 5;
public void setVariable(int b){
a = b;
}
public int getVariable(){
return a;
}
#Override
public String toString() {
return String.valueOf(a);
}
}
By overriding toString() you can more easily print instances of Numbers. For example,
System.out.println(numbersList);

Java program HugeInteger

I am writing a program that will add 2 arrays that are 40 elements long together. I have to keep the add() method as a HugeInteger (can’t change it to a integer) so when I try to return the sum of the 2 integers it gives me “HugeInteger#77e1ee5d”. Could someone let me know what this means and also tell me how I could fix it.
Thank you
public class HugeInteger {
private int[] integer ;
public HugeInteger(int num[]){
integer =new int [40];
for(int x=1; x<=39; x++){
integer[x]= num[x];
}
}
public void parse(String s){
for(int i=0; i<=s.length(); i++){
integer[i]=Integer.parseInt(s.substring(i,i+1));
}
}
public HugeInteger add(HugeInteger a1){
HugeInteger sum = new HugeInteger(integer);
int cary=0;
for (int i=39; i>=0; i--){
sum.integer[i]=integer[i]+a1.integer[i]+cary;
if(sum.integer[i]>=10){
cary=1;
sum.integer[i]-=10;
}else{
cary=0;
}
}
return sum;
}}
//This is my test program
public class HugeIntegerTest {
public static void main(String[] args) {
int []num={1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
HugeInteger hi= new HugeInteger(num);
System.out.println("Addition: "+hi.add(hi));
}
}
That's the output of the default Object.toString() method. You need to override toString and provide a better implementation yourself. An example:
#Override
public String toString() {
StringBuilder builder = new StringBuilder(integer.length);
for(int digit : integer) {
builder.append(digit);
}
return builder.toString();
}
Note that this implementation does not trim leading zeros, i.e. it will print "0000...000123" instead of just "123". This is left as an exercise for the reader, erm, programmer. ;-)
Another tip: in your constructor, your loop should start at i=0. Otherwise the most significant digit (integer[0]) will always be zero, for example your test program would give you a HugeInteger representing 0 instead of 1039.
You have to write your own version of the toString() for HugeInteger to make it display correctly.

Categories