Array required but Integer found - java

I am trying to compare two values present in two different arrays but I end up getting the " Array required but Integer found " compile time error . I am really not able solve this. I have marked the line from where the error was coming. It would be very appreciable if anybody can help me out with this. Here is the code .
public class Banker
{
int proccess, n, allocated[][], need[][], maximum[][], available[], safe[];
boolean done[];
public Banker(int n, int proccess) {
this.n = n;
this.proccess = proccess;
allocated = new int[n][n];
need = new int[n][n];
maximum = new int[n][n];
safe = new int[proccess];
done = new boolean[proccess];
}
public void getSafeSequence() {
int result = 0;
for (int i = 0; i < proccess; ++i) {
result = getLocation();
if (result != -1) {
safe[i] = result;
done[result] = true;
} else {
System.out.println(" No Safe Sequence Exist ");
break;
}
}
if (result != -1)
DisplaySequene();
}
public int getLocation() {
boolean flag = true;
for (int i = 0; i < proccess; ++i) {
if (done[i] != true) {
flag = true;
for (int j = 0; j < n; ++j)
***if (available[i][j] < need[i][j])*** {
flag = false;
break;
}
}
if (flag)
return i;
}
return -1;
}
}

available is one dimensional array so you cannot write available[i][j]. Change it to smh like available[i]

You defined available[] as a one dimensional array and use it with two dimensions available[i][j].

Related

Capture duplicates from array without using any inbuilt functions

I have been given a task to write my own implementation for removing duplicate objects from an array. The array is unsorted.
As an example, I have this array of objects
ItemsList[] objects = {
new ItemsList("ob1"),
new ItemsList("ob2"),
new ItemsList("ob2"),
new ItemsList("ob1"),
new ItemsList("ob3")
};
"ob1" stands for itemId
My goal is to get the result array like this ["ob1", "ob2", "ob3"], but given NullPointerException when trying to find objects that aren't doubled and add those to array.
Note: cannot use Set, HashSet, ArrayList, Arrays.copyOf, Sort etc. or any other tools such as iterators.
So far I've done this:
public String[] removeDuplicates(ItemsList[] objects) {
String[] noDubs = new String[objects.length];
int len = objects.length;
int pos = 0;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (objects[i].getItemId().equals(objects[j].getItemId())) {
noDubs[pos] = objects[i].getItemId();
pos++;
}
else {
//NullPointerException given
if (!objects[i].getItemId().equals(objects[j].getItemId()) && !objects[i].getItemId().contains(noDubs[i])) {
noDubs[pos] = objects[i].getItemId();
pos++;
}
}
}
}
String[] result = new String[pos];
for(int k = 0; k < pos; k++) {
result[k] = noDubs[k];
}
return result;
}
getItemId is class ItemsList method
Here is another option. This copies entries to a buffer the first time it finds them, and then copies the buffer to a correctly sized array.
There is an advantage to looking for duplicates in the buffer, instead of the original array. If there are a lot of duplicates, then there will be fewer checks when looking in the buffer compared to when looking in the original array.
I pulled out the loop to check if an item is in the buffer into another function. This avoids nesting the for loops, which can make it easier to read.
I think this overall approach also reduces the number of variables required to keep track, which also helps make it easier to read.
private static ItemsList[] removeDuplicates(ItemsList[] arr) {
ItemsList[] buffer = new ItemsList[arr.length];
int bufferLength = 0;
for (ItemsList candidate : arr) {
if (!isInBuffer(candidate, buffer, bufferLength)) {
buffer[bufferLength] = candidate;
bufferLength++;
}
}
ItemsList[] result = new ItemsList[bufferLength];
for (int i = 0; i < bufferLength; i++) {
result[i] = buffer[i];
}
return result;
}
private static boolean isInBuffer(ItemsList candidate, ItemsList[] buffer, int bufferLength) {
for(int i = 0; i < bufferLength; i++) {
if (Objects.equals(candidate, buffer[i])) {
return true;
}
}
return false;
}
Here is an implementation. Just mark the item as duplicated if it is equal to one of the next elements. Later add it to the output array, which will need to grow.
public String[] removeDuplicates(ItemList[] items) {
String[] output = {};
for (int i = 0; i < items.length; i++) {
boolean isDuplicated = false;
ItemList current = items[i];
if (current == null)
throw new RuntimeException("item can not be null");
for (int j = i + 1; j < items.length; j++) {
if (current.equals(items[j])) {
isDuplicated = true;
break;
}
}
if (!isDuplicated) {
String[] temp = new String[output.length + 1];
System.arraycopy(output, 0, temp, 0, output.length);
temp[output.length] = current.getItemId();
output = temp;
}
}
return output;
}
You could also make every duplicate null and later add each non null element to the output array, like this:
public String[] removeDuplicates2(ItemList[] items) {
String[] temp = new String[items.length];
int inTemp = 0;
for (ItemList item : items) {
boolean isDuplicated = false;
if (item == null)
throw new RuntimeException("item can not be null");
for (int i = 0; i < inTemp; i++) {
if (item.getItemId().equals(temp[i])) {
isDuplicated = true;
break;
}
}
if (!isDuplicated) temp[inTemp++] = item.getItemId();
}
String[] output = new String[inTemp];
System.arraycopy(temp, 0, output, 0, inTemp);
return output;
}
But note that the first solution is faster
It would be better to use an intermediate array of booleans to track the duplicates and define the length of the result array. This would facilitate detection of multiple duplicates when the same element might occur more than 2 times.
Also, we need to make sure the method equals (and possibly hashCode) is properly overridden in ItemList:
// class ItemList
public boolean equals(Object o) {
if (null == o || !(o instanceof ItemList)) {
return false;
}
if (o == this) return true;
ItemList that = (ItemList) o;
return Objects.equals(this.itemId, that.itemId);
}
public int hashCode() {
return Objects.hash(this.itemId);
}
When checking for equality of ItemList it may be better to use Objects.equals to handle null values without throwing a NullPointerException. Thus, duplicate null entries in the input items will be filtered out too.
public static String[] removeDuplicates(ItemList[] items) {
final int n = items.length;
if (n < 1) {
return new String[0];
}
boolean[] dups = new boolean[n];
int dupCount = 0;
for (int i = 0; i < n; i++) {
ItemList current = items[i];
for (int j = i + 1; j < n; j++) {
if (dups[j]) {
continue;
}
if (Objects.equals(current, items[j])) {
dups[j] = true;
dupCount++;
}
}
}
String[] output = new String[n - dupCount];
for (int i = 0, j = 0; i < n; i++) {
if (!dups[i]) {
output[j++] = null == items[i] ? "<NULL>" : items[i].getItemId();
}
}
// info message
System.out.printf("Found and removed %d duplicate value%s%n", dupCount, dupCount != 1 ? "s" : "");
return output;
}
Test:
ItemList[] items = {
null, new ItemList("ob1"), new ItemList("ob2"), new ItemList("ob2"), new ItemList("ob1"),
new ItemList("ob3"), null, new ItemList("ob3"), new ItemList(null), new ItemList("ob5"),
new ItemList("ob2"), new ItemList(null), new ItemList("ob4"), new ItemList("ob5"), null,
};
System.out.println(Arrays.toString(removeDuplicates(items)));
// compare removal of duplicates to using set
System.out.println("\nUsing Set");
Set<ItemList> set = new LinkedHashSet<>(Arrays.asList(items));
System.out.println(set);
Output:
Found and removed 8 duplicate values
[<NULL>, ob1, ob2, ob3, null, ob5, ob4]
Using Set
[null, {id=ob1}, {id=ob2}, {id=ob3}, {id=null}, {id=ob5}, {id=ob4}]

