I'm fairly new to java and have started on ArrayLists and I'm stuck on a particular issue.
What I'm trying to do in the code below is have a value passed to the method locateCatalogue, which will go through the array list collection to match the value entered.
Once it finds the matched value, stop executing and show how many items there are for the said item. Otherwise if the number doesn't exist just return null, Here's my code:
Arraylist<Catalogue> items;
Public locateCatalogue (int number)
// if int number matches value entered, find number.
for(int i=0; i < locateCatalogue.length; i++)
if (Catalogue.get(i) = number)
return Catalogue;
}
else {
//return no value if entered value has no matching number.
return null;
}
the operator =means to define variables. For comparison use ==. Furthermore you messed up the if statement:
Arraylist<Catalogue> items;
Public int locateCatalogue (Catalogue catalogue ){
for(int i=0; i < items.size(); i++)
if(items.get(i) == catalogue )
return i;
else
return -1;
}
But you can not count the items you want if you return after you found the first. Also it's not clear what you want to return
The syntax for the for-loop is as follow:
for(int i=0; i < items.size(); i++) {
//some code
}
The syntax for the if-statement is:
if(items.get(i) == number) {
//some code
}
public Catalogue locateCatalogue( int number ) {
for( Catalogue item : items ) {
if( item.id == number ) {
return item;
}
return null;
}
Related
Basicly im trying to look through an Arraylist to check if the same object is listed 2 times - and if: append to "tempFinalFilterSearchList"
Im not allowed to use Hashmap (School assignment).
UPDATE - This code actual works now... Now I just need to remove dublicates from "tempFinalFilterSearchList"
public List<Venue> filterToFinalSearchList()
{
for (int i=0; i < tempFilterSearchList.size(); i++)
{
int occurences=0;
for (int j = 0; j < tempFilterSearchList.size(); j++)
{
if (tempFilterSearchList.get(i).getVenueId() == tempFilterSearchList.get(j).getVenueId())
{
occurences++;
}
}
if (occurences == 2)
{
tempFinalFilterSearchList.add(tempFilterSearchList.get(i));
}
}
return tempFinalFilterSearchList;
}
if the same venueId is listed exact 2 times in "tempfilterSearchList", then the Object have to be added to "tempFinalFilterSearchList"...
have tried several different things now, without luck - And also search here / google - there alot of solutions, but all with Hashmap which im not allowed to use.
Thank you in advance for any advise.
First of all keep in mind that using the remove function inside a loop for the same list is not safe(Unless using an iterator).
I assume you have a class let's call it A that has the attribute venueId.
It looks something like this + other attributes that you want:
public class A {
private int venueId;
public A(int venueId) {
this.venueId = venueId;
}
public int getVenueId() {
return venueId;
}
public void setVenueId(int venueId) {
this.venueId = venueId;
}
}
1.Create a function that parses the list and counts the number of times an object with the same venueId repeats itself
public boolean doesVenueIdRepeatInList(int venueId, List<A> list) {
int timesRepeated = 0;
//Parse the list and count the number of items that have the same venueId
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getVenueId() == venueId) {
timesRepeated++;
}
}
//If the venueId repeats more than 3 times
if (timesRepeated >= 3) {
return true;
}
return false;
}
3.Now to the code that actually does what you asked.
We will parse the list and identify the the objects that repeat more than 3 times.
If they repeat more than 3 times we won't add them to the new list
List<A> tempFilterSearchList = Arrays.asList(
new A(1),
new A(2),
new A(1),
new A(2),
new A(3),
new A(1),
new A(2)
);
//We will be using a new list to put the result in
//It's not safe to use the delete function inside a loop
List<A> filteredList = new ArrayList<>();
//Count the number an object repeats and if it repeats more than 3 times store it inside repeatedVenueIds
for (int i=0; i < tempFilterSearchList.size(); i++)
{
int venueId = tempFilterSearchList.get(i).getVenueId();
boolean itRepeat3Times = doesVenueIdRepeatInList(venueId, tempFilterSearchList);
//If it doesn't repeat more than 3 times add it to the new list
if(!itRepeat3Times) {
filteredList.add(tempFilterSearchList.get(i));
}
}
You have your result inside filteredList
It is a better advanced option to use 'iterator' since it allows you to remove elements while iterating an arraylist
ArrayList<Integer> tempFilterSearchList = new ArrayList<Integer>(Arrays.asList(1,2,5,3,7,3,7,3) );
Iterator itr = tempFilterSearchList.iterator();
while (itr.hasNext())
{
int count = 0;
int number = (Integer)itr.next();
for (int i=0; i < tempFilterSearchList.size(); i++)
{
int x = tempFilterSearchList.get(i);
if (x == number)
{
count++;
}
}
if( count != 3 )
{
itr.remove();
}
}
"using the remove function inside a loop for the same list is not safe. " this will not be an issue if you use iterator in java which is a advance option in java language
Your code must look like the folowing. First of all you should loop over all the elements in tempFilterSearchList. Then for each element, you should count the number of times it appears in the list. I choosed rather to place all the positions where the current elements' venueId occures in separate List to further delete them easly.
ArrayList<Integer> occurrences = new ArrayList<Integer>()
for (int i=0; i < tempFilterSearchList.size(); i++)
for (int j=0; j < tempFilterSearchList.size(); j++){
if(tempFilterSearchList.get(i).getVenueId() ==tempFilterSearchList.get(j).getVenueId()){
occurrences.add(j)
}
}
if(occurrences.size() != 3){
for(int j:occurrences){
tempFilterSearchList.remove(occurrences[j])
}
}
}
I'm trying to create a simple indexOf() method that returns an int value and that recognizes a string (not char) of an string array.
public int indexOf(String str) {
/*Getting and return the index of the first
*occurrence of the specified String. Return
*-1 if string not in the list
*/
for(int i = 0; i < listArray.length; i++) {
if(listArray[i].equals(str)) {
return str.indexOf(listArray[i]);
}
}
return -1;
}
I'm using indexOf() method from Java for the first return, but it always returns 0. Why is this, and is there a better way to write this method?
Your for-loop is fine, the problem there is that when you find it, you are returning the index where the string is in itself, and that will always be 0.
For instance, "hello" is in the position 0 for the string "hello".
You should just return i, like this:
public int indexOf(String str) {
/* Getting and return the index of the first
* occurrence of the specified String. Return
* -1 if string not in the list
*/
for (int i = 0; i < listArray.length; i++) {
if (listArray[i].equals(str)) {
// If we get here, it means that the item for position `i` is equal to `str`.
return i; // just return `i`
}
}
return -1;
}
return i; by definition listArray[i] is equal to str.
Because, whenever you run return str.indexoOf(listArray[i]);, you already have str equals listArray[i]. Of course you are getting 0 all the time, it's equivalent to str.indexOf(str);
And you really don't need to do that. You have already found an element in the list that equals the given string, just return its location:
return i;
You must return i (index) when the if condition is satisfied.
public int indexOf(String str) {
for(int i = 0; i < listArray.length; i++) {
if(listArray[i].equals(str)) {
return i;
}
}
return -1;
}
I think you have got confused. if you want to find a string from ArrayList and if you have already found the string in your if(listArray[i].equals(str)) then all you have to do is just return that index i as you have already found it.
for(int i=0;i<listArray.length;i++){
if(listArray[i].equals(str)){
return i;
}
}
is the answer.
Always remember: If you even post the contents or sample of your listArray and sample string to find in it... It will help us better to understand where exactly you are stuck
You can do this using a for loop.
Check if the string matches using equals.
If yes, return the index.
If you come out of the for loop, return -1.
public int indexOf(String iparam){
String astring = "" //YOUR OWN STRING
boolean astat = false;
List<Integer> alist = null;
for(int i=0; i<astring.toCharArray().length; i++){
alist = new ArrayList<>();
for(int j=0; j<iparam.toCharArray().length; j++){
try{
if(astring.toCharArray()[i+j] == iparam.toCharArray()[j]){
alist.add(i+j);
}else{
break;
}
}catch(Exception ex){
ex.printStackTrace();
break;
}
}
if(alist.size() == iparam.toCharArray().length){
astat = true;
break;
}
}
if(astat){
return alist.get(0);
}else{
return -1;
}
}
Given an array of integers, check whether any number has been repeated in the array. That is, whether the array has any duplicates.
Sample Input 1
anyDuplicates({1,2,3,4})
Sample Output 1
false
Sample Input 2
anyDuplicates({11,22,33,44,22)
Sample Output 2
true
MyApproach
For checking whether the elements contains duplicates or not.I took too loops and checked whether the elements contains more than or equal to 2 times repeatition.If it does,i return false.else I return true.
public boolean anyDuplicates(int[] arr) {
boolean b1=false;
int count=0;
int z[]=new int[arr.length];
for(int i=0; i<arr.length; i++)
{ count=0; //#Edit
for(int j=0; j<arr.length; j++) {
if(arr[i]==arr[j]) {
count++;
}
}
z[i]=count;
if(z[i]>=2) {
b1=true;
break;
}
}
if(b1==true)
return true;
else
return false;
}
#Edit
DRY RUN
When I dry run the code I got my Ans as I need to put count=0 after my for i loop.Thank you all for giving me your views.
Parameters Actual Output Expected Output
{24,27,30} false false
My question:Why I am not getting expected output?
Update you code likewise,
for(int i=0;i<arr.length-1;i++)
{
for(int j=i+1;j<arr.length;j++)
{
.........
if(z[i]>=1){...}
}
}
Your mistake is, you are first taking one value that is reside into
a[i], and again into j-loop start with 0, so obviously a[i=0] and a[j=0] comes into comparison, which return true , and you will get
wrong comparion as per your requirement,
My code will work like, once value pick that is store into a[i=0...n-1],
now not repeat a[j=1...n] again unless and untill it is revise into array
Two problems with your code:
You're comparing each element with itself.
You're also comparing each pair of number twice which could be reduced to once.
Here's a sample code that could achieve solutions to both these problems:
public boolean anyDuplicates(int[] arr) {
for(int i=0; i<arr.length-1; i++) {
for(int j=i+1; j<arr.length; j++)
if (arr[i]==arr[j])
return true;
}
return false;
}
in your code, change:
if ((i!=j) && (arr[i]==arr[j]))
more clean:
public boolean anyDuplicates(int[] arr)
{
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr.length;j++)
if ((i!=j) && (arr[i]==arr[j]))
return true;
}
return false;
}
faster:
use a Set to put your values, and check the length against array length
public boolean anyDuplicates(int[] arr)
{
// => Integer[]
Integer[] array_Integer = ArrayUtils.toObject(arr);
// => Set<Integer>
Set<Integer> Set_Integer= new HashSet<Integer>(Arrays.asList(array_Integer));
// => size
int sz=Set_Integer.size();
return (sz!=arr.length);
}
I'm attempting to write a method in a class that will prompt the user to enter the name of a student. Then search the list of already existing names for a match. But I cant seem to figure out how to proceed in coding it on how to search for a valid match.
public void modifyExam(String [] names)
{
String name;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the name of the student whose grade you would like to modify: ");
name = scanner.nextLine();
boolean nameMatch = true;
for (int i=0; i<names.length; i++)
{
// ....
}
You should use .equals() to compare strings in Java. Example:
public void modifyExam(String [] names) {
String name;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the name of the student whose grade you would like to modify: ");
name = scanner.nextLine();
boolean nameMatch = false;
for (int i=0; i<names.length; i++) {
if( names[i].equals(name) ) {
// do your logic here ...
}
}
}
I would recommend that you store your students in a Map with the name as the key. Then you wouldn't have to iterate (assuming your names are unique).
Map<String, Student> students = new HashMap<String, Student>();
Student s = new Student("Joe Smoe");
students.put(s.getName(), s);
Then you can lookup the student to update like this:
Student studentToUpdate = students.get(name);
if (studentToUpdate != null) {
// logic here...
}
Note Returns null if this map contains no mapping for the key. So you would want to add a null check before using the return value of the get call and deal with it accordingly.
Equalities.
if(name.equals(name[i]))
System.out.println("match at " i);
boolean nameMatch = false;
for (int i=0; i<names.length; i++) {
if(names[i].equals(name)) {
namesMatch = true;
break;
}
}
The break means you don't carry on searching the array as a match has been found.
I would break this function into two functions. One called findName() or even more generic findString() and the other called modifyExam. Let findString() return an index, use the index in modify exam.
Here is what findString() should do
int findString(String [] names, String name) {
for ( int i = 0; i < names.length; i++ ) {
if names[i].equals(name) return // either a boolean or an index or something.
}
return -1 // or null
}
You could also use binary search if the search array is large and already sorted. Using binarySearch() the findString method will be something like :-
int findString(String[] names, String name, int startIndex, int stopIndex) {
if ( startIndex > stopIndex) return;
int mid = (stopIndex - startIndex)/2
if ( name < names[mid] ) return findString(names, name, startIndex, mid-1);
else if ( names[mid].equals(name) ) return mid;
else return findString(names, name, mid+1, stopIndex);
}
I have 2 parallel arrays: the first contains State Names, the second Capitals of the states.
I'm making a quiz that randomly generates a State then asks the user to enter the Capital of the state. Once the input is received I want to call a method to check if the index of the capital entered is the same as the index of the state it goes with.
ie: stateArray[0] = "New York" and capitalArray[0] = "Albany".
Check Answer Method
public static void checkAnswer(String[]stateArray, String capitalArray, String answer)
{
int index;
for (int i = 0; i < capitalArray.length; i++){
if(capitalArray[i].equalsIgnoreCase(answer)){
index = i;
}
}
if(capitalArray[index] == stateArray[index])
{
System.out.println("correct");
}
else
{
System.out.println("incorrect");
}
}
I know the second if statement is wrong. How can I compare the two arrays using the index where the users answer was found in the capitalArray?
boolean checkAnswer(String[] stateArray, String[] capitalArray, String displayedState, String answer) {
for (int i = 0; i < stateArray.length; i++) {
if (stateArray[i].equals(displayedState) && capitalArray[i].equals(answer)) {
return true;
}
}
return false;
}
Or something. The key is you need to pass in something to represent the state you displayed.
You need to keep track of the index that holds the State displayed to the user. For example, the way your code is written now gives the user the ability to get a right answer by giving a wrong answer. Take this example as explanation:
string[] stateArray = {"New York", "California"};
string[] capitalArray = {"Albany", "Sacramento"};
If you were to show "New York" as the question and the user happens to answer "Sacramento" your code would display correct.
You also need a case in which the answer does not match any of the capitals in the array. One way of doing this to implement in your code is to initiate the index to -1.
int index = -1;
Once you finish the for loop check if index is -1 and display "Your answers is not a valid State" or something along those lines.
Maybe use a HashMap, I am not completely familiar with Java it appears to be the similar to a Dictionary in Python. Dictionary object has great performance.
Since you know what state you asked about you should know its array index as well. As you see below both arrays are declared as class variables.
... class Quiz {
private String[] states = new String[50];
private String[] capitals = new String[50];
... method to fill both arrays with the correct data
public static void checkAnswer(int question, String answer)
{
if(capitalArray[question].equalsIgnoreCase(answer)){
{
System.out.println("correct");
}
else
{
System.out.println("incorrect");
}
}
}
It's better to have checkAnswer method's return type as Boolean, but I left it your way.
An alternate implementation in Java would be to use a Map instead of two arrays.
Map<String,String> stateCapitals = new HashMap<String,String>();
stateCaptitals.put("New York", "Albany");
then you can check the map with
public voic checkAnswer(String chosenState, String chosenCapital) {
if (stateCapitals.get(chosenState).equals(chosenCapital) {
System.out.println("you are correct!");
}
}
This does not do it with 2 parallel arrays, but it is a better implementation if your real concern is the type of data you mentioned, and not the arrays themselves.
Try this function it return array:-
public static String[] numSame (String[] list1, String[] list2)
{
int same = 0;
for (int i = 0; i <= list1.length-1; i++)
{
for(int j = 0; j <= list2.length-1; j++)
{
if (list1[i].equals(list2[j]))
{
same++;
break;
}
}
}
String [] array=new String[same];
int p=0;
for (int i = 0; i <= list1.length-1; i++)
{
for(int j = 0; j <= list2.length-1; j++)
{
if (list1[i].equals(list2[j]))
{
array[p]= list1[i]+"";
System.out.println("array[p] => "+array[p]);
p++;
break;
}
}
}
return array;
}