Searching an Array using a console interface - java

I posted a few days ago asking this question and got some great answers. the only problem is the code that I am currently using will only allow for a search to be made if only one object exists in the array.
Im currently using this:
private static void Search(Student[]Students)
{
// Create a scanner for input, and get the name for search
Scanner inputScanner = new Scanner(System.in);
System.out.println("Type student name for search:");
String studentName = inputScanner.nextLine();
// use for loop to search array.
for(int i = 0; i < Students.length; i++){
if(Students[i].getName().equals(studentName)){
// If student was found, print his details and return from this function.
System.out.println(Students[i]);
return;
}
}
// If we reach this point, it means the student was never found in the for loop.
System.out.println("Student not found.");
}
Ive tried using a While loop instead of a for loop which only game me the results of the first object with the searched objects name for some reason. Im in real need of some help here so any would be really great :)
I have noticed my if statement isnt right, it doesnt account for null values in the array and falls over, how would I fix this?

First, filter students by name and collect them to the found list:
List<Student> found = Stream.of(students)
.filter(s -> s.getName.equals(name))
.collect(toList());
then, print results
if (found.size == 0) {
System.out.println("No students found.");
} else {
found.forEach(System.out::println);
}
BTW, you can achieve this just by removing return out of the for loop in your code - it breaks the loop after the first match.

Your return here:
System.out.println(Students[i]);
return;
Means that you exit the method as soon as you have found the first match. Remove that and you will go on through and find them all.

Related

A method that I wrote with a scanner class doesn't seem to end

I wrote a method in order to get the choice of the user for the size of a grid. However, my code doesn't seem to work after executing the method, as it continues to run without end after I type in the response to console (if it matters, I am on repl.it). What is the issue with the code that prevents it from ending?
public static String createSize() {
int count = 0;
String answer = "";
Scanner sc = new Scanner(System.in);
System.out.println("How big do you want the grid? (Sizes: 4x4, 5x5, 6x6)");
String size = sc.nextLine();
//Checks if user-inputted answer matches possible answers
while (count < 1) {
if (size.equals("4x4") || size.equals("5x5") || size.equals("6x6")) {
count++;
answer = sc.nextLine();
}
else {
System.out.println("That was not a viable size. Please type a viable size.");
size = sc.nextLine();
}
}
sc.close();
return answer;
}
In the first If check in the while loop
Change
answer = sc.nextLine();
to
answer = size;
since u do not want the user to input size twice.
Your code should work fine now.
Let me know if anything isn't clear so I can modify and elaborate further
what's the main problem? I tried to run this code on all possible test cases and I didn't get any problem.
In the if statement you have answer = sc.nextLine(); which will again ask you for the input that's why the program was not executing further. If you pass input second time only then it will execute. Further in if statement answer wasn't assigned any value so even after entering two values it will not return anything.
Correction :-
if (size.equals("4x4") || size.equals("5x5") || size.equals("6x6")) {
count++;
answer = size;
}

Search For String in Multidimensional Array

I am trying to find a contact by searching the first two names of the array below and then update the phone number associated with the contact. In the coding I've provided, I can find the first name of the contact (strFirstName) in the outer loop but can't verify that it is associated with the appropriate last name (strLastName). Even tho in the array provided there are no duplicates of first or last name, I want my coding to be able to match the exact record.
After I find the appropriate record, I the need to prompt the user for the new phone number. I believe I can figure this part, but I'm open to ideas to accomplish this.
numContacts = the numbers of rows in the array
String [][] contactsArray = {
{"Emily","Watson","913-555-0001"},
{"Madison","Jacobs","913-555-0002"},
{"Joshua","Cooper","913-555-0003"},
{"Brandon","Alexander","913-555-0004"},
{"Emma","Miller","913-555-0005"},
{"Daniel","Ward","913-555-0006"},
{"Olivia","Davis","913-555-0007"},
{"Isaac","Torres","913-555-0008"},
{"Austin","Morris","913-555-0009"}
public static void updateContact(Scanner scanner, String[][] contactsArray, int numContacts) {
System.out.println("Updating contact");
System.out.print("Enter first and last name: ");
String strFirstName = scanner.next();
String strLastName = scanner.next();
for (int i=0; i < numContacts; i++){
System.out.println(i);
if (contactsArray[i][0].equals(strFirstName) ) {
for (int j = 0; j < 3;j++) {
System.out.println(j);
if (contactsArray[1][j].equals(strLastName) ) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
}
}
Appreciate all the help resolving this in advance.
I feel you are close to the solution. The string comparison with the last name is unfortunately incorrect.
In fact, you are doing contactsArray[i][0] for firstname, which is correct. However, you are doing contactsArray[1][j] for the lastname, which is incorrect. Maybe contactsArray[i][1] is more correct.
Then you could ask yourself if you really need your second loop? You actually just want to find a record given the first and lastname. Therefore, you only need one loop to iterate over your "records".
Finally, you should break out of your loop if the record was actually found, and print "yes". If none was found after the loop, you should print "no".

Read words until user writes 'end', then, order lexicographically(as in a dictionary), show the last word

User will enter words until the last word written is "end", then the code has to order lexicographically, as we have in a dictionary, all the words entered before 'end' and print the last word, the one classified the last.
//.....
Scanner word = new Scanner (System.in);
String keyword="end";
String finalstring;
String[] firststring= new String[1000]; //Don't know how to stablish a //dynamic string[] length, letting the user stablish the string[].length
for(int c=0;c<firststring.length;c++){
firststring[c]=word.next();
if(firststring[c].equals(keyword)){
finalstring=firststring[c].substring(0,c);
c=cadena.length-1; //To jump out of the for.
}
}
for (int c=0;c<finalstring.length();c++) {
for(int i=c+1;i<finalstring.length();i++) {
if (firststring[c].compareTo(firststring[i])>0) {
String change = firststring[c];
firststring[c] = firststring[i];
firststring[i] = change;
}
}
}
System.out.print("\nYou entered "end" and the last word classified is "+finalstring[finalstring.length()-1]); //Of course, error here, just did it to put one System.out.print of how should the result be.
}
}
This is what I tried, though, without any type of success, any help of yours will be a big help, thank you ALL!
Don't know how to stablish a dynamic string[] length, letting the user establish the string[].length
It is not necessary to do that. But here's how.
Approach #1: ask the user to give you a number and then allocate the array like this:
String[] strings = new String[theNumber];
Warning: the requirements don't say you are allowed to do that, and you may lose marks for deviating from the requirements.
Approach #2: use an ArrayList to accumulate a list of words, the use List.toArray to create an array from the list contents. (Read the javadocs for list to work it out.)
Of course, error here, just did it to put one System.out.print of how should the result be.
Yea. One problem is that the length is 1000, but you don't have 1000 actual strings in the array. The same problem affects your earlier code too. Think about is ...
I'm not going to fix your code to make it work. I've given you enough hints for you to do that for yourself. If you are prepared to put in the effort.
One more hint: you can / should use break to break out of the first loop.
I know some words are not in English but in Catalan, but the code can be perfectly understood, yesterday I finally programmed this answer:
public static void main(String[] args) {
Scanner entrada= new Scanner(System.in);
System.out.println("Escriu les paraules que vulguis, per acabar, usa la paraula 'fi'.");
String paraules = "";
int c=0;
do {
String paraula = entrada.next();
if (paraula.equals("fi")) {
c++;
} else {
if (paraula.compareTo(paraules) > 0) {
paraules = paraula;
}
}
} while (c==0);
System.out.println("L'última parala ordenada alfabèticament és "+paraules+".\n");
}
}

Inifnite loop while reading numbers

Basically I am trying to write a program that will read a finite set of values from the user then print the average. (I know how to do the calculations so I will leave those out.)
I am having a problem with the logic side of the loop.
I understand that everyone here would prefer that I attempted it but I am new to loops and I am having extreme difficulties understanding loop logic.
I am attempting to do this assignment for my class but the teacher is flying through material and does not help at all when questions are asked. When I ask for help with a problem he says do your best to attempt it and I will grade it accordingly?
I honestly do not know where to start.
import java.util.Scanner;
public class P4Point5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String Status = "";
int count = 0;
while (in.hasNext()) {
count++;
}
for (int i = 0; i < count; i++) {
//Do calculations here?
}
}
}
You never get the next element:
while (in.hasNext())
count++;
You are always on the 1st element and asking if there is a 2nd element.
You should use:
while (in.hasNext())
int next = sc.nextInt();
BTW: please avoid statement without curly brackets. It is the root of all evil.
When you read for the first time, you don't read anymore, so hasNext() will stay always true since there will always be next element, which is.. the current element you're reading.
One solution is to do something like that:
String input = null;
while((input = in.next()) != null) {
//...
}
You can try this:
while (in.nextInt() != 'SOME INT TO STOP LOOP')
count++;
Instead of verify every time if we have an entered number, we can verify if the entered number is an stop condition.

Java, how to compare Strings with String Arrays

I have been searching here for some time but haven't been able to find the answer to it.
I am basically required to use an array for this assignment from college. And then I am supposed to check that the input (which is also a String) matches whatever's stored within the String array.
I know one can easily compare Strings by using the .equals() method. However, the same method is not working with the String array.
I created the following example of code for the purpose of StackOverflow so you can use it to explain it to me, if you'd like.
What am I doing wrong?
import java.util.Scanner;
class IdiocyCentral {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
/*Prints out the welcome message at the top of the screen*/
System.out.printf("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf("%55s", "=================================\n");
String [] codes = {"G22", "K13", "I30", "S20"};
System.out.printf("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2], codes[3]);
System.out.printf("Enter one of the above!\n");
String usercode = in.nextLine();
if (codes.equals(usercode)) {
System.out.printf("What's the matter with you?\n");
}
else {
System.out.printf("Youda man!");
}
}
}
I apologize if this has been asked before and I just missed it, if its a double question, I will remove it.
I presume you are wanting to check if the array contains a certain value, yes? If so, use the contains method.
if(Arrays.asList(codes).contains(userCode))
Right now you seem to be saying 'does this array of strings equal this string', which of course it never would.
Perhaps you should think about iterating through your array of strings with a loop, and checking each to see if they are equals() with the inputted string?
...or do I misunderstand your question?
Iterate over the codes array using a loop, asking for each of the elements if it's equals() to usercode. If one element is equal, you can stop and handle that case. If none of the elements is equal to usercode, then do the appropriate to handle that case. In pseudocode:
found = false
foreach element in array:
if element.equals(usercode):
found = true
break
if found:
print "I found it!"
else:
print "I didn't find it"
If I understand your question correctly, it appears you want to know the following:
How do I check if my String array contains usercode, the String that was just inputted?
See here for a similar question. It quotes solutions that have been pointed out by previous answers. I hope this helps.
Instead of using array you can use the ArrayList directly and can use the contains method to check the value which u have passes with the ArrayList.
import java.util.Scanner;
import java.util.*;
public class Main
{
public static void main (String[]args) throws Exception
{
Scanner in = new Scanner (System.in);
/*Prints out the welcome message at the top of the screen */
System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf ("%55s", "=================================\n");
String[] codes =
{
"G22", "K13", "I30", "S20"};
System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
codes[3]);
System.out.printf ("Enter one of the above!\n");
String usercode = in.nextLine ();
for (int i = 0; i < codes.length; i++)
{
if (codes[i].equals (usercode))
{
System.out.printf ("What's the matter with you?\n");
}
else
{
System.out.printf ("Youda man!");
}
}
}
}

Categories

Resources