Searching an element in an array - java

I have to write a program having 3 parallel arrays one that holds 4 digit student ID the second the student Name and the last one that holds the GPA and the size of the arrays have to be 10
also the program be able to do a Student ID search and if it doesnt exist to show an error message
the first part works fine but when it comes to the searching it doesnt work
import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.util.Scanner;
public class StudentIDArray
{
public static void main(String[] args)
{
int option;
String inputString;
inputString = JOptionPane.showInputDialog("Welcome"
+" Choose the option you will like"
+ " \n1. Enter Student Information "
+ "\n2. Search for Student");
option = Integer.parseInt(inputString);
if(option ==1)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of the Student");
String[] studentname = new String[10];
for(int i =0; i<studentname.length; i++)
{
studentname[i] = in.nextLine();
}
System.out.println("Enter the 4 digit Student ID");
int[] studentID = new int[10];
for(int x=0; x<studentID.length; x++)
{
studentID[x] = in.nextInt();
}
System.out.println("Enter the Student's Grade Point Average");
int[] gpa = new int[10];
for(int y=0; y<studentID.length; y++)
{
gpa[y] = in.nextInt();
}
}
else
{
searching();
}
}
public static void searching()
{
int idnumber,
results;
int[]studentID = null;
String inputString;
inputString = JOptionPane.showInputDialog("Please Enter the ID number");
idnumber = Integer.parseInt(inputString);
results = sequentialSearch(studentID, idnumber);
if (results == -1)
{
System.out.println("no information");
}
else
{
System.out.println("yeii congrats");
}
}
public static int sequentialSearch(int[] studentID, int value)
{
int index;
int element;
boolean found;
index =0;
element = -1;
found = false;
while(!found && index < studentID.length)
{
if (studentID[index] == value)
{
found = true;
element = index;
}
index++;
}
return element;
}
}

The primary issue is that you are declaring the studentID array locally to your methods.
Make it a class member instead (an instance member would be preferred, but all your methods are static), so that your methods are working on the same array, not on different ones:
public class StudentIDArray
{
private static int[] studentID = new int[10];
...
Note that this limits the number of entries to the size of the array and you will get exceptions if you exceed these limits. Consider using a Vector or an ArrayList instead.

searching(studentID);
Pass the studentID array to the searching method instead of declaring it again.
public static void searching(int[] studentID)
{
int idnumber,
results;
//int[]studentID = null;
String inputString;
inputString = JOptionPane.showInputDialog("Please Enter the ID number");
idnumber = Integer.parseInt(inputString);
results = sequentialSearch(studentID, idnumber);
if (results == -1)
{
System.out.println("no information");
}
else
{
System.out.println("yeii congrats");
}
}
public static int sequentialSearch(int[] studentID, int value)
{
int index;
int element;
boolean found;
index =0;
element = -1;
found = false;
while(!found && index < studentID.length)
{
if (studentID[index] == value)
{
found = true;
element = index;
}
index++;
}
return element;
}
A better approach would be to keep it as a static/class variable as #Andreas pointed out.

These are the Running Steps of Program....
First Step => Enter Size of Array.
Second Step => Enter Member of Array.
Third Step => Enter Searching Integer of Array.
import java.util.Scanner;
public class Searching
{
public static void main(String[] args)
{
int temp =-1;
Scanner user_input=new Scanner(System.in);
System.out.println("Enter Size Of Array ");
int Size=user_input.nextInt();
int[] a=new int[Size];
//Scan input Array.
System.out.println("Enter element Of an Array...");
for(int j=0;j<Size;j++)
{
a[j]=user_input.nextInt();
}
System.out.println("The contents of the Array are :");
//Print input Arrray
for(int i=0;i<a.length;i++)
{
System.out.println("array[" + i + "] = " + a[i]);
}
System.out.println("Enter Integer For Searching..");
int Search=user_input.nextInt();
//Searching in an Array.
for(int index=0;index<a.length; index++)
{
if(a[index]==Search)
{
temp=index;
break;
}
}
if(temp!=-1)
{
System.out.println(" The search element is : " + Search);
System.out.println(" It is found in the array at position : " + temp);
}
else
System.out.println("\n Element not Found..");
}
}

Related

It only gives one string as the output

If I enter 3 objects
aakash
12323
aakshit
24r352
rahul
12323
If i give this as a input and enter search string as 'aa' then it gives only first string that matches the search ouput will be
aakash
12323
why not aakshit also
import java.util.Scanner;
import java.io.*;
public class DA_2_searching {
String name,phone_number;
Scanner s = new Scanner(System.in);
DA_2_searching()
{
System.out.print("Enter the Details");
name=s.nextLine();
phone_number= s.nextLine();
}
void search()
{
String search;
search=s.nextLine();
if(name.startsWith(search))
{
System.out.println(name);
System.out.println(phone_number);
}
}
public static void main(String args[])
{
int n;
Scanner s = new Scanner(System.in);
n= s.nextInt();
DA_2_searching obj[]= new DA_2_searching[n];
for(int i=0;i<n;i++)
{
obj[i]= new DA_2_searching();
}
for(int i=0;i<n;i++)
{
obj[i].search();
}
}
}
The reason for your problem is, that you only search for one object at a time. Your for loop that calls the search() function only compares one object to a search input at a time.
In the for loop, you are only calling the search function for one DA_2_searching object (the one with index i - obj[i]). But you want to search in every DA_2_searching object you created, that means you have to rework the search() function so that it gets all DA_2_searching objects and compares them to the search-String.
Here's my solution:
import java.util.Scanner;
public class DA_2_searching {
private String name, phone_number;
private static DA_2_searching[] allPersons;
private static Scanner s = new Scanner(System.in);
public DA_2_searching() {
System.out.println("Enter the Details: ");
System.out.print("Name: ");
this.name = s.next();
System.out.print("Phone-Number: ");
this.phone_number = s.next();
System.out.println("\nNext: ");
}
public static void search() {
System.out.println("Type a word to search for: ");
String toSearch = s.next();
for(DA_2_searching person : allPersons) {
if(person.name.contains(toSearch)) { //contains is better for searching.
System.out.println("Result: " + person.name + " | " + person.phone_number);
}
}
System.out.println("\n");
if(!toSearch.equals("exit")) {
search();
}
}
public static void main(String args[]) {
System.out.print("Amount of Entries: ");
int n = s.nextInt();
System.out.println("");
allPersons = new DA_2_searching[n];
//Creating Persons
for(int i = 0; i < n; i++) {
allPersons[i] = new DA_2_searching();
}
//initializing search
search();
}
}
In your current code you search for a String in every iteration. You read in a String and check if this String equals Array[0] then you print it. Then you read in a String again and check if it is equal to Array[1]... and so on. What you want is a search in the whole Array.
A simple solution would be to read in the String before the 2nd loop and pass the
string into search();
void search(String search) {
if (name.startsWith(search)) {
System.out.println(name);
System.out.println(phone_number);
}
}
public static void main(String args[]) {
int n;
Scanner s = new Scanner(System.in);
n = s.nextInt();
DA_2_searching obj[] = new DA_2_searching[n];
for (int i = 0; i < n; i++) {
obj[i] = new DA_2_searching();
}
String search = new String();
search = s.nextLine();
for (int i = 0; i < n; i++) {
obj[i].search(search);
}
}

I have been asked to make an Create a new integer array with 16 elements

Java code (not Java script). I was asked to create a new integer array with 16 elements.
Only integers between 1 and 7 are to be entered in the array from user (scanner)input.
Only valid user input should be permitted, and any integers entered outside the bounds (i.e. < 1 or > 7 should be excluded and a warning message displayed.
Design a program that will sort the array.
The program should display the contents of the sorted array.
The program should then display the numbers of occurrences of each number chosen by user input
however i have been trying to complete this code step by step and used my knowledge to help me but need help my current code is under I would appreciate if some one is able to edit my code into the above wants.I know it needs to enter the array by user input store and reuse the code to sort the numbers into sort the array.
The result should print out something like this like this
“The numbers entered into the array are:” 1, 2,4,5,7
“The number you chose to search for is” 7
“This occurs” 3 “times in the array”
import java.util.Scanner;
public class test20 {
public static void main (String[] args){
Scanner userInput = new Scanner (System.in);
int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6};
int count = 0;
int input = 0;
boolean isNumber = false;
do {
System.out.println ("Enter a number to check in the array");
if (userInput.hasNextInt()){
input = userInput.nextInt();
System.out.println ("The number you chose to search for is " + input);
isNumber = true;
}else {
System.out.println ("Not a proper number");
}
for (int i = 0; i< nums.length; i++){
if (nums [i]==input){
count ++;
}
}
System.out.println("This occurs " + count + " times in the array");
}
while (!(isNumber));
}
private static String count(String string) {
return null;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class test20 {
private static int readNumber(Scanner userInput) {
int nbr;
while (true) {
while(!userInput.hasNextInt()) {
System.out.println("Enter valid integer!");
userInput.next();
}
nbr = userInput.nextInt();
if (nbr >= 1 && nbr <= 7) {
return nbr;
} else {
System.out.println("Enter number in range 1 to 7!");
}
}
}
private static int count(int input, int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == input){
count++;
} else if (nums[i] > input) {
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int[] nums = new int[16];
for (int i = 0; i < nums.length; i++) {
nums[i] = readNumber(userInput);
}
Arrays.sort(nums);
System.out.println ("Sorted numbers: " + Arrays.toString(nums));
int input = 0;
while(true) {
System.out.println("Search for a number in array");
input = readNumber(userInput);
System.out.println("The number you chose to search for is " + input);
System.out.println("This occurs " +
count(input, nums) + " times in the array");
}
}
}
Because the array is sorted, I break the loop if an element larger than the one we're looking for is found; if we encounter a larger one then no other matches can be found in the rest of the array.

How do I display a string from an array from user input?

I have an array of 8 strings
(Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi")
all referenced by "county"
I'd prompt the user to input a number of 1-8 (iVal), 1 being Carter, 2 being Cocke, etc...
Is there a way I could do this other than using a switch statement?
Also, how would I go about this if the user were to input Washington I'd display "Washington is in the array" and the opposite if the string isn't in the array?
Thanks in advance.
Here is my array.
String [] county = {"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
for (int i = 0; i< county.length; i++)
{
System.out.print (county [i]+ "\n");
}
To prompt the user to enter a county, and then display it (without a switch) is simple enough. You could use something like,
String[] county = { "Carter", "Cocke", "Washington", "Greene",
"Hawkins", "Johnson", "Sullivan", "Unicoi" };
Scanner scan = new Scanner(System.in);
for (int i = 0; i < county.length; i++) {
System.out.printf("%d %s%n", i + 1, county[i]);
}
System.out.println("Please select a county from above: ");
int choice = scan.nextInt();
if (choice > 0 && choice <= county.length) {
System.out.println("You selected: " + county[choice - 1]);
} else {
System.out.println("Not a valid choice: " + choice);
}
As for testing if a String array contains a particular String you could write a utility function using the for-each loop like
public static boolean contains(String[] arr, String val) {
if (arr != null) {
for (String str : arr) {
if (str.equals(val)) {
return true;
}
}
}
return false;
}
i was working on the same thing, use ArrayList. this was my code
import java.util.*;
public class Practice{
public static void main(String[] args){
ArrayList<String> mylist = new ArrayList<>();
mylist.add("Maisam Bokhari");
mylist.add("Fawwad Ahmed");
mylist.add("Ali Asim");
mylist.add("Maheen Hanif");
mylist.add("Rimsha Imtiaz");
mylist.add("Mugheer Mughal");
mylist.add("Maaz Hussain");
mylist.add("Asad Shahzada");
mylist.add("Junaid Khan");
System.out.println("Name of the student: "+mylist);
}
}
now if u want a specific name from the list put this in system.out.println
System.out.println("Name of the student: "+mylist.get(1));
now the trick is to let the user enter the number in get( )
for this i made this program, here is the code
first make a scanner
Scanner myScan = new Scanner(System.in);
int a = myScan.nextInt();
System.out.println("Name of the student: "+mylist.get(a));
now it will only print that name depending on what number user have entered !!
I didn't understand well your questions, but I am going to answer on what I have understand.
In case you want to print the value of a given index by the user here is the solution:
Try an i with correct (existing) index and another one which does not exist e.g i=9
public class app
{
public static void main(String[] args)
{
String [] county ={"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
int i = 10; //i is the user input, you should do that using a BufferedReader or Scanner.
try
{
System.out.println(county[i-1]);
}
catch(IndexOutOfBoundsException e)
{
System.out.println("This index doesn't exist");
}
}
}
In case you want to check if a given word exist you can do it that way:
Again try a string which exist and one which does not exist.
public class app
{
public static void main(String[] args)
{
String [] county = {"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
String word = "Cocke"; //word is the user input, you should do that using a BufferedReader or Scanner.
boolean found = false;
for(int i=0; i<=7; ++i)
{
if(word == county[i])
{
found = true;
break;
}
}
if(found == true)
{
System.out.println(word + " is in the array.");
}
else
{
System.out.println(word + " is not in the array.");
}
}
}

how to match entries and display entries

I do not know how to display entries entered by user, and also to match and sort them.
import java.util.Scanner;
public class Case1
{
public static void main(String[] args) {
Scanner in=new Scanner (System.in);
System.out.println("Input a size of an array: ");
int size = in.nextInt();
int num[]=new int[size];
int i=0;
for (i=0;i<num.length;i++) {
System.out.println("Input a number: ");
num[i]=in.nextInt();
}
for (int c=0;i<num.length;c++){
for (int a=0; a<num.length;a++){
if(num[c]>num[a]){
int temp = num[c];
num[c]= num[a];
num[a]=temp;
}
}
}
for (int d=0;i<num.length;d++){
int value = 0;
if(value==num[i]) {
System.out.println("Match Found!");
}
}
}
}
help please.
It should look like this ->
import java.util.Scanner;
public class Case1
{
public static void main(String[] args) {
Scanner in=new Scanner (System.in);
System.out.println("Input a size of an array: ");
int size = in.nextInt();
int num[]=new int[size];
int i=0;
for (i=0;i<num.length;i++) {
System.out.println("Input a number: ");
num[i]=in.nextInt();
}
// DISPLAY ENTRIES
System.out.println("You entered the following entries.");
for (int index=0; index<num.length; index++) {
System.out.print(index + ": " + num[index] + " ");
}
// END DISPLAY ENTRIES
for (int c=0;c<num.length;c++){ // Changed i to c
for (int a=0; a<num.length;a++){
if(num[c]>num[a]){
int temp = num[c];
num[c]= num[a];
num[a]=temp;
}
}
}
for (int d=0;d<num.length;d++){ // Changed i to d
int value = 0;
if(value==num[d]) { // Changed i to d
System.out.println("Match Found!");
}
}
}
}
This should work, but when you asked in your question about matching, did you want to match each entry with 0 (which makes no sense) or did you want to compare each entry to 0?

How do I remove/not display the null values from two arrays?

My code works fine. However the output seems incorrect when I enter -1 from name or age input. How do I remove null values and "-1" and display the existed array?
import java.util.Scanner;
public class quizLoop {
private static Scanner key = new Scanner(System.in);
private static Scanner keyNum = new Scanner(System.in);
public final static int arrayLoop = 5;
public static String[] nameList = new String[arrayLoop];
public static int[] age = new int[arrayLoop];
public static void main(String[] args) {
System.out.println("NAME & AGE SYSTEM\n-----------------\n");
for(int i=0; i<arrayLoop; i++) {
System.out.print("Name: ");
nameList[i] = key.nextLine();
if(nameList[i].equals("-1"))
break;
System.out.print("Age: ");
age[i] = keyNum.nextInt();
if(age[i] < 0)
break;
}
System.out.println("----------");
for(int i=0; i<nameList.length; i++) {
System.out.println(nameList[i] + " " + age[i]);
}
}
}
Currently, when you input -1, the loop exits. That is, as soon as you input -1, the loop is not run again. This is because you use the break statement.
If you'd like to let -1 allow the user to start the current entry again, you'll need to do two things:
if (nameList[i].equals("-1")) {
// Take the loop variable down one.
i--;
// Instead of break, continue to the next iteration.
continue;
}
If you want to keep the loop how it is, but only print non-null values, modify your printing code:
for(int i=0; i<nameList.length; i++) {
if (nameList[i] == null || nameList[i].equals("-1") || age[i] < 0) {
// Invalid; go to the next one.
continue;
} else { // (not strictly necessary)
System.out.println(nameList[i] + " " + age[i]);
}
}
Try to use a List instead a Array, something like this:
import java.util.Scanner;
public class quizLoop {
private static Scanner key = new Scanner(System.in);
private static Scanner keyNum = new Scanner(System.in);
public final static int arrayLoop = 5;
public static List<String> nameList = new ArrayList<String>();
public static List<Integer> ages = new ArrayList<Integer>();
public static void main(String[] args) {
System.out.println("NAME & AGE SYSTEM\n-----------------\n");
while (true){
System.out.print("Name: ");
String name = key.nextLine();
if(name.equals("-1"))
break;
System.out.print("Age: ");
Integer age = keyNum.nextInt();
if(age < 0)
break;
nameList.add(name);
ages.add(age);
}
System.out.println("----------");
for(int i=0; i<nameList.length; i++) {
System.out.println(nameList[i] + " " + age[i]);
}
}
}

Categories

Resources