2 Replies - 232 Views - Last Post: 06 October 2012 - 05:50 PM Rate Topic: -----

#1 mike31s  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 43
  • Joined: 05-October 12

Double printing method value

Posted 06 October 2012 - 05:29 PM

Hi

I am trying to output results of a linear search with the following pieces of code:

My Print Method:
System.out.print("\nEnter a value for linear search ---> ");
		int key =input.nextInt();
		if (linear_search(array,key) == -1)
			System.out.println("Value not found");
			else System.out.println("The value is indexed at [" + linear_search(array,key) + "]");

My Search Method:
	public static int linear_search(int[] list, int key){
		int comparisonCount = 0;
		for (int i = 0; i<list.length; i++){
			comparisonCount++;
			if (key == list[i]){
				System.out.print(comparisonCount + " comparisons were made. ");
				return i;
			}
		}
		return -1;
	}


My issue is that the bolded area is printing twice. This is what my output is looking like:

9936 9895 9637 9293 7951 7696 7667 6073 3019 2565
1178 806 183
Enter a value for linear search ---> 183
13 comparisons were made. 13 comparisons were made. The value is indexed at [12]


How can I get rid of the duplicated line?

Thanks for any advice!

Is This A Good Question/Topic? 0
  • +

Replies To: Double printing method value

#2 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,141
  • Joined: 14-September 07

Re: Double printing method value

Posted 06 October 2012 - 05:34 PM

Don't call the function twice. It gets called once in the if conditional and then again if the else fires. Call it once before if, store the return value and key off of that.
Was This Post Helpful? 1
  • +
  • -

#3 mike31s  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 43
  • Joined: 05-October 12

Re: Double printing method value

Posted 06 October 2012 - 05:50 PM

aha!

changed the first code to this

System.out.print("\nEnter a value for linear search ---> ");
		int key =input.nextInt();
		int returned = linear_search(array,key);
		if (returned == -1)
			System.out.println("Value not found");
			else System.out.println("The value is indexed at [" + returned + "]");


Thanks for the help! I'm learning it is better to work with variables instead of the method itself.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1