Method with int and int[] parameters - java

I have a method with two parameters but they are different types (int , int[]). The problem is in the caller, Eclipse will not compile because it says both of the parameters need to be integer types. The caller looks like this:
boolean uniqueTorF = isUnique(count, userArray[i]);
The method is this:
public static boolean isUnique(int oneCount, int[] multiCount) {
for (int i = 0; i < multiCount.length; i++) {
if (oneCount == multiCount[i]) {
return false;
}
}
return true;
}
This is my entire code:
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int validCount = 0, i = 0, uniqueSoFar = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (validCount < 5) {
int count = entry.nextInt();
boolean validTorF = isValid(count);
boolean uniqueTorF = isUnique(count, userArray[i]);
if (validTorF == true) {
userArray[i] = count;
validCount++;
i++;
if (uniqueTorF == true){
uniqueSoFar++;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int validParameter) {
if (validParameter > 50 && validParameter < 100) {
return true;
} else {
return false;
}
}
public static boolean isUnique(int oneCount, int[] multiCount) {
for (int i = 0; i < multiCount.length; i++) {
if (oneCount == multiCount[i]) {
return false;
}
}
return true;
}
}

Get rid of the index [i]. userArray[i] is a single element of the array. userArray is the entire array.
boolean uniqueTorF = isUnique(count, userArray);

I'll bet it's saying the params ARE both integer types, not that they SHOULD BE. You're passing count and userArray[i], but you probably should be passing count and userArray.

Defined method expects second argument as array whereas the caller is sending specific element. So send the entire array as argument

The reason of the error is because you are passing the parameters wrongly...
When you do this:
boolean foo = isUnique(count, userArray[i]);
Then you are invoking the method with 2 int parameters, but you need a int, int [] instead...
You are for sure looking for something more like this:
boolean foo = isUnique(count, userArray);

Related

Writing an equals method to compare two arrays

I have the following code, I believe something is off in my equals method but I can't figure out what's wrong.
public class Test {
private double[] info;
public Test(double[] a){
double[] constructor = new double[a.length];
for (int i = 0; i < a.length; i++){
constructor[i] = a[i];
}
info = constructor;
}
public double[] getInfo(){
double[] newInfo = new double[info.length];
for(int i = 0; i < info.length; i++){
newInfo[i] = info[i];
}
return newInfo;
}
public double[] setInfo(double[] a){
double[] setInfo = new double[a.length];
for(int i = 0; i < a.length; i++){
setInfo[i] = a[i];
}
return info;
}
public boolean equals(Test x){
return (this.info == x.info);
}
}
and in my tester class I have the following code:
public class Tester {
public static void main(String[] args) {
double[] info = {5.0, 16.3, 3.5 ,79.8}
Test test1 = new Test();
test 1 = new Test(info);
Test test2 = new Test(test1.getInfo());
System.out.print("Tests 1 and 2 are equal: " + test1.equals(test2));
}
}
the rest of my methods seem to function correctly, but when I use my equals method and print the boolean, the console prints out false when it should print true.
You are just comparing memory references to the arrays. You should compare the contents of the arrays instead.
Do this by first comparing the length of each array, then if they match, the entire contents of the array one item at a time.
Here's one way of doing it (written without using helper/utility functions, so you understand what's going on):
public boolean equals(Test x) {
// check if the parameter is null
if (x == null) {
return false;
}
// check if the lengths are the same
if (this.info.length != x.info.length) {
return false;
}
// check the elements in the arrays
for (int index = 0; index < this.info.length; index++) {
if (this.info[index] != x.info[index]) {
return false;
} Aominè
}
// if we get here, then the arrays are the same size and contain the same elements
return true;
}
As #Aominè commented above, you could use a helper/utility function such as (but still need the null check):
public boolean equals(Test x) {
if (x == null) {
return false;
}
return Arrays.equals(this.info, x.info);
}

I want to search a specific element of an array and if it exists to return its index