returning the smallest value of an array

I have a method that is supposed to return the smallest value of an array. The array is in the parametre of the method, so you input the values of your own choosing when you make an object of the class. This is the method I have come up with so far:
public class minsteNummer {
public minsteNummer() {
}
public int minsteNummer(Integer[] nummer) {
int minste = 0;
for(int i = 0; i< nummer.length; i++){
if(nummer[i] <= nummer.length) {
minste = i;
System.out.println("Minste nummer er " + minste);
} else if(nummer.length == 0) {
return 0;
}
}
return 0;
}
}
It does not execute the way I want it to, and I cant figure out what exacly it prints, but it is definetly not the smalles number of the array. I have tried with a while loop, but that does not work either.
Does anyone know where the fault in the code is, and how to improve it? I would also like it to just return, not print, the smalles number, but when I try to put "return minste;" in the if-statement, it says "unexpected return value".
Thanks in advance.
There are few places in your code that need attention:
As method scope is public you should always check for invalid input
Should not assign: int minste = 0; as there could be a negative number in a given array
When assign minimum number, should always compare it to the loop current number
if (minste > nummer[i]) minste = nummer[i];
Finally always return your minimum number return minste;
All together:
public static int minsteNummer(Integer[] nummer) {
if (nummer==null || nummer.length == 0) {
throw new IllegalArgumentException("Bad or empty array");
}
int minste = nummer[0];
for (int i = 1; i< nummer.length; i++){
if (minste > nummer[i]) minste = nummer[i];
}
System.out.println("Minste nummer er " + minste);
return minste;
}
It is worth to mention that you could use Java build-in functionality for such a basic task, i.e. sort array in ascending order and get first element:
public static int minsteNummer(Integer[] nummer) {
if (nummer==null || nummer.length == 0) {
throw new IllegalArgumentException("Bad or empty array");
}
Arrays.sort(nummer);
return nummer[0];
}
use streams
Integer[] arrayB = null;
OptionalInt min = Arrays.stream(arrayB).mapToInt(Integer::intValue).min();
public int minsteNummer(Integer[] nummer) {
int minste = Integer.MAX_VALUE;
for(int i = 0; i< nummer.length; i++){
if(nummer[i] < minste ) {
minste = nummer[i] ;
}
if(minste != Integer.MAX_VALUE)
return minste;
else
return 0;
}

Java (specifically Netbeans and JForms): Checking duplicates in each line of 2D array

I am doing a Lotto application in a jForm/GUI in Netbeans with 3 rows of 5 numbers, and I don't want duplicates to be allowed on each line. To have one number on line 1 and the same on line 3 is OK, but to have those numbers on the same line is not OK.
The only way I can think of doing it that I know will work is to hard code it, and preferably, I don't want that.
I have tried:
boolean dup = false;
for (int k = 0; k < num[0].length){ //loop through columns
for (i = 0; i < num.length-1; i++) {
for (int j = i; j < inArray.length; j++){
if (num[k][i] == num[k][j]){
dup = true;
break;
}
}
}
}
and this:
public static boolean hasDuplicates(int [][] num) {
for (int row = 0; row < num.length; row++) {
int curRow = num[row];
Set set = Sets.newHashSet(Arrays.asList(curRow));
if (set.size() < curRow.length) {
return true;
}
}
return false;
}
I have also looked at other coding extensively and I can't get one that works.
The exact thing I'm trying to do is:
Get user's input for three lines of Lotto via text field, check each line for duplicates, print to a jLabel if it's a duplicate or leave the jLabel blank and run the rest of the code if there's no duplicates.
The current code I have is:
private void playBtnActionPerformed(java.awt.event.ActionEvent evt) {
num[0][0] = Integer.parseInt(line00Tf.getText());
num[0][1] = Integer.parseInt(line01Tf.getText());
num[0][2] = Integer.parseInt(line02Tf.getText());
num[0][3] = Integer.parseInt(line03Tf.getText());
num[0][4] = Integer.parseInt(line04Tf.getText());
num[1][0] = Integer.parseInt(line10Tf.getText());
num[1][1] = Integer.parseInt(line11Tf.getText());
num[1][2] = Integer.parseInt(line12Tf.getText());
num[1][3] = Integer.parseInt(line13Tf.getText());
num[1][4] = Integer.parseInt(line14Tf.getText());
num[2][0] = Integer.parseInt(line20Tf.getText());
num[2][1] = Integer.parseInt(line21Tf.getText());
num[2][2] = Integer.parseInt(line22Tf.getText());
num[2][3] = Integer.parseInt(line23Tf.getText());
num[2][4] = Integer.parseInt(line24Tf.getText());
duplicateLbl.setText("");
LottoPhase1 p1 = new LottoPhase1();
p1.setNum(num);
p1.createSecret();
secret = p1.getSecret();
p1.computeCheckInput();
correctL1 = p1.getCorrectL1();
correctL2 = p1.getCorrectL2();
correctL3 = p1.getCorrectL3();
//prints secret to output
System.out.println("Phase 1 Main Secret: " + Arrays.toString(secret));
System.out.println();
displayResults0Lbl.setText(Integer.toString(secret[0]) + ", " + Integer.toString(secret[1]) + ", " + Integer.toString(secret[2]) + ", " + Integer.toString(secret[3]) + ", " + Integer.toString(secret[4]));
matched1NumLbl.setText(Integer.toString(correctL1));
matched2NumLbl.setText(Integer.toString(correctL2));
matched3NumLbl.setText(Integer.toString(correctL3));
}
public static boolean hasDuplicates(int[][] num)
{
boolean hasDuplicate = false;
// for each line in num
for(int[] line : num)
{
// for every number in the row
for(int i = 0; i < line.length && !hasDuplicate; i++)
{
// for every number in the row
for(int j = 0; j < line.length; j++)
{
// if we are not comparing the same number
if(i != j)
{
// check for equality
if(line[i] == line[j])
{
hasDuplicate = true; // we have found a duplicate
break; // no need to keep checking; break the loop and return
}
}
}
}
}
return hasDuplicate;
}
The second method has a couple of errors, for instance,
int curRow = num[row];
Should actually be:
int[] curRow = num[row];
Also, you appear to be using Sets, which probably comes from some library you're using (Guava, Google Common, etc.). Assuming you were not using any library, you could change your code to something similar to:
public static boolean hasDuplicates(int [][] num) {
for (int[] curRow : num) {
Set<Integer> set = new HashSet<>();
for (int n : curRow) {
if (!set.add(n)) {
return true;
}
}
}
return false;
}
If you're using Java 8, one way to remove the second for loop is by using a Stream:
public static boolean hasDuplicates(int [][] num) {
for (int[] curRow : num) {
Set<Integer> set = IntStream.of(curRow).boxed().collect(Collectors.toSet());
if (set.size() < curRow.length) {
return true;
}
}
return false;
}
Other alternatives to the Stream can be found in threads like these.
Testing with the following input produces what I think you would expect:
int[][] testA = {{0,1,2,3,4}, {0,1,2,3,4}, {0,1,2,3,4}}; //false
int[][] testB = {{0,1,2,3,4}, {0,2,2,3,4}, {0,1,2,3,4}}; //true
int[][] testC = {{0,1,2,3,4}, {0,1,2,3,4}, {0,4,3,3,4}}; //true
int[][] testD = {{0,1,2,3,4}, {5,6,7,8,9}, {10,11,12,13,14}}; //false

need help in algorithm of deterministic finite automata

i'm working on an application on deterministic finite automata but there's a problem in algorithm, all the details will be set from user's input. it becomes problem if user inputs details like following
totalStates = 3 //user input
initialState = 1 //user input
finalState = 3 //user input
//transitions created in linked-list
//contains three data members(prevState(int), transition symbol(String), nextState(int))
2->b->1 //user input
1->a->2 //user input
2->b->3 //user input
string = ab
this is a valid string for this automata but not according to my algorithm, there's problem in algo that it changes the states according to transitions indexes. like
for 'a' it works good and change the state from 1 to 2
for 'b' it choose the transition from 2 to 1 not 2 to 3
because 2->b->1 is created before 2->b->3
how to solve this using linked-list( for transitions) and String(for string input) in java. Thanks
complete code is
public boolean match() {
s = str;
current = FiniteAutomata.startState;
for (int t = 0; t < str.length(); t++) {
curFlag = false;
list2 = originalList.head;
while (list2 != null) {
if (current == list2.initialState) {
for (int i = 0; i < s.length(); i++) {
String s2 = delL(s.toCharArray(), i);
if (s2.equals(list2.transitionString)) {
current = list2.finalState;
curFlag = true;
s = delF(s.toCharArray(), i);
}
}
}
if (curFlag) {
break;
}
list2 = list2.next;
}
}
boolean flag = false;
if (s.equals("")) {
for (int i = 0; i < FiniteAutomata.finalStates.length; i++) {
if (current == FiniteAutomata.finalStates[i]) {
flag = true;
}
}
}
if (flag) {
return true;
} else {
return false;
}
}
String delF(char[] temp, int c) {
String s = "";
for (int i = c + 1; i < temp.length; i++) {
s = s + temp[i];
}
return s;
}
String delL(char[] temp, int c) {
String s = "";
for (int i = 0; i <= c; i++) {
s = s + temp[i];
}
return s;
}

manipulating two-dimensional arrays of String

this is an array of process, that have inforamtion like, number of proces, name and sex
private String process[][] = {
{"0001", "Maria Gomes", "Feminino"},
{"0002", "José Santos", "Masculino"},
{"0003", "João Oliveira", "Masculino"}};
and I have doubt here, to get the next new number of process, in array is 0003, and the next is 0004
public String getNewNextNumberOfProcess() {//
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process[i].length; j++) {
return process[i][j];
}
}
return "-1";
}
and I have doubt here, in create process
public boolean createProcess(String number_process, String name, String sex) {
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process[i].length; j++) {
//add number of process
process[i][0] += number_process;
//add name
process[i][1] += name;
//add sex
process[i][2] += sex;
return true;
}
}
return false;
}
and I have doubt here, in delete process
public boolean deleteProcess(String numberProcess) {
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process[i].length; j++) {
//if number of process is the same in array of process
if(numberProcess.equals(process[i][j])){
//delete all information associated with number of process
process[i][j] -= process[i][0];
//return true
return true;
}
}
}
return false;
}
public String getNewNextNumberOfProcess() {//
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process[i].length; j++) {
return process[i][j];
}
}
return "-1";
}
Will always return process[0][0] during the first iteration of the j for loop inside the i for loop.
May I suggest using a different data structure. What if you used a Map with the process as the key and an array with the name and sex as the value?
Here is some more information on Maps.
https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
I think it would be better if you create a Process class and implement it like this:
private Map<Integer, Process> processes = new HashMap<Integer, Process>;
public class Process
{
public int processId;
public string processName;
public string processSex;
}
public void AddProcess(Process process)
{
if (processes.get(process.processId) == null)
{
processes.put(process.processId, process);
}
}
public void DeleteProcess(Process process)
{
if (processes.get(process.processId) != null)
{
processes.remove(process.processId);
}
}

Categories