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

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.");
}
}
}

Related

I want to find the index of the string in an array

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
}
}
}

How can I stop a program's input loop only if it receives a special input?

I am looking to have this output:
$ java Rp6
zipcode: 4328024
4328024: 浜松市立西小学校
zipcode: 9691622
not found
zipcode: -1
bye
$
The program should continue accepting zipcodes, until a value lower than 0 is inputted.
For the program I made, it stops after the first zipcode.
import java.util.Scanner;
class Rp6 {
static String[] zipcodes = new String[] { "100", "200", "300" };
public static void main(String[] args) {
int i = 0;
System.out.print("Zipcode: ");
Scanner scan = new Scanner(System.in);
int zipcodez = scan.nextInt();
for (String zip : zipcodes) { // loop through zipcodes
i++;
if (zipcodez == Integer.parseInt(zip)) {
System.out.println("found");
break;
} else if (i == 3 && zipcodez != Integer.parseInt(zip)) {
System.out.println("not found");
} else if (zipcodez <= 0) {
System.out.println("bye");
break;
}
}
}
}
I'm thinking of using a loop but not sure where to put the loop. Do you guys have any suggestions?
EDITED: I tried simplifying the code
The code currently only loops over the zipcodes: for (String zip : zipcodes)
If you have code that loads the zipcodes list, you should first loop through the file to load the list. Then once it is loaded, have a second loop on scan which will repeatedly get standard input.
Something like this:
import java.util.Scanner;
class Rp6 {
static String[] zipcodes = new String[] { "100", "200", "300" };
public static void main(String[] args) {
// Start an input loop to check the loaded zipcodes
Scanner scan = new Scanner(System.in);
int zipcodez = 0;
while (zipcodez >= 0) {
System.out.print("Zipcode: ");
zipcodez = scan.nextInt();
// stop the loop if the user enters -1
if (zipcodez < 0) {
System.out.println("bye");
break;
}
// check if the user's zipcode is in zipcodes
boolean found = false;
for (String zipcode : zipcodes) {
if (zipcodez == Integer.parseInt(zipcode)) {
System.out.println(zipcode);
found = true;
}
}
if (!found) {
System.out.println("not found");
}
}
}
}

Searching String trouble in single array for java

I am new to programming and I decided to learn Java. I had just finished reading about one dimensional array and I am having trouble with searching.
The summary of this program I had made is to ask the user how many students will be enrolled in the class. The user then inputs the name of the students based on the length of the array. Then I want the to be able to have the user search for the students name. How can i accomplish this? What I want to accomplish is when the user inputs the first name it will return the list of full names that has the matching first name. I really struggling with this. Please don't give any advanced methods. I would like to stay in pace pace with my book.
I am using introduction to java programming comprehensive version 10th edition.
import java.util.Scanner;
public class classSystem {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
}
public static String[] getStudentAttendance(int studentAmount)
{
Scanner input = new Scanner(System.in);
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++)
{
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String StudentSearch)
{
for (int count = 0; count < enrolledStudents.length; count++)
{
if(StudentSearch.equals(enrolledStudents[count]))
{
return getStudent;
}
}
}
}
I have updated your code. Please see the comments inline. Hope this helps.
import java.util.Scanner;
class classSystem {
static Scanner input; //created a static reference for Scanner
//as you will be using in both the methods
public static void main(String[] args) {
input = new Scanner(System.in); //creating the Scanner object.
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
input.nextLine(); //added this to consume new-line leftover
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
input.close(); //close the scanner
}
public static String[] getStudentAttendance(int studentAmount) {
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String studentSearch) {
boolean flag = false; //added flag, this will be true if name is found
//otherwise false
for (int count = 0; count < enrolledStudents.length; count++) {
if (studentSearch.equals(enrolledStudents[count])) {
flag = true;
break; //if name is found breaking the loop.
} else {
flag = false;
}
}
if (flag == true) //checking the flag here
return studentSearch + " is present in the class";
else
return studentSearch + " is not present in the class: ";
}
}
I am getting below result after running my code.
Looks like you already got the idea how to search using .equals() method. Assuming you'll fix getStudent() method by handling "not found" situation, you should be done.
Next, do you want to improve your search, is that your real question? That depends on what type of search do you want to implement. Partial name match, name starts with, ignoring upper/lower case, wildcard search are different options. If that is what you want, please add it to the question.

Searching an element in an 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..");
}
}

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