Someone can fix or tell me what is wrong with this Java code? package projPak; i
ID: 640646 • Letter: S
Question
Someone can fix or tell me what is wrong with this Java code?
package projPak;
import java.util.*;
import javax.swing.JOptionPane;
public class Proj2 {
private int newArray[];
String input;
private int searchKey;
//More efficient binary search (sort array first)
//Create three private data members newArray[] of ints and string input
//and int searchKey
Proj2(){
input = " ";
searchKey = 0;
newArray = new int [50];
for(int i =0; i <newArray.length; i++) {
newArray[i]= i*2;
}
showArray();
}
//constructor - create on that initializes input to null, searchKey to zero
//and fills newArray with even numbers up to 100.
//Starting class method
public void startApp(){
//take input from the user asking to search for what value
input = JOptionPane.showInputDialog("Enter a search value: ");
searchKey = Integer.parseInt(input);
if(binarySearch()){
JOptionPane.showMessageDialog(null, "The value "+searchKey+" was found!");
}
else{
JOptionPane.showMessageDialog(null, "The value "+searchKey+" was not found!");
}
}
//class method binarySearch
public boolean binarySearch(){
int low = 0;
int high = newArray.length - 1;
int middle;
while(low <= high){
middle = (low + high)/ 2;
if(searchKey == newArray[middle]){
return true; //key found
}
else if(searchKey < newArray[middle]){
high = middle - 1;
}
else {
low = middle + 1;
}
}
return false;
}
public void showArray(){
for(int i = 0; i < newArray.length; i++){
System.out.print(newArray[i] + " ");
}
}
public static void main(String[] args) {
//create and instantiate an object of type Proj2
//use the object to start the application
Proj2 obj = new Proj2();
obj.startApp();
}
}
}
Explanation / Answer
Proj2(){
input = " ";
searchKey = 0;
newArray = new int [50];
for(int i =0; i <newArray.length; i++) {
newArray[i]= i*2;
}
showArray();
}
newArray.length......since you are using constructor to fill data...but newArray is empty at this spot..then length is always zero
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.