I have created an array of type Savings which contains a String (Name) and a double (Account Number). I want to search using an Account Number and see if it exist and then return all the elements (Name + Account Number) and the Index of the Array that contain these elements. I tried this but it does not work.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Savings[] ArrayOfSavings = new Savings[5];
System.out.print("Enter Account Number: ");
Scanner scan = new Scanner(System.in);
double Ms = scan.nextDouble();
//Loop until the length of the array
for(int index = 0; index<= ArrayOfSavings.length;index++){
if(ArrayOfSavings[index].equals(Ms)){
//Print the index of the string on an array
System.out.println("Found on index "+index);
}
}
ArrayOfSavings[0] = new Savings("Giorgos",87654321);
ArrayOfSavings[1] = new Savings("Panos",33667850);
}
}
/Savings Class/
public class Savings extends Generic {
public Savings(String FN, double AN) {
super(FN, AN);
}
#Override
public String toString(){
return String.format("Customer: %s \n Acount Number: %.1f,
getFirstName(),getAccNumber();
}
}
You could do something like this, where you return -1 if it doesn't exist, or the index if you've found it. Just have to make sure you check for this case.
public static int findSavingsIfExists(double accountNumber, Savings[] allSavings) {
for(int i = 0; i < allSavings.length(); i++) {
if(allSavings[i].accountNumber == accountNumber) {
return i;
}
}
return -1;
}
and use it like so
int index = findSavingsIfExists(..., ArrayOfSavings);
if(index != -1) {
Savings foundSavings = ArrayOfSavings[index];
} else {
//Not found
}
Try to use somethig like this:
double Ms = scan.nextDouble();
int index = 0;
for (int i = 0; i < ArrayOfSavings.length; i++) {
if (ArrayOfSavings[i].getAccountNumber == Ms ) {
index = i;
break;
}
}
System.out.println(index);

Issue converting array to array list

Trying to write a java code for a single row Battleship style game, and when I tried to convert from an array to an ArrayList, the game started returning "miss" no matter what.
public class SimpleDotComGame {
public static void main(String[] args) {
int numofGuess = 0;
Scanner sc = new Scanner(System.in);
SimpleDotCom dot = new SimpleDotCom();
int ranNum = (int) (Math.random() * 5);
ArrayList<Integer> locations = new ArrayList<Integer>();
locations.add(ranNum);
locations.add(ranNum + 1);
locations.add(ranNum + 2);
dot.setLocationCells(locations); //think like you're running a
// separate program with parameters to set cells as "locations"
boolean isAlive = true;
while (isAlive == true) {
System.out.println("Enter a number");
String userGuess = sc.next();
String result = dot.checkYourself(userGuess); //run program to
// check if cells were hit by userGuess
numofGuess++;
if (result.equals("kill")) {
isAlive = false;
System.out.println("You took " + numofGuess + " guesses");
}
}
sc.close();
}
}
public class SimpleDotCom {
int numofHits = 0;
ArrayList<Integer> locationCells;
public void setLocationCells(ArrayList<Integer> locations) { //locations
// variable described array so we must define it as array now
locationCells = locations;
}
public String checkYourself(String userGuess) { //check using parameter userGuess
int guess = Integer.parseInt(userGuess);
String result = "miss";
int index = locationCells.indexOf(userGuess);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
}
System.out.println(result);
return result;
}
}
Change :
int index = locationCells.indexOf(userGuess);
to
int index = locationCells.indexOf(guess);
userGuess is a String which can not possibly be in a list of Integers. guess is an int which can.

issue with Arrays.asList()

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;
}

Custom equation solver error

I am having some difficulties getting my custom equation evaluator to work. I pass it a string read from a text file (no spaces except between string words) as equation as well as passing it a map of keywords which link to the values they represent. I have tested that and all of my maps are working properly. Below is my attempt to handle the result regardless of it is an int or a string. These will be the only two allowed entry types. Each side of the equation can have one or two elements to it, separated by either a plus or a minus. The only three operators allowed to evaluate the two sides are <,>,=. Sides are restricted to either having only keywords or only integers, so you can't have something like dexterity + 1 = strength + 2.
The error I am currently getting when I try to compile this class is "no suitable method found for parseint" "method Integer.parseInt(String,int) is not applicable". If I am not mistaken since I am compiling this class directly and not the main class it wouldn't even have the map to make that kind of judgement call. Is this a problem? I am compiling in this way because I have been having issues where recompiling the main class did not recompile secondary class files causing problems.
Any example equation: dexterity>3 or background=Ex Legionary
import java.lang.String;
import java.util.HashMap;
import java.util.Map;
public class Equation {
private String[] sides = new String[2];
private String[] rawEquation = new String[3];
private String[] parts = new String[2];
private String type;
private int[] tempInt = new int[2];
private int[] finalSide = new int[2];
private String[] finalStride = new String[2];
public boolean solve(String equation, Map gladMap) {
if (equation.indexOf("<") > -1) {
sides = equation.split("<");
rawEquation[1] = "<";
} else if (equation.indexOf(">") > -1) {
sides = equation.split(">");
rawEquation[1] = ">";
} else if (equation.indexOf("=") > -1) {
sides = equation.split("=");
rawEquation[1] = "=";
}
rawEquation[0] = sides[0];
rawEquation[2] = sides[1];
for (int d = 0; d < 2; d++) {
if (sides[d].indexOf("+") > -1) {
parts = rawEquation[0].split("\\+");
for (int a = 0; a < 2; a++) {
if (isInteger(parts[a])){
tempInt[a] = Integer.parseInt(parts[a]);
} else {
tempInt[a] = Integer.parseInt(gladMap.get(parts[a]));
}
}
finalSide[d] = tempInt[0]+tempInt[1];
type = "Int";
} else if (rawEquation[0].indexOf("-") > -1) {
parts = rawEquation[0].split("\\-");
for (int a = 0; a < 2; a++) {
if (isInteger(parts[a])){
tempInt[a] = Integer.parseInt(parts[a]);
} else {
tempInt[a] = Integer.parseInt(gladMap.get(parts[a]));
}
}
finalSide[d] = tempInt[0]-tempInt[1];
type = "Int";
} else {
if (isInteger(sides[0])){
finalSide[d] = Integer.parseInt(sides[0]);
} else {
if (isInteger(gladMap.get(sides[0]))) {
finalSide[d] = Integer.parseInt(gladMap.get(sides[0]));
type = "Int";
} else {
finalStride[d] = gladMap.get(sides[0]);
type = "Str";
}
}
}
}
if (rawEquation[1].equals("<")) {
if (type.equals("Int")) {
if (finalSide[0] < finalSide[1]) {
return true;
}
}
} else if (rawEquation[1].equals(">")) {
if (type.equals("Int")) {
if (finalSide[0] > finalSide[1]) {
return true;
}
}
} else {
if (type.equals("Int")) {
if (finalSide[0] == finalSide[1]) {
return true;
}
} else if (type.equals("Str")) {
if (finalStride[0].equals(finalStride[1])) {
return true;
}
}
}
return false;
}
public boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception NumberFormatException ) {
return false;
}
}
}
I tried to separate the Integer.parseInt() from the gladMap.get(sides[0]) by creating a temporary string variable, but it didn't change anything. Any help would be appreciated!
Here, the map which you are passing is not with the generic types. Hence, get() will always return an object, which is not an appropriate argument for parseInt() method.
Changing the method signature to
public boolean solve(String equation, Map< String ,String > gladMap) {
should solve the errors.
The problem might be following: your map is untyped so calls like gladMap.get(sides[0]) return Object. Integer.parseInt expects String. You can change it to
gladMap.get(sides[0]).toString().
It think it should work. If value is actual String then toString will return itself, it it is Integer it will be converted to string and parsed back.

Categories