I'm working on a method that finds the first instance of a given value and returns its position. It works for some cases, but if I give it an array of [1,2,3], and set the value to 2, it returns 0, instead of 1. I'm not sure why, either. Here is the code:
int b = 0;
for(int a = 0; a < values.length; a++) {
if (values[a] == find){
b++;
}
}
return b-1;
Thanks in advance!
Its because you are returning b-1. In fact, if you need to find the same instance and return the index, you wont even need the variable b. You could achieve this with something like this:
for( int a = 0; a < values.length; a++) {
if (values[a] == find){
return a;
}
}
return -1 // Notfound
}
Add the return -1 line for when a value is not found, to use as a sentinel value.
Try
for( int a = 0; a<values.length; a++) {
if (values[a] == find){
return a;
}
}
Why not return a itself instead of doing b-1;
Maybe you can add a break statement too to stop iterating as you just need the position of first instance
int b=0,result;
for( int a = 0; a<values.length; a++)
{
if (values[a] == find)
{
result=a;
break;
}
}
return result;
Related
I'm trying to write the remove method for Set but it doesn't work when I test it. Am I doing it wrong? the size doesn't reduce after I remove the element.
public class MySet<T> implements Set<T> {
private T[] arrayB;
private int elements;
#Override
public boolean remove(Object f) {
T h = (T) f;
for (T z : arrayB) {
if(z == h) {
z = null;
}
}
return true;
}
#Override
public int size() {
int count = 0;
for(int arr = 0; arr < arrayB.length; arr++){
if(arrayB[arr] != null) {
count++;
}
}
return count;
}
The test code is:
MySet<Integer> ints = new MySet<Integer>();
for (int i = 0; i < 100; i++) {
ints.add(i);
}
for (int i = 0; i < 100; i += 2) {
ints.remove(i);
}
}
Your size method relies on whether the element is null to decide whether to count it. Assuming that you are attempting to place a null in the array, you're doing it wrong. All you've done is assign null to z, which is just a local variable. The array is not changed.
You must use a traditional for loop and use an array access expression to assign null to the array element. You'll also want to call equals instead of using == to find the element.
for (int i = 0; i < array.length; i++)
{
if (array[i] != null && array[i].equals(h))
{
array[i] = null;
}
}
Depending on whether you want to remove all elements that match, or just the first one, you may consider adding a break statement inside the if.
I'm trying to compare the last names of two students in a directory, I'm doing this by overriding the compareTo method. The following code does not reflect exactly what I'm wanting to do here, the return value is just a placeholder for now. It is saying it won't compile because it cannot find the symbol for subString(int) in class String.
for (int i = 0; i < this.getLastName().length(); i++) {
if (!this.getLastName().subString(i).equals(s.getLastName().subString(i))) {
return 1;
}
}
Update: I appreciate y'all pointing out my idiocy in case sensitivity (no really, thanks) here's an update to where I'm at in the code. I think I can take it from here.
#Override
public int compareTo(Student s) {
for (int i = 0; i < this.getLastName().length(); i++) {
if (!this.getLastName().equals(s.getLastName())) {
for(int j = 0; j < this.getLastName().length() || j < s.getLastName().length(); j++) {
if (this.getLastName().charAt(j) < s.getLastName().charAt(j)) {
return 1;
}
else {
return -1;
}
}
}
}
looking at it again, I don't even need that first for loop.
and here's the finished method.
#Override
public int compareTo(Student s) {
if (!this.getLastName().equals(s.getLastName())) {
for(int j = 0; j < this.getLastName().length() || j < s.getLastName().length(); j++) {
if (this.getLastName().charAt(j) < s.getLastName().charAt(j)) {
return 1;
}
else if (this.getLastName().charAt(j) > s.getLastName().charAt(j)) {
return -1;
}
}
}
if (!this.getFirstName().equals(s.getFirstName())) {
for (int i = 0; i < this.getLastName().length() || i < s.getLastName().length(); i++) {
if (this.getFirstName().charAt(i) < s.getFirstName().charAt(i)) {
return 1;
}
else if (this.getFirstName().charAt(i) > s.getFirstName().charAt(i)) {
return -1;
}
}
}
return 0;
}
The simple way to compare two Java strings is to use the String.compareTo(String). You don't need to implement that yourself using loops. (Or at least, not in a real world context.)
If you want to order by lastname then firstname:
call `compareTo` on the last name string
- if the result is non zero, return it
- if the result is zero, compare the first name string.
I'll leave you to figure out the rest ... since this is clearly a "learning exercise".
Not sure why you want to reinvent the wheel. Stephen C was trying to point out that you can achieve the same result like this:
#Override
public int compareTo(Student that) {
int compare = this.getLastName().compareTo(that.getLastName());
if (compare == 0) {
compare = this.getFirstName().compareTo(that.getFirstName());
}
return compare;
}
Can you use a for loop inside the condition of an if-else statement? For example, something like this...
if(
for(q = 0; q < 10; q++){
values[q]>=values[q+1];
}
)
{
done = 0;
}
This is loading an error I can't seem to place. I want the if statement to check to see if the int[] I called values is in order from greatest to least, and if it is, set int variable done equal to 0.
I only just started taking a programming class and I bet this is a very dumb mistake, but I've been trying to figure this out for a while and some help would be absolutely fantastic.
You should work out your condition first (ie is your array in order), and then feed that in to your if statement. Like so...
boolean isOrdered = true;
for(q = 0; q < 10; q++){
if (values[q]>=values[q+1]){
// in order
}
else {
// not in order
isOrdered = false;
break; // we have found a false, so we can quit out of the for loop
}
}
if (isOrdered){
// do something if the array is in order;
}
You can do it if you refactor the logic into a method that returns a boolean:
if (isInOrder(values)) {
//
}
private static boolean isInOrder(int[] array) {
for (int i = 0; i < array.length - 1; i++)
if (array[i] > array[i+1])
return false;
return true;
}
A for loop can exist inside of an if block
if (true) {
for (int i = 0; i < 5; i++) {
System.out.println("Hello, World!");
}
}
But a for loop can not be the condition of the if block
if( for (int i = 0; i < 5; i++) { } ) { }
A for loop is not a boolean. Every if condition requires a boolean.
No. If requires a boolean test. For loop doesn't return a boolean value. You can instead separate the check into another function.
if( isArrayOrdered(values) ){
done = 0;
}
// assuming values is an array of `int` values
private boolean isArrayOrdered( int[] values){
for(int q = 1; q < values.length; q++){
if( values[q] > values[q-1] ){
return false;
}
}
return true;
}
I think you probably want the alternate nesting, and start with the assumption that done = 0 (that is, that the list is correctly ordered), unless you prove in the loop that it is not true.
public class Play{
public static void main(String[] args) {
done = 0;
for(q = 1; q < 10; q++){
if (values[q-1]<values[q]) {
done = 1;
break;
}
}
}
}
You need to break you logic down into steps.
first of all, a method
boolean isInOrder (int [] values) {
for(int q = 0; q < values.length - 1; q++){
if (values[q] > values[q+1]) {
return false;
}
}
return true;
}
// now lets call this method
if (isInOrder (values)) {
System.out.println ("In Order");
}
else {
System.out.println ("Not In Order");
}
No, you can't. The if condition must evaluate to some boolean value, which doesn't happen with this for loop.
It can only be in the if statement body, like
if(someCondition)
for(int i = 0;i < 10;i++)...
To achieve your goal, a code like this one might help:
boolean ordered = true;
for(int i = 0;i < array.length - 1;i++) {
if(array[i] > array[i+1]) {
ordered = false;
break;
}
}
if(ordered) // your if body here
It is impossible to put the "for loop" statement between if statement "(" and ")".But it is possible if you write "for loop" between if statement "{" and "}".Thanks
The expression inside the "if" condition should evaluate to a boolean or Boolean otherwise the code will not compile.
Check that Java specs page here
If I want to compare index 0 with index 1, 2 and 3 for instance, how is that possible?
boolean iftrue = false;
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < i; j++) {
if (IntValue(array[j]) == IntValue(array[i + j])) {
iftrue = true;
}
}
}
return iftrue;
}
Just to put Sotirios' suggestion into code... Recall he suggested you save the first elem and compare other elements against it.
public boolean sameAsFirstElem(int[] array) {
boolean isEqual = false;
int firstElem = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] == firstElem) {
return true;
}
}
return isEqual;
}
Take 0th element is an variable and go on searching from 1st index onward. If you find the match stop else go all the way upto end of the array and report that match not found. This can be done in linear time O(N) where N is the size of the array. No need to have two loops and hence increase the time complexity to O(N^2)
boolean sameAsFirstElem(Object[] array) {
boolean isEqual = false; //Assume match will not be there, if we come across any,
// we will set it to true
int firstElement = IntValue(array[0]);
for (int i = 1; i < array.length; i++) {
if (IntValue(array[i]) == firstElement) {
isEqual = true; //Indicating that match has found
}
}
return isEqual;
}
I am assuming that IntValue(Object) return int, and hence the int firstElement, and taking Object as a parameter.
I'm trying to see if any series of data, beginning at array position 0, is contiguous in the sense that array[0] has a numerical value of 0, array[1] has a numerical value of 1, and so on. For example:
private void isContiguous(int[] array, int position){
for(int i = 1; i < array.length; i ++){
if(!array[i].equals(null)){
long previous = this.extract_long(array[i - 1], OFFSET);
long current = this.extract_long(array[i], OFFSET);
if((previousOffset/PACKET_LENGTH) < ){
}
}
}
}
is about as far as I can think of for a general solution. This is kinda bending my mind so it'd be nice to have some help :)
Something to start with:
public static boolean isContiguous(int[] array) {
for (int i = 0; i < array.length-1; i++) {
if (array[i+1]-array[i] != 1) {
return false;
}
}
return true;
}
(I don't know why you need position, OFFSET, and so on, but the above code should fulfill the written requirement)
First of all you if you are storing primitive int in your array, they can never have a null value! The array itself might be null, but the values cannot!
Secondly if all you want to check is if array[0]==0, array[1]==1, array[2]==2 then your code should be as simple as this:
private boolean isContiguous(int []array) {
if( array == null ) return false;//a null array cannot be contiguous as it doesn't contain any elements!
for( int i = 0; i < array.length; i++ )
if( array[i] != i ) return false;
return true;
}
Would this not work?