I have to search a string in an array from the user input, but I have an error in my logic. Even when the user input is in the array I still get "data not found"
I also have to display the index where the string is located in the array if it's found but got an error there too.
Below is the code I've tried.
This was the original question
create a program that ask user to insert 5 names.
store names in array
ask user to insert the name they want to find from the list created earlier
if name found, display "data found at [index]"
if not, display "data not found". Hint; use Java method equals to compare two strings.
package stringsearch;
import java.util.Scanner;
public class StringSearch
{
public static void main(String[] args)
{
int i;
Scanner sc = new Scanner(System.in);
String [] names = new String[5];
for (i = 0; i < names.length; i++)
{
System.out.print("Enter name " + (i + 1) + " > ");
names[i] = sc.nextLine();
}
System.out.print("Input Name to compare > ");
String inName = sc.nextLine();
if (names.equals(inName)){
System.out.println("Data found at ["+i+"]");
}
else
{
System.out.println("Data not found!");
}
}
}
You need to compare the value of inName with each of the values stored in the array, not with the array itself. You access each of the values stored in the array using the index starting with 0.
for (i = 0; i < names.length; i++) {
if (inName.equals(names[i])) {
System.out.println("Data found at [" + i + "]");
break;
}
}
// If the value stored in `inName` is found, the value of `i` will not reach up
// to the value equal to `names.length` because of the `break` statement. If the
// value of `i` has reached there, it means that the value stored in `inName`
// has not been found.
if (i == names.length) {
System.out.println("Data not found!");
}
Complete program:
import java.util.Scanner;
public class StringSearch {
public static void main(String[] args) {
int i;
Scanner sc = new Scanner(System.in);
String[] names = new String[5];
for (i = 0; i < names.length; i++) {
System.out.print("Enter name " + (i + 1) + " > ");
names[i] = sc.nextLine();
}
System.out.print("Input Name to compare > ");
String inName = sc.nextLine();
for (i = 0; i < names.length; i++) {
if (inName.equals(names[i])) {
System.out.println("Data found at [" + i + "]");
break;
}
}
// If the value stored in `inName` is found, the value of `i` will not reach up
// to the value equal to `names.length` because of the `break` statement. If the
// value of `i` has reached there, it means that the value stored in `inName`
// has not been found.
if (i == names.length) {
System.out.println("Data not found!");
}
}
}
A sample run:
Enter name 1 > John
Enter name 2 > Harry
Enter name 3 > Sam
Enter name 4 > Cristina
Enter name 5 > Manny
Input Name to compare > Sam
Data found at [2]
You are comparing the whole array to a single string, that will always return false.
It's the same as:
String[] names = {"a", "b", "c"};
names.equals("d");
Iterate the array to see if there string is there
int i = 0;
for (String item: names) {
if (item.equals(inName) ) {
return i;
}
i++
}
if (i == names.length ) {
// not found
}
Running example:
public class A {
public static void main(String...args){
String[] names = {"a", "b", "c"};
String inName = "d";
int i = 0;
for (String item: names) {
if (item.equals(inName) ) {
System.out.println(i);
break;
//return i;
}
i++;
}
if (i == names.length ) {
System.out.println(-1);
// not found
}
}
}
Related
What am I missing it keeps, coming back false on the first try. What do I need to change to make sure it scans to get rid of duplicates.
final int numPassengers = 4;
final int numShips = 2;
boolean input = false;
String[] travelerNames = new String[4];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < numPassengers; ++i) {
System.out.println("Enter traveler name ");
do {
travelerNames[i] = scanner.nextLine();
if(travelerNames[i].equals(travelerNames[i])) {
System.out.println("Names cannot match enter new name!");
input = false;
scanner.next();
}
else {
input = true;
}
} while(!input);
System.out.println(travelerNames[i]);
A simple solution would be to use an arraylist.
Arraylist has a method called contains.
List<String> names = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
if(names.contains(input)){
System.out.println("Name is duplicated");
}
else {
names.add(input);
}
I hope i could help you with your Problem
travelerNames[i] = scanner.nextLine(); Whoops... too late, it's already within the Array and it's in there before you get to check and see if it has been previously entered. Don't save a step here by popping the name into the Array right away, put the name into a String variable first then traverse the Array to see if that name already exists, for example:
for (int i = 0; i < numPassengers; ++i) {
String name = "";
while(name.isEmpty()) {
System.out.print("Enter traveler name #" + (i + 1) + ": -> ");
name = scanner.nextLine().trim();
if (name.isEmpty() || name.matches("\\d+")) {
System.out.println("Invalid Name Supplied! ("
+ name + ") Try again...\n");
name = "";
continue;
}
// Is the name already within the travelerNames[] Array?
for (String nme : travelerNames) {
if (nme != null && nme.equalsIgnoreCase(name)) {
System.out.println("Invalid Entry! The name '" + name
+ "' already exists! Try again...\n");
name = "";
break;
}
}
}
// Everything seems OK so add the name to the Array.
travelerNames[i] = name;
}
System.out.println();
System.out.println("The names contained within the Array:");
System.out.println(Arrays.toString(travelerNames));
When I insert the arguments the search always returns "not found" - even though the searched value was input into the array?
import java.util.Scanner;
public class assignment {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String searchValue = "";
String [] BookID = new String [3];
String [] Booktitle = new String [3];
//input the BookID
System.out.println("Enter the 12 BookID");
for (int a = 0 ; a < BookID.length; a++)
{
System.out.print("BookID :");
BookID[a] = sc.next();
}
//Input the book title
for (int b = 0 ; b < Booktitle.length ; b++)
{
System.out.print("Booktitle :");
Booktitle[b] = sc.next();
}
//The Linear search on BookID
System.out.print("Enter BookID to find :");
for(int c = 0; c < BookID.length; c++)
{
searchValue = sc.next();
if(searchValue.equals(BookID))
System.out.print("BookID is found : ");
else
System.out.print("BookID is not found : ");
}
}
}
I'm expecting the result to return like so: if input BookID 112. The Linear search would return "The BookID is found :" instead of the else statement.
Try printing out the value of the bookId you wanna find to see if there anything with the string that could cause it to not be equals. Also, you could convert the string to an integer with:
Integer.parseInt("BookId");
The equals would have less chance of failing, you could also change de the array for an array of int instead of String.
This code has some basic things right, but it could be a bit better. Some of the changes I made are for keeping Java conventions (so the code is easier to read and understand) and some are functional. I added them as comments.
import java.util.Scanner;
public class Assignment {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String searchValue = "";
String [] bookIDs = new String [3]; //lowercase for the attribute name (convention)
String [] bookTitles = new String [3]; //plural for the array (convention)
//input the BookID
System.out.println("Enter the Book ID");
for (int i = 0 ; i < bookIDs.length; i++) { //you can re-use the i in all loops
System.out.print("Enter " + i + " Book ID: ");
bookIDs[i] = sc.next();
}
//Input the book title
for (int i = 0 ; i < bookTitles.length ; i++) {
System.out.print("Enter " + i + " Book title: ");
bookTitles[i] = sc.next();
}
//The Linear search on BookID
System.out.print("Enter Book ID to find: ");
searchValue = sc.next(); //NOTE: this is your first mistake. read out of the loop
for(int i = 0; i < bookIDs.length; i++) {
if(searchValue.equals(bookIDs[i])) { //NOTE: this is your second mistake - you wanted the array value, not the array
System.out.println("BookID is found in position "+i);
break; //suggestion - stop the loop when found.
}
else {
System.out.println("BookID is not found in position "+i);
}
}
sc.close(); //NOTE: important to close scanners at the end.
}
}
Good luck with your studies.
I use sort() to sort my array alphabetically, but it does so from A-Z to a-z. I try to capitalize each word beforehand, but it doesn't work unless it's being printed out, which should be happening after the sorting. At the moment, with this code, it will list the pupils with capital letters, but if it was inputted as lowercase, it will be sorted as lowercase. Putting the capitalize() in the initial for loop, right after assigning the input to the array, doesn't work. Any solutions?
import java.util.Scanner;
import java.util.Arrays;
public class Pupils {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean loop = true;
int names = 0;
String[] ay = new String[1000];
for(int i = 0; loop == true; i++) {
System.out.println("Enter name: ");
ay[i] = scan.nextLine();
names++;
if (ay[i].equals("0")) {
loop = false;
ay[i] = " ";
}
}
String[] aay = new String[names - 1];
for(int i = 0; i < aay.length; i++) {
aay[i] = ay[i];
}
if (names == 1) {
System.out.print("There are no people in our class.");
} else if (names == 2) {
System.out.print("The person in our class is ");
} else {
System.out.print("The people in our class are ");
}
Arrays.sort(aay);
for(int i = 0; i < names - 1; i++) {
if(i == names - 2) {
System.out.print(capitalize(aay[i]) + ".");
} else if (i == names - 3) {
System.out.print(capitalize(aay[i]) + " and ");
} else {
System.out.print(capitalize(aay[i]) + ", ");
}
}
}
public static String capitalize(String line)
{
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
}
What about using Arrays.sort() with a Comparator? Note that there is a suitable comparator defined in String, so:
Arrays.sort(aay, String.CASE_INSENSITIVE_ORDER);
should do the job.
I suggest storing all the data in the array in lowercase. It will simplify sorting as well as search (if you search for a student in the array, and it was entered as, say "Walter" and you are looking for "walter", you won't find it. If you use lowercase both for storage and for search, it will work).
And since you capitalize the names for printing anyway, the names will still be displayed capitalized.
So instead of doing
ay[i] = scan.nextLine();
You can do:
ay[i] = scan.nextLine().toLowerCase();
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.");
}
}
}
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..");
}
}