I have an array of int [] scores = new int[SCORES]; where SCORES = 5 and I want to create a method that will return my array of my int. Is it possible with a get method? With a String, getScore works fine but what about an int [] getScore?
public String getScore() {
String i = "";
for (int scoresIndex =0; scoresIndex< scores.length; scoresIndex++)
i += scores[scoresIndex]+" ";
return i;
}
public int [] getScores() {
////_____////
}
You could just return the array:
public int[] getScores() { return scores; }
You can also choose to give them a copy instead:
public int[] getScores() { return scores.clone(); }
The latter approach is safer because it prevents your caller from corrupting your object's internal state, but of course it comes with a small performance penalty because of the extra copying.
public int[] getScores(){ return scores ;}
This would be fine for what you want.
public int[] getScores()
{
// any other code
return scores;
}
Related
So I asked a question previously about returning arrays in Java, to which I got an answer, and now my code is updated with a getter, however I keep getting something along the lines of:
Phone#b08deb
as an output, which is not what I want, and if I were to do something like:
return arr[1];
It tells me that Phone cannot be converted to Phone[], and I'm incredibly lost as to how to get simply the number "00000" to be spit out by the compiler from the array (as I do understand that I don't need to initialize the array because it defaults to 0)
Link to question:
How do I return an array to another class in Java?
Updated code:
class TheDriverClass
{
public static void main(String[] args)
{
Phone p = new Phone(5);
System.out.println(p);
// Here it's supposed to return the values of an array with size 5,
//so it should print out 00000
}
}
Next I have the class Phone:
class Phone
{
private Phone[] arr; //I'm supposed to keep the array private
public Phone(int theLength){
arr = new Phone[size];
}
public Phone[] getPhone(){
return arr;
}
}
When you System.out.println() an array it basically prints out the array pointer.
you need something like Arrays.toString(array) it will call the toString on each element and print out something that is human readable.
Also to have a Phone that you can read. You will need to override the toString() on it as well.
class Phone
{
private int[] numbers; //I'm supposed to keep the array private
public Phone(int theLength){
numbers = new int[theLength];
}
public int[] getPhone(){
return numbers;
}
#Override
public String toString() {
return Arrays.toString(numbers);// also can use return Arrays.toString(numbers).replaceAll(",|\\[|\\]| ", ""); to clean up the , and []s
}
}
public class HelloWorld {
public static void main(String[] args) {
Phone p = new Phone(5);
System.out.println(p.getPhone());
}
}
class Phone {
private int[] arr;
public Phone(int size) {
this.arr = new int[size];
}
/* convert array to string */
public String getPhone() {
return Arrays.toString(arr);
}
}
If you would like to get the exact output as "00000" format, then you need to use StringBuilder
In the Phone class, the Phone[] arr will default to null, hence using int[] will default values to 0
If you don't want to make any changes in Phone class then inherit Phone class in CustomPhone class and override toString. this will work when Phone class is not final. I guess the following code may solve your problem.
class PhoneCustom extends Phone{
public PhoneCustom(int theLength) {
super(theLength);
}
#Override
public String toString() {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < super.getPhone().length; i++) {
if(super.getPhone()[i] == null) {
sb.append(0);
}else {
sb.append(super.getPhone()[i]);
}
}
return sb.toString();
}
}
Also, modify toString according to your requirement in else part.
If you have flexiblity to modify you phone class then override the toString method in phone class.
class Phone
{
private Phone[] arr; //I'm supposed to keep the array private
public Phone(int theLength){
arr = new Phone[theLength];
}
public Phone[] getPhone(){
return arr;
}
#Override
public String toString() {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < arr.length; i++) {
if(arr[i] == null) {
sb.append(0);
}else {
sb.append(arr[i]);
}
}
return sb.toString();
}
}
I have a very simple program and I just need to check an array for a value in it.
I have a class called bulkBean. this is it.
public class bulkBean {
private int installmentNo;
private double amount;
public int getInstallmentNo() {
return installmentNo;
}
public void setInstallmentNo(int installmentNo) {
this.installmentNo = installmentNo;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
Now I have an array of this bulkBean type in my program, this is my program.
import java.util.Arrays;
public class test {
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
}
for(int j = 0; j< arr.length ;j++){
System.out.println("INFO: array "+j+" = "+arr[j]);
}
if (Arrays.asList(arr).contains(i) == true) {
return true;
} else {
return false;
}
}
public static void main(String[] arg){
bulkBean bb1 = new bulkBean();
bb1.setInstallmentNo(1);
bb1.setAmount(5500);
bulkBean bb2 = new bulkBean();
bb2.setInstallmentNo(2);
bb2.setAmount(4520);
bulkBean[] bulkArray = new bulkBean[2];
bulkArray[0] = bb1;
bulkArray[1] = bb2;
boolean a = scan_bulkList(bulkArray,1);
System.out.println("val = "+a);
}
}
I create 2 instances of bulk bean and I set values to them. Then I added those two instances to an array. Then I pass that array to the method to check for a value(also given as a parameter. In this case it is 1.). If the array contains that value, it should return true, otherwise false.
whatever value I enter, it return false.
Why do I get this issue?
Arrays.asList() returns a List which has a single element - an array. So, you are actually comparing against an array. You need to compare against each value in the array.
As TheListMind told, Arrays.asList() taken on an int[] gives you a list containing the array.
Personally, I would construct directly the List instead of constructing the array, or even better (no need of array instanciation), test while iterating the bulk array :
for(int x=0;x<bulkList.length;x++){
if (bulkList[x].getInstallmentNo() == i){
return true;
}
}
return false;
The mistake you made here is , you created the int array which must be Integer array because Arrays.asList().contains(Object o); makes the input parameter also Integer(Integer i). int is not an object Integer is the object. Hope it will work.
int[] arr = new int[bulkList.length];
change to:
Integer[] arr = new Integer[bulkList.length];
Change the method as below to avoid complications:
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
if (bulkList[x].getInstallmentNo()==i) {
return true;
}
}
return false;
}
I am getting the totals of various String ArrayLists such as [1,3,4]...
by parsing them into integers and getting the total. This worked when I coded each individual one, but when I made a method by passing in the total int value and arraylist I always get a value of zero.
A method would save a lot of time.
public class Playing {
static ArrayList<String> list;
static int Vigor;
public static void main(String[] args) {
list = new ArrayList<String>();
vigoroustotal(list,Vigor);
public static void Listtotal(String par, int tt) {
for (String s : par) {
int i = Integer.parseInt(s);
tt += i;
}
}
Any changes you do to tt inside your method won't be visible anywhere else, because Java passes everything by value. Make the method return an int instead.
Your mistake her is passing the function tt and expecting it to be modified. Java doesn't modify parameters passed to functions. The corrected code would be this:
public static int ListTotal(List<String> par) {
int tt = 0;
for (String s : par) {
int i = Integer.parseInt(s);
tt += i;
}
return tt;
}
and would be used like this:
Vigor = ListTotal(list);
The changes that are made to the integer tt in the Listtotal() method will not be visible anywhere else but that method. You can make that method return an integer to solve that!
public static int Listtotal(ArrayList<String> par) {
int tt = 0;
for (String s : par) {
int i = Integer.parseInt(s);
tt += i;
}
return tt;
}
And then you need to change the main method:
public static void main(String[] args) {
list = new ArrayList<String>();
Vigor = Listtotal(list);
}
As, said, you need to return the total since java passes everything by-value, so the int tt you pass in won't hold a reference to the Vigor variable outside the method.
Therefore, when you pass in primitive types such as (int, char, boolean, byte etc.), anything you do to them inside a method won't be visible outside the method.
However, when you pass in a reference type (Objects such as ArrayList), it is still passed-by-value but that value is a copy of the reference to the Object outside the method. So, in the populateList method bellow, I can just call ArrayList.add() on the input because this input, even though it is passed-by-value, still points to the original Object that was put into this method.
public class Playing {
static ArrayList<String> list;
static int Vigor;
public static void main(String[] args) {
list = new ArrayList<String>();
populateList(list);
Vigor = getListTotal(list);
System.out.println("Total is:\t" + Vigor);
}
public static void populateList(ArrayList<String> list) {
String[] sampleData = { "4", "7", "2" };
for(int i = 0; i < sampleData.length; i++) {
list.add(sampleData[i]);
}
}
public static int getListTotal(ArrayList<String> list) {
int tt = 0;
for (String s : list) {
int i = Integer.parseInt(s);
tt += i;
}
return tt;
}
}
What you want is the... let's call it CountingList,
public class CountingList {
private List<Integer> integers = new ArrayList<Integer>();
private int sum;
public add(String s) {
int value = Integer.parseInt(s);
integers.add(value);
sum += value;
}
private void updateSum() {
sum = 0;
for (int i : integers) {
sum += i;
}
}
}
Obviously, you'll want to expose the functionality you need to use outside of the class, but this is (one) way of encapsulating the behavior you're needing.
I need to know the way to find the second largest element among an array of objects. for eg.
if there is an array of objects of a Book class with attributes like book name, price, in stock quantity
Book[] b=new Book[];
b[0]=new Book("x",200,50);
b[1]=new Book("y",100,44);
b[2]=new Book("z",500,29);
How can we list the book with second largest price along with other attributes like name and in stock quantity
Make a List of Books from it, sort it using Collections.sort and take the element on index 1.
List<Book> booklist = new ArrayList<Book>(Arrays.asList(b));
Collections.sort(booklist, new Comparator<Book>() {
#Override
public int compare(Book o1, Book o2) {
return o2.getPrice() - o1.getPrice();
}
});
if (booklist.size() > 1) {
System.out.println(booklist.get(1));
}
You can loop through this Array to find the largest and with this the second largest Element of the Array. Because the Elements are Objects you have to get the Value that you want to compare from the element with a getter or the variable is public in the objects.
public int getSecondLargest(Object[] obj){
int length = obj.length;
int largest = 0;
int secondLargest = 0;
for(int i = 0; i<length; i++){
if(obj[largest].getValue() <= obj[i].getValue()){
secondLargest = largest;
largst = i;
}
}
return secondLargest;
}
I think you should implements Interface Comparable.
and then use Collections.sort();
Implements a Comparator And sort your array, then pick second element.
class BookPriceComparator implements Comparator<Book> {
#Override
public int compare(Book a, Book b) {
return a.getPrice() - b.getPrice();
}
}
Arrays.sort(bookArr, new BookPriceComparator ());
import java.util.*;
//here you can make changes or you can create your own new class
//to sort book according to pages
class sortPrice implements Comparator<Test> {
public int compare(Test i1, Test i2) {
Integer x = i1.getPrice(), y = i2.getPrice();
return y.compareTo(x); // <--- changed
}
}
// in your case Test class could be Book class
public class Test {
/**
* #param args
*/
int price , page ;
String name;
Test(String n , int p ,int pg){
name=n;
price=p;
page=pg;
}
public String toString(){
return name+" "+price +" "+page ;
}
public String getName(){
return name;
}
public int getPage(){
return page;
}
public int getPrice(){
return price;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test[] b=new Test[3];
b[0]=new Test("x",200,50);
b[1]=new Test("y",100,44);
b[2]=new Test("z",500,29);
ArrayList<Test> a = new ArrayList<>();
for(int i=0;i<3;i++){
a.add(b[i]);
}
sortPrice s= new sortPrice(); // required to pass as argument to tell
//based on which sorting order you want to sort
Collections.sort(a,s ); //here we are sorting Test(Book) based on price.
System.out.println(a.get(1)); // printing arrayList //<----- changed
}
}
Intro
My code to do a custom sort by using Comparable is not work the way I want it to. I'm basically taking an Array of directories and sorting them by:
First number of directories, the fewer comes first.
If it's a tie alphabetically.
The problem
An example of an input you be:
["/", "/usr/", "/usr/local/", "/usr/local/bin/", "/games/",
"/games/snake/", "/homework/", "/temp/downloads/" ]
Which should return this:
["/", "/games/", "/homework/", "/usr/", "/games/snake/",
"/temp/downloads/", "/usr/local/", "/usr/local/bin/" ]
But for some reason my code is return this:
["/", "/usr/", "/games/", "/homework/", "/usr/local/",
"/games/snake/", "/usr/local/bin/", "/temp/downloads/" ]
My code [edited with comments]
import java.util.*;
public class Dirsort { public String[] sort(String[] dirs) {
//Creates Array list containing Sort object
ArrayList<Sort> mySort = new ArrayList<Sort>();
//Loop that gets the 3 needed values for sorting
for (String d: dirs){
String [] l = d.split("/");//String array for alphabetical comparison
int di = d.length();//Length of array for sorting by number of directories
mySort.add(new Sort(di,l,d));//adds Sort object to arraylist (note d (the entire directory) is needed for the toString)
}
Collections.sort(mySort);//sorts according to compareTo
String [] ans = new String [mySort.size()];//Creates a new string array that will be returned
int count = 0;//to keep track of where we are in the loop for appending
for (Sort s: mySort){
ans[count] = s.toString();
count++;
}
return ans;
}
class Sort implements Comparable<Sort>{
private int d;//number of directories
private String [] arr;//array of strings of names of directories
private String dir;//full directory as string for toString
//Constructor
public Sort(int myD, String [] myArr, String myDir){
d = myD;
arr = myArr;
dir = myDir;
}
//toString
public String toString(){
return dir;
}
#Override
public int compareTo(Sort arg0) {
// TODO Auto-generated method stub
//If they are the same return 0
if (this.equals(arg0)){
return 0;
}
//if the directories are empty
if("/".equals(arg0.dir)){
return 1;
}
if ("/".equals(this.dir)){
return -1;
}
//If they are not the same length the shorter one comes first
if (this.d != arg0.d){
return this.d - arg0.d;
}
//If they are the same length, compare them alphabetically
else{
for (int i = 0; i < arg0.d; i++){
if (!this.arr[i].equals(arg0.arr[i])){
return this.arr[i].compareTo(arg0.arr[i]);
}
}
}
return 0;
}
}
}
The bug is here:
for (String d: dirs){
String [] l = d.split("/");
int di = d.length(); // <- here
mySort.add(new Sort(di,l,d));
}
Because there you are comparing the length of the entire directory String, not the number of 'folders' in the directory. That's why "/usr/" comes before "/homework/", for example, because:
"/usr/".length() == 5
"/homework/".length() == 10
I believe what you wanted was this, using the length of the split:
int di = l.length;
Then the output is:
/
/games/
/homework/
/usr/
/games/snake/
/temp/downloads/
/usr/local/
/usr/local/bin/
There's another small bug though (possibly), which is that calling split on a String that starts with the delimiter will result in an empty String at the beginning.
IE:
"/usr/".split("/") == { "", "usr" }
So you might want to do something about that. Though here it means that all of them start with the empty String so it doesn't end up with an effect on the way you're doing the comparison.
And as a side note, it's also true what #JBNizet is suggesting that giving your variables more meaningful names helps a lot here. fullDir.length() and splitDir.length would have made this much easier to spot (and it may have never happened in the first place).
Here's a fixed version of your code, which handles the case where both directories are "/", which removes the unnecessary, and incorrectly passed length of the parts array, and which uses more meaningful variable names:
public class Dirsort {
public static void main(String[] args) {
String[] input = new String[] {
"/",
"/usr/",
"/usr/local/",
"/usr/local/bin/",
"/games/",
"/games/snake/",
"/homework/",
"/temp/downloads/"
};
String[] result = new Dirsort().sort(input);
System.out.println("result = " + Arrays.toString(result));
}
public String[] sort(String[] dirs) {
ArrayList<Sort> sorts = new ArrayList<Sort>();
for (String dir : dirs) {
String[] parts = dir.split("/");
sorts.add(new Sort(parts, dir));
}
Collections.sort(sorts);
String[] result = new String[sorts.size()];
int count = 0;
for (Sort sort: sorts) {
result[count] = sort.toString();
count++;
}
return result;
}
class Sort implements Comparable<Sort> {
private String[] parts;
private String dir;
public Sort(String[] parts, String dir) {
this.parts = parts;
this.dir = dir;
}
public String toString(){
return dir;
}
#Override
public int compareTo(Sort other) {
if (this.equals(other)){
return 0;
}
if("/".equals(other.dir) && "/".equals(dir)) {
return 0;
}
if("/".equals(other.dir)){
return 1;
}
if ("/".equals(this.dir)){
return -1;
}
if (this.parts.length != other.parts.length){
return this.parts.length - other.parts.length;
}
else {
for (int i = 0; i < other.parts.length; i++){
if (!this.parts[i].equals(other.parts[i])){
return this.parts[i].compareTo(other.parts[i]);
}
}
}
return 0;
}
}
}
I spotted the problem by simply using my debugger and make it display the value of all the variables.
public class Disort
{
public static String[] sort(String[] dirs)
{
ArrayList<Path> mySort = new ArrayList<Path>();
Path pathDir;
for(String dir : dirs){
pathDir = Paths.get(dir);
// check if directory exists
if(Files.isDirectory(pathDir)){
mySort.add(pathDir);
}
}
// sort the ArrayList according a personalized comparator
Collections.sort(mySort, new Comparator<Path>(){
#Override
public int compare(Path o1, Path o2)
{
if(o1.getNameCount() < o2.getNameCount()){
return -1;
}
else if(o1.getNameCount() > o2.getNameCount()){
return 1;
}
else{
return o1.compareTo(o2);
}
}
});
// to return a String[] but it will better to return a ArrayList<Path>
String[] result = new String[mySort.size()];
for(int i = 0; i < result.length; i++){
result[i] = mySort.get(i).toString();
}
return result;
}
}