In this program, I am getting incorrect output for the ArrayList.
In the first line, it always prints every single element of the ArrayList horizontally.
It then will correctly print the ArrayList.
Can someone take a look at the code and see if I did something wrong? I will show you the two classes.
Class 1:
public class contactDriver
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println ("What would you like to do?");
int answer;
System.out.println ("Press 1 to add a contact.");
System.out.println ("Press 2 to display all contacts.");
answer = scan.nextInt();
ArrayList<Contact> contacts = new ArrayList<Contact>();
contacts.add(new Contact("Patrick McGee", "334-555-8860", "pmcgee123#gmail.com"));
contacts.add(new Contact("John Appleseed", "142-555-6740", "jappleseed99#gmail.com"));
contacts.add(new Contact("Matt Jordan", "213-555-2323", "mjordan23#gmail.com"));
contacts.add(new Contact("Kanye East", "255-434-9909", "keast123#gmail.com"));
contacts.add(new Contact("Derrick Flower", "144-555-1111", "dflower1#gmail.com"));
if (answer == 1){
System.out.println ("Please enter the first and last name of the contact.");
String name = scan.next();
scan.nextLine();
System.out.println ("Please enter the phone number of the contact.");
String num = scan.next();
scan.nextLine();
System.out.println ("Please enter the email of the contact.");
String email = scan.next();
scan.nextLine();
contacts.add(new Contact(name, num, email));
}
if (answer == 2){
}
System.out.println(contacts);
for(Contact c : contacts) {
System.out.println(c);
Class 2:
public class Contact
{
public Contact(String name, String num, String email)
{
this.name = name;
this.num = num;
this.email = email;
}
public String getFirstname()
{
return name;
}
public String getNum()
{
return num;
}
public String getEmail()
{
return email;
}
public String toString()
{
return "Contact[" + name + ", " + num + ", " + email + "]";
}
private String name;
private String num;
private String email;
}
The output:
[Contact[Patrick McGee, 334-555-8860, pmcgee123#gmail.com], Contact[John Appleseed, 142-555-6740, jappleseed99#gmail.com], Contact[Matt Jordan, 213-555-2323, mjordan23#gmail.com], Contact[Kanye East, 255-434-9909, keast123#gmail.com], Contact[Derrick Flower, 144-555-1111, dflower1#gmail.com]
(all in one line).
Then prints:
Contact[Patrick McGee, 334-555-8860, pmcgee123#gmail.com]
Contact[John Appleseed, 142-555-6740, jappleseed99#gmail.com]
... so on.
Any ideas on the fix?
Thanks :)
The output
[Contact[Patrick McGee, 334-555-8860, pmcgee123#gmail.com], Contact[John Appleseed, 142-555-6740, jappleseed99#gmail.com], Contact[Matt Jordan, 213-555-2323, mjordan23#gmail.com], Contact[Kanye East, 255-434-9909, keast123#gmail.com], Contact[Derrick Flower, 144-555-1111, dflower1#gmail.com]
is due to
System.out.println(contacts);
This prints a String representation (by the method toString()) of the ArrayList contacts.
Edit
To don't get this output just delete that line. The for you are using to print each Contact looks fine:
for(Contact c : contacts) {
System.out.println(c);
}
You've an extra sysout statement which is printing the extra values. System.out.println(contacts); prints all the elements of the array list(All contacts in one line).
[Contact[Patrick McGee, 334-555-8860, pmcgee123#gmail.com], Contact[John Appleseed, 142-555-6740, jappleseed99#gmail.com], Contact[Matt Jordan, 213-555-2323, mjordan23#gmail.com], Contact[Kanye East, 255-434-9909, keast123#gmail.com], Contact[Derrick Flower, 144-555-1111, dflower1#gmail.com]
I guess you just wanted to print the plain text "contacts" and then print each and every contact, like this.
if (answer == 2){
System.out.println("contacts:"); // prints the plain text contacts
for(Contact c : contacts) {
System.out.println(c); // prints each contact using the toString() implementation provided by you
}
}
And if you do not want to print any text before printing each contact in the list, then just remove the extra sysout statement.
if (answer == 2){
// System.out.println(contacts); // not needed - commented/deleted
for(Contact c : contacts) {
System.out.println(c); // prints each contact using the toString() implementation provided by you
}
}
I don't really understand what the problem is. I'm not sure if the issue is it printing horizontally in one line (although it seems you have figured out how to get it to print on multiple lines), or if that the problem is that it is printing twice, once on one line and once on multiple.
I'm going to try and explain why it does what it does, maybe that will help you. If you can clarify what the issue is I'm sure I could help if this doesn't answer your question.
So, I'm not sure if this was intentional or not, but the if statement at the bottom of your first class has nothing inside its code block. It has no purpose unless you put code inside of it, if you don't plan on doing that, you could go ahead and remove it.
if (answer == 2){
}
System.out.println(contacts);
for(Contact c : contacts) {
System.out.println(c);
As you can see, the curly brace underneath it is stopping any of that code from being inside executed by the if statement. All of that code will be ran with the program regardless of whether or not the 1 or 2 was inputted. If you wish for some of that code underneath (or all) to be ran when number 2 is inputted, put it inside those curly braces. Otherwise you can leave it out and it will run regardless of the option selected.
There are two things happening at the end of the first class.
System.out.println(contacts);
This is telling it to print the entire arraylist in one line. That is why you get the horizontal line of all contacts.
for(Contact c: contacts){
System.out.println(c);
}
This is telling it to loop through the arraylist and print each individual contact on its own separate line. That is why you get the 2nd output. Please note that in your original post you were missing a curly brace after the bottom for loop, I added it in this post.
I hope that clears up any confusion. You should be able to choose if you want both of those outputs, or if you want one or both to run only when option 2 is selected. Again, I wasn't really sure what the issue was, so I tried to just give an overview of what the code was doing. I apologize that this post was so lengthy. Clearly the other people answering did a better job of using less text. Good luck on your code!
Related
I am literally know and get the hang of the java right now and I'm writing the program that helps to records patient'd ID in the Hospital, i'll show the whole code first,then, I will tell where you will, here is the code
package hospitalsrecord;
import java.util.*;
import java.io.*;
public class HospitalsRecord {
public static Scanner read = new Scanner(System.in);
public static ArrayList nameList = new ArrayList();
public static ArrayList patientAge = new ArrayList();
public static ArrayList Disease = new ArrayList();
public static ArrayList dateHospitalized = new ArrayList();
public static ArrayList roomNumber = new ArrayList();
//adding patient function
public static void AddNewPatient () {
//Ask patient's name
System.out.println("Please enter patient's name:");
String patientName = read.next();
//Ask Patient's age
System.out.println("Please enter patient's age:");
int age = read.nextInt();
//Ask patient's illness
System.out.println("Please enter patient's Disease name (also include accidents eg. Leg broke by Car Accident):");
String illness = read.next();
//Ask patient Hospitalized date
System.out.println("Please enter patient's Hospitalized date(Total days not included):");
String HPTLdate = read.next();
//Ask patient's room number
System.out.println("Please enter patient's hospitalize room number(3 degits):");
int HRN = read.nextInt();
//Confirmation
System.out.println("Doctor, would you like to confirm the following(y/n)?");
System.out.println("Name:" + patientName);
System.out.println("Age:" + age);
System.out.println("Disease:" + illness);
System.out.println("Date Hospitalized (HPTLD):" + HPTLdate);
System.out.println("Room Number:" + HRN);
String Confirm = read.next();
if (Confirm.equals("y")) {
nameList.add(patientName);
patientAge.add(age);
Disease.add(illness);
dateHospitalized.add(HPTLdate);
roomNumber.add(HRN);
} else {
AddNewPatient();
}
}
//Searching patient that listed
public static void searchPatient (){
}
//remove the patient function
public static void removePatient() {
}
//text printing function when strat the program
public static void selectorPage(){
System.out.println("Hello Doctor, welcome to Hospital Recorder v1.0.0");
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
//text printing simmilar to selecterPage function but perform after function
public static void selecterPageAfterAction() {
System.out.println("Your action has been performed, doctor");
System.out.println("Would you like to perform another action?(y/n)");
choiceSelection = read.next();
if (choiceSelection.equals("y")){
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
}
//Selection var
public static String option;
public static String choiceSelection;
//Main program
public static void main(String[] args) {
selectorPage();
switch (option) {
case("add"): {
AddNewPatient();
break;
}
case("search"):{
searchPatient();
break;
}
case("remove"):{
removePatient();
break;
}
case("end"):{
break;
}
default: {
System.out.println("Please enter the indentified option");
break;
}
}
if (option.equalsIgnoreCase("end")){
}
}
}
I hope you guys can read every line because it was so so so so complex, but for someone who can read all of it, i'll know that you'll say I still need more time for hard working, no worry i'll spend sometime to get most knowledge from you guys first, but still working hard for program to complete while waiting for answers! anyway the point that I want you guys to focus at this point:
if (option.equalsIgnoreCase("end")){
}
It maybe too blank because I've just newly add it while i'm working on it. So, what I want to know is at the if statement I type option.equalsIgnoreCase("end"), Am I explain the computer to do the following?
1.Compare the the String variable options with the String"end"?
2.Tell the computer to do the action inside if statement's when the String option wasn't the word end?
And please tell me how this method work, i don't clearly understand it. I understand like this "It compare two strings if it wasn't the same then it's result is true" I know my explanation is wrong so could you please help me? thanks again for helping if you can.
option.equalsIgnoreCase("end") - equalsIgnoreCase will ignore whether string is in lower case or uppercase.
So it will enter into if block only when option variable has either end or END.
Your first assumption is correct, you are asking to compare String whether it is equal to end. But Second one is wrong, from above code it will enter and execute statements present inside if only when option is end/END.
If you want to go inside If block when the option is not end then add a not like this if(!option.equalsIgnoreCase("end")).
I Hope this clears your doubt!
The class String has two methods to compare one String to another.
See the example below:
public static void main(String[] args) {
String str1 = "beer";
String str2 = "Beer";
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));
}
The first method equals() compares str1and str2and takes the case into consideration. Hence, the first comparison results in false, meaning Beer is not equal to beer.
The second method equalsIgnoreCase()does the same, except that it is not case-sensitive. Result of this comparison is true, meaning "ignoring the case, Beer is the same string as beer".
Hope this helps.
After reading the string methods description in a chapter i was trying to solve this programming exercise. here it is.
Write a program that asks for the user's name and then writes that name to the monitor with either "Ms." or "Mr." in front, depending if the name is for a female or male. Assume that the only female names are
Amy
Buffy
Cathy
and that the only male names are
Elroy
Fred
Graham
All other names will be echoed without a title. The program continues looping until the user hits "enter" without first typing a name.
C:\>java Title
Enter a name:
Amy Johnson
Ms. Amy Johnson
Enter a name:
Fred Smith
Mr. Fred Smith
Enter a name:
Zoltan Jones
Zoltan Jones
Enter a name:
C:\>
here is my code i know its wrong because i am very confused.
import java.util.Scanner;
class titleApplier {
public static void main(String[] args) {
String name;
String male = {"Elroy" , "Fred " , " Graham"};
String females = {"Amy", "Buffy", "Cathy"};
Scanner scan = new Scanner(System.in);
while(name.hasNext()) {
System.out.println("Enter a name ");
name = scan.nextLine();
if(name.equals(male)) {
System.out.println("Mr " + male);
}
else if (name.equals(females)) {
System.out.println(" Mrs " + females);
}
else {
System.out.println(scan.nextLine());
}
}
}
}
You're mostly on the right track, good work!
Instead of storing the names in Strings individually, you could just reference them directly in your if statements as such:
if(name.equals("Elroy") || name.equals("Fred") || name.equals("Graham")) {
System.out.println("Mr " + male);
}
Also, since you're providing first and last names, I don't think you should be matching with the equals method, but instead, checking to see if the name contains one of the names:
if (name.contains("firstName"))
As this looks like homework, try something along the same lines for the women yourself. Let me know if you have anymore questions. Good luck!
There are plenty of errors in your program which need to be corrected.Better give this a try.I have used BufferedReader since the Scanner class causes some problems while taking several input values within a loop.:-
import java.io.*;
import java.util.*;
class MF{
static boolean search(String arr[],String st){
for(int i=0;i<arr.length;i++){
if(arr[i].equalsIgnoreCase(st)==true)
return true;
}
return false;
}
public static void main(String args[])throws IOException{
String male[]={"Elroy","Fred","Graham"};
String fem[]={"Amy","Buffy","Cathy"};
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("Enter name:-");
String st=br.readLine();
if(st.equals("")==false){
StringTokenizer str=new StringTokenizer(st);
String tok=str.nextToken();
if(search(male,tok)==true)
System.out.println("Mr."+st);
if(search(fem,tok)==true)
System.out.println("Ms."+st);
}
else
break;
}
System.out.println("Program terminates.");
}
}
A few observations from your code:
male and females should be arrays of String, not just a single String. (i.e. String[] females = {"Amy", "Buffy", "Cathy"};
Watch out for leading and trailing white spaces. "Fred" and "Graham" will never pass a comparison unless you call the String.trim() method.
The method hasNext() is not defined in the String class; thus the compilation error. If you are writing this on an IDE such as Eclipse, read the errors you are getting and resolve them. Even for a beginner this should not be difficult at all.
Your program prompts the user AFTER the name is already entered. This might be easier if you enclose your code in a do/while rather than in a while loop. This is a matter of preference, or course. Also, normally you would want the user input to appear in the same line as the prompt, so use System.out.print() for the prompt instead of System.out.println().
When you are learning, you should always try your programs with very controlled inputs. In this case, you should have tried the program with a single male name and female name, and once you got that part working, then you should try expanding your solution to handle multiple names.
Your code allows to enter a LINE (words separated by space) rather than a String (array of characters with no white spaces). Therefore, you need to break that line into tokens (words) and examine either the first token (first name) or the second token (last name) and compare it to the names in the array. Otherwise, the equals() method will return false. This is because 'Elroy Smith' is not equal to 'Elroy'. You can do what I just explained, or use other String methods such as contains() or startsWith().
You should append the title to the entered name, and not the first name in your String array. Instead of outputting "Mrs. Amy", your program should output "Mrs. Amy Smith".
Your while() clause does not capture this requirement: "The program continutes looping until the user hits "enter" without first typing a name." This method will always return true even if the line has a length of zero. Instead, use the String entered and loop only if the length of the String entered is larger than zero.
To eliminate unnecessary processing, you can use a boolean variable to see if the name has been found, in order to break (exit loop) or continue (skip to next iteration).
This is one potential solution (might not be the most effective, but easy for you to follow):
public static void main(String[] args)
{
String name;
String[] males = {"Elroy", "Fred ", " Graham"};
String[] females = {"Amy", "Buffy", "Cathy"};
Scanner scan = null;
do
{
System.out.print("Enter a name: ");
scan = new Scanner(System.in);
name = scan.nextLine();
boolean found = false;
// Search all possible male names
for (String temp: males)
{
if (name.startsWith(temp))
{
System.out.println("Mr. " + name + "\n");
found = true;
break; // stop looping if found
}
}
if (found) { continue; } // skip the rest of the loop if name has been found
// Search all possible female names (only if name has not been found)
for (String temp: females)
{
if (name.startsWith(temp))
{
System.out.println("Ms. " + name + "\n");
found = true;
break;
}
}
if (name.length() > 0 && !found)
{
// A name was entered but it was never found
System.out.println("Unknown name entered.\n");
}
} while (name.length() > 0);
scan.close();
}
The output:
Enter a name: Fred Smith
Mr. Fred Smith
Enter a name: Buffy Vampire Slayer
Ms. Buffy Vampire Slayer
Enter a name: Cathy Doe
Ms. Cathy Doe
Enter a name:
Exiting program.
I'm making a program that reads a person's name and age, and when "zzz" is entered, it prints the names and ages of everyone who's 18 or older. Also, I want to calculate the percentage of people who's 18 or older. But, here's the problem: the code i'm posting bellow, only prints the first name (example: "Ricardo Almeida" and age "19". Output: "Ricardo : 19", but i want "Ricardo Almeida : 19). The percentage calculation has a error too but i cant figure out whats wrong. It gives 0 all the times. (DONE!) Thanks in advance to anyone who's reading this and trying to help.
PS: I dont want to use arrays! I already learned how to use them, but i want to know how to solve this without using them :)
package javaapplication38;
import java.util.Scanner;
public class JavaApplication38 {
private static final Scanner in=new Scanner(System.in);
private static String metodo1(String name, int age) {
String frase="";
if (age==18 | age>18) {
frase=String.format("%s : %d %n",name,age);
}
return frase;
}
public static void main(String[] args) {
int age, counter1=0, counter2=0;
String name, acumtxt="", aux;
do {
System.out.print("Name: ");
name=in.next(); in.nextLine();
if (!"ZZZ".equalsIgnoreCase(name)) {
counter1++;
do {
System.out.print("Age: ");
age=in.nextInt();
} while (age<=0);
if (age==18 | age>18) {
counter2++;
}
aux=metodo1(name,age);
acumtxt+=aux;
}
} while(!"ZZZ".equalsIgnoreCase(name));
System.out.print(acumtxt);
if (counter1>0) {
System.out.println("The percentage of people who's 18 or older is "+ (counter2/counter1) +"%.");
}
}
}
It seems that your problem is here
name=in.next(); in.nextLine();
In this code next() reads and returns only one word from line until it finds whitespace or end of line. Rest of it is consumed with readLine(), but you ignore its result. Try maybe to with
name=in.nextLine();
to read entire line.
After that you will also have to change
age=in.nextInt();
and either use
age=Integer.parseInt(in.nextLine());
or add in.nextLine() after it to also consume new line marks which would affect next name question.
age=in.nextInt(); in.nextLine();//add in.nextLine(); to consume new line marks
in.next() will read until there is a whitespace. You can use in.nextLine (http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()) or use [BufferedReader](http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html) instead, and you can call the readLine() method.
Apologies for posting about this topic twice today, this one is a different question. So I am working on a java problem at the moment where I am creating a program that simulates the old TV quiz show, You Bet Your Life. The game show host, Groucho Marx, chooses a secret word, then chats with the contestants for a while. If either contestant uses the secret word in a sentence, he or she wins $100.00.
My program is meant to check for this secret word.
Here is my code:
import java.util.Scanner;
public class Groucho{
String secret;
Groucho(String secret){
this.secret = secret;
}
public boolean saysSecret(String line){
if(secret.equals(line)){
return(true);
}
else{
return(false);
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String line = in.nextLine();
Groucho g = new Groucho(line);
while (in.hasNextLine()) {
String guess = in.nextLine();
/*Not sure about these next two lines:
*String answer = g.saysSecret(guess);
*/System.out.println(answer);
}
}
}
When I run it nothing happens. I thought it should be returning true or false? What I would actually like it to do is if the line contains the secret word, it prints a message that says “You have won $100” and tells what the secret word is. Could anyone point me in the right direction?
Many thanks
Miles
As Sotirios points out, you should use saysSecret(String) to check if the guess is correct.
So the loop could look like:
while (in.hasNextLine()) {
String guess = in.nextLine();
if (g.saysSecret(guess))
{
System.out.println("You got it! The word was: "+g.secret);
} else {
System.out.println("Aw, try again.");
}
}
Your code does not work because you are assigning a boolean value to a String. You should compare the return value of g.saysSecret(guess), and then if this value is true print your successful message (or even print a failure message if this value is false).
Also, you have said:
What I would actually like it to do is if the line contains the secret word ...
so
secret.equals(line)
is not what you want since that will be true only if the entire line is equal to the secret word. For search for a word inside a line you could use:
line.contains(secret)
or maybe you need a more elaborated method for case insensitive matchs and so on.
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(""))) {