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(""))) {
Related
The repl.it link below takes you to a piece of code which I am currently working on. It is a test for creating a 2D array and searching through it for specific values. I would like to implement this into other code to allow a user to input an email, username and password while signing up and store it in a 2D array as a new account. Then during a login it will search for the password associated with the email entered and compare it to the password which is entered.
The code in main method is to allow me to create the 2D array which will store three accounts and enter test information. It then prints the 2D array to prove it has been created. The search method is meant to then search through the array for the password associated with an email which I enter. However, there is a problem with the code so that it never finds the email in the array. I have ensured it cycles through the array by making it print the email which it is meant to be comparing the value being searched for and then prints next. It does cycle through this array.
I believe the problem is when the code compares the entered value to the value the code has found. I do not know how to fix this as the code should find the email and be able to print the password.
This is likely an easy fix but I need some help.
Thank you for any responses.
https://repl.it/#Griff0408/ArrayTestCurrent#Main.java
import java.util.Scanner;
import java.util.Arrays;
class Main {
static int rowNumber = 3;
static int colNumber = 3;
static String[][] Accounts = new String[3][3];
public static void main(String[] args) {
for (int row=0;row<rowNumber;row++) {
for (int col=0;col<colNumber;col++){
Scanner sc = new Scanner(System.in);
if (col==0) {
System.out.println("Enter e-mail:");
String yourEmail = sc.nextLine();
Accounts[row][col] = yourEmail;
} else if (col==1) {
System.out.println("Enter Name:");
String yourName = sc.nextLine();
Accounts[row][col] = yourName;
} else {
System.out.println("Enter password:");
String yourPassword = sc.nextLine();
Accounts[row][col] = yourPassword;
}
}
}
System.out.println(Arrays.deepToString(Accounts));
search();
}
public static void search() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter email:");
String searchEmail = sc.nextLine();
boolean found = false;
int currentRow = 0;
while (found==false){
if (currentRow < rowNumber) {
String arrayEmail = Accounts[currentRow][0];
System.out.println(arrayEmail);
if (arrayEmail == searchEmail){
found = true;
System.out.println("Email: " + Accounts[currentRow][0] + "\nPassword: " + Accounts[currentRow][2]);
} else {
currentRow++;
System.out.println("next");
}
} else {
System.out.println("Email not found.");
found = true;
}
}
}
}
Strings in java are actually objects! So unlike primitive data types when two strings are compared with the equality operator we just compare whether those are the same object.
Fortunately there is a simple way to fix this. The equals method.
if (arrayEmail.equals(searchEmail)){
found = true;
System.out.println("Email: " + Accounts[currentRow][0] + "\nPassword: " + Accounts[currentRow][2]);
}
I have also provided a working REPL https://repl.it/#dehan/ArrayTestCurrent#Main.java
You are using == which is reference comparision parameter.
If you want to compare content use equals method.
The problem is most likely due to the fact that you use "==" to compare the strings.
"==" does not compare string values, it checks whether the two strings are the same object.
Instead of if (arrayEmail == searchEmail) use if (arrayEmail.equals(searchEmail))
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".
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.
How do I go about getting the result of all the string inputs to print as a list with out the use of arrays? For example, I'd like the list to print vertically, like below, rather than all on one line:
kidsname
bookname
kidsname
bookname
I appreciate any help which can steer me in the right direction!
package part3;
import java.util.Scanner;
public class listnames {
private static Scanner kb;
public static void main(String args[]) {
String finished;
String kidsname;
String storage = " ";
String bookname;
String storageb = " ";
String storagec = " ";
int noofchild;
kb = new Scanner(System.in);
System.out.print("How many Children do you have?");
noofchild = kb.nextInt();
for (int k = 1; k <= noofchild; k++) {
System.out.print("What is the kids name?");
kidsname = kb.next();
storage += (String.valueOf(kidsname) + "\t");
do {
System.out.print("What book did they buy?");
bookname = kb.next();
storageb += (String.valueOf(bookname) + "\t");
System.out.print("Do you want to finish? y/n ");
finished = kb.next();
storagec = (storage + ("\n-----------------------\n") + storageb);
} while (finished.equalsIgnoreCase("n"));
System.out.println();
System.out.print(storagec);
}
}
}
storageb +=(String.valueOf(bookname)+"\t"); --> storageb +=(String.valueOf(bookname)+"\n");
It's almost like you're doing too much here. You have kidsname and bookname already declared as variables, yet you're storing them with tabs appended to the end, which is overly verbose, and a bit confusing.
Furthermore, your do...while loop seems misplaced; you're always going to be overwriting the value of bookname if someone decides to continue (even by entering "&" they'll continue).
Lastly, since you know you're dealing with Strings, String#valueOf is unnecessary. In actuality, since you're going to be placing a new line after the tab character, the tab character is also unnecessary.
So, a few things:
Remove storagea, storageb, and storagec - they serve no real purpose.
Move your printing statement inside of the do...while. This way, you can print one child name per with multiple book names per iteration.
Change System.out.print to System.out.println. Everywhere.
Your printing statement would ultimately read like this:
System.out.println(kidsname + "\n-----------------------\n" + bookname);
EDIT: If you want bookname to hold more than one element, keep appending to it. Initialize it to the empty string, then when you read the line, append to it and append a newline as well.
bookname = kb.next() + "\n";
You keep outputting the string using System.out.print(). Try using System.out.println instead.
I am working on an assignment which is confusing to me. It requires me to write a method called processName() that accepts a Scanner for the console as a parameter and prompts the user to enter a full name, then prints the last name first and then the first name last. For instance, if I enter "Sammy Jankins", it would return "Jankins, Sammy".
My plan is to go through the string with a for loop, find an empty space, and create two new strings out of it—one for the first and last name each. However, I am not sure if this is the right path and how to exactly do this. Any tips would be appreciated, thanks.
Here is what I have so far:
import java.util.*;
public class Exercise15 {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
processName(inputScanner);
}
public static void processName(Scanner inputScanner) {
System.out.print("Please enter your full name: ");
String name = inputScanner.next();
System.out.println();
int n = name.length();
String tempFirst;
for (int i = 0; i <= name.length()-1; i++) {
// Something that checks the indiviual characters of each string to see of " "exists
// Somethow split that String into two others.
}
}
}
Why don't you simply use String#split?
I won't solve this for you, but here what you should do:
split according to spaces.
Check if the size of the array is 2.
If so, print the second element then the first.
Tip: Viewing the API can save a lot of efforts and time.
Why not just to say:
String[] parts = name.split("\\s+");
String formattedName = parts[1] + ", " + parts[0];
I am leaving it for you as an exercise to support names that contain more than 2 words, for example "Juan Antonio Samaranch" that should be formatted as "Samaranch, Juan Antonio".
Using StringTokenizer will be more easier. Refer http://www.mkyong.com/java/java-stringtokenizer-example/ for example.
You can replace for loop with the following code:
int spaceIdx = name.indexOf(' '); // or .lastIndexOf(' ')
if (spaceIdx != -1) {
int nameLength = name.length();
System.out.println(name.substring(spaceIdx + 1) + ", " + name.substring(0, spaceIdx));
} else {
// handle incorrect input
}
I think you should also consider such inputs - Homer J Simpson
1.Use the StringTokenizer to split the string .This will be very helpful when you are trying to split the string.
String arr[]=new String[2]; int i=0; StringTokenizer str=new StringTokenizer(StringToBeSplited,"");
while(str.hasMoreTokens()){
arr[i++]=new String(str.nextToken());
}
System.out.println(arr[1]+" "+arr[0]);
That's all