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".
Related
System.out.println("How many teams are in this tournament?");
no_of_teams=kb.nextInt();
for(int x=1; x<=no_of_teams; x+=1)
{
System.out.println("Please enter the name of team " + x);
team=kb.next();
}
I would like to have team contain all the user inputs, so I can then use String.split later on in the program to output the team names once again.
I asked my original question on Reddit but to no avail, it went like this:
We have been asked to create a program which runs to collect data
based on a round robin soccer tournament for 'n' no. of teams. My
issue is when I must ask for all the team names at the beginning
(which I must) based on what no. of teams the user inputs of course, I
can do this with a for loop and the output is perfect:
input the code from up above here
However, as I am sure you are aware, this
basically means that team will now just be stored as whichever team
name was entered last as the for loop caused it to be overwritten.
This is a problem because later down in the program you are meant to
then output all the different team names for when they are playing
against each other but team is only storing one team name. Using
team1, team2, team3, etc. is impractical because the user can enter an
infinite amount for the number of teams. We are not allowed to use
arrays because we have not covered them yet, and by all accounts the
way I am to get around this is to use String concatenation and while
loops, but I am unsure how this would apply. Any help would be
gratefully appreciated! Thanks.
You can just append names to a String with an attached delimiter:
StringBuilder team = new StringBuilder();
for(int x=1; x<=no_of_teams; x+=1)
{
System.out.println("Please enter the name of team " + x);
//this will add a - after each name, and then you could split on the - character
team.append(kb.next()).append("-");
}
However, this is really not the best options. I would use an array to store names. The answer I gave t would return one big string, that you would have to split on the '-'.
After you got your string, you could split it by doing:
team.toString().split("-");
If you wanted to output all the team names you would do something like:
for(String aTeam : team.toString().split("-")){
System.out.println("Team Name: " + aTeam);
}
Actually, it is possible! You do not have to use arrays or lists provided by java for your convenience, even implicitly like the split method BlackHatSamurai provided in his answer. It's simple - you implement your own ArrayList! Well, ArrayList-like thing anyway.
class MyStringStringList {
private static final char delimeter = '%'; //just a character not in the input
private String internalMemory = "";
public void add(String s) {
internalMemory += s + delimeter;
}
public String getAll() {
return internalMemory;
}
public String get(int index) {
int delimeterCount = 0;
StringBuilder currentWord = new StringBuilder();
for (int j = 0; j < internalMemory.length(); j++) {
if (internalMemory.charAt(j) == delimeter) {
if (delimeterCount == index) {
return currentWord.toString();
} else {
delimeterCount++;
currentWord = new StringBuilder();
}
} else {
currentWord.append(internalMemory.charAt(j));
}
}
throw new ArrayIndexOutOfBoundsException(index);
}
}
I moved this code to a new class for clarity, but you could just paste the insides into your main class and use it from there.
Some usage:
MyStringStringList list = new MyStringStringList();
for (int x = 1; x <= no_of_teams; x += 1) {
System.out.println("Please enter the name of team " + x);
list.add(kb.next());
}
for (int i = 0; i < no_of_teams; i++) {
System.out.println("Team number " + i+1 + ": " + list.get(i));
}
Do note, that only a crazy person would do that. Inefficient, probably buggy, incomplete feature-wise... But if you are not mistaken, and you were in fact prohibited from using the built-in array or collections that could be the "Your rules are stupid" solution your teacher deserves.
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.
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");
}
}
in my program I want the user to be able to print an element from an array. This is how far I've and I can't think of what to put next?
public void viewClub() {
System.out.println("Please enter the name of the country whose details you would like to see");
String Name = input.next();
for (int i = 0; i < countryList.size(); i++) {
Country x = countryList.get(i);
if (Name.equalsIgnoreCase(x.getName())) {
}
You anyways have x.getName in which x points to ith element of the array. So even if you just do a sys out for
x.getName()
you will get the value.
Hope this be of some help
Happy Learning :)
You want to output the details of a country that the user inputs. To do this, you will need a function in your country class that returns a string containing the details of that country:
System.out.println(x.getCountryDetails());
You don't want to output the name, because the user already knows that.
After you find the country, you should break out of your loop, to stop further processing:
for (int i = 0; i < countryList.size(); i++)
{
if (name.equalsIgnoreCase(countryList.get(i).getname()))
{
System.out.println(countryList.get(i).getCountryDetails());
break; //Exit the for loop because you found the specified country
}
}
firstly you take a array in your program, then by using buffered input streams or any other take the input from the user, store it into the array and then print the array index which contain the values
I need to write a program that will have a user enter a list of tutor names. Only up to 10 peer tutors may be hired. Then, the program will present each name, based on a list alphabetized by last name. This is what I have so far, but it does not work and I don't know what to do. I need it to continue to run until I stop it and continue with more of the program.
import javax.swing.JOptionPane;
import java.util.Arrays;
public class Report {
public static void main(String[] args) {
int numTutors = 10;
String[] listNames = getTutorNames();
}
public static String[] getTutorNames() {
String firstName;
String lastName;
String[] listNames = new String[10];
for (int x = 0; x < listNames.length; x++) {
firstName = JOptionPane.showInputDialog(null, "Enter Tutor's First Name: ");
lastName = JOptionPane.showInputDialog(null, "Enter Tutor's Last Name: ");
if (firstName.equals("")) && lastName.equals("")) {
break; // loop end
}
listNames[x] = lastName + ", " + firstName;
}
return listNames;
}
}
Well, this is a first. IntelliJ didn't format the code correctly when I edited it, and I soon discovered this hit-list of errors. Just bear in mind - the code won't even compile, let alone run, until these are fixed.
int numTutors comes out of nowhere. If you want to define it, then do so outside of the method call and set it to an appropriate value.
public static void main(String[] args) {
int numTutors = 10;
String[] listNames = getTutorNames(numTutors);
}
These declarations are invalid:
String = firstName;
String = lastName;
You need some sort of variable name in between String and =.
You're also not matching the contract for what you're passing in to getTutorNames - either what you pass in or what you accept must change. I'm thinking that it's the latter.
You can't use == to compare String. You have to use .equals(). Which leads me to...
Your break is outside of your loop. Move it inside of the loop.
for (int x = 0; x < listNames.length; x++) {
firstName = JOptionPane.showInputDialog(null, "Enter Tutor's First Name: ");
lastName = JOptionPane.showInputDialog(null, "Enter Tutor's Last Name: ");
if (firstName.equals(" "))&&lastName.equals(" ")){
break; // loop end
}
}
..and that leads me to...
You don't put the values anywhere through the loop! You're just running the same code ten times! Place them into the array.
// after you check to see if the firstName and lastName are blank
listNames[x] = firstName + lastName; // I don't know what you want to do with them from here.
There is no .add() for an array. The above is how you enter elements into an array.
Your return is outside of your method block entirely. Move it into your method.
Now, these are the issues that I could find. Work on the compilation issues first, then one may talk about errors in code logic. If you can, snag a quiet moment and ensure you understand variable declaration and String comparison. I would strongly recommend the reading material found in the Java wiki tag.
So sorry for making an answer for something this small but your
If (firstName.equals("")) && lastName.equals("")) {
Should be replaced by
If ((firstName.equals("")) && lastName.equals(""))) {