Transfering a non-static variable to static in JAVA? - java

Only my third week of class (new to programming).
I'm making a text-based story in Java, but I've come to a stump in the process. I have a static variable called "static String dogName;" that I'm trying to change the value of (only once). In the beginning of the game, the user has the option to name their dog. When I try to name the dog, the code skips the naming prompt because of the static String dogName.
I want to give the user the option to name their dog.
If there's a better way to do things in my code, please let me know.
Part of the code may not be complete like the decisions...
public static Scanner keyboard = new Scanner(System.in);
public static int choice;
// dogName is Dogs name forever a hundred times rick & morty
static String dogName;
public static void main(String[] args) {
int karma = 0;
// Dog stuff...
Dog Dandy;
Dandy = new Dog();
// Prologue
System.out.println("You're walking through an alley late at night "
+ ", you see a stray dog. What do you do? ");
System.out.println("[1] Approach");
System.out.println("[2] Attempt to touch");
System.out.println("[3] Give treat");
boolean running = true;
GAME:
while (running) {
choice = keyboard.nextInt();
switch (choice) {
case 1:
System.out.println("The dog became alarmed!");
Dandy.bark();
break;
case 2:
System.out.println("The dog becomes aggressive!");
Dandy.bite();
break;
case 3:
System.out.println("The dog comes in peace");
Dandy.sit();
break;
}
if (choice == 1) {
System.out.println("You stand back in caution. You cannot risk being bitten.");
}
if (choice == 2) {
System.out.print("");
karma--;
}
if (choice == 3) {
System.out.println("You give the dog a treat. It wags its tail in excitement");
karma++;
}
// Chapter 1.1 - Man's best friend
System.out.println("\nThe dog will live a harsh life in the outside world. What would you like to do? "
+ "\n[1] Adopt dog\n[2] Leave dog\n[3] Quit game! You're bored...");
choice = keyboard.nextInt();
switch (choice) {
case 1:
System.out.println("\nYou welcome your new companion");
System.out.println("\nWould you like to give him a name?\n[1] No\n[2] Yes");
choice = keyboard.nextInt();
switch (choice){
case 1:
System.out.println("You see a shiny object beneath his foot, it's a dog collar."
+ "\nYou pick up the dog collar and see the name Todd on it."
+ "\nYes, because you did not choose a name for your dog, we gave him the most basic name ever. "
+ "You're welcome.");
dogName = "Todd"; //RIP doge
karma--;
break;
case 2:
dogName = keyboard.nextLine();
karma++;
}
}
// Good guy player gives his dog a name
// Chapter 1.2 - Home sweet home
System.out.println("\n" + dogName + " crawls up to your leg and lets out a whimper.\n"
+ "Is " + dogName + " just afraid of the dark, or is he hungry?"
+ "\nYou don't know the last time he ate. What will you do?");
System.out.println("\n[1] Go home\n[2] Find a store\n[3] Search the area");
choice = keyboard.nextInt();
if (choice == 1){
System.out.println("\nYou head home with " + dogName + " as fast as you can.\n"
+"On the way back, " + dogName + " seems extremely happy to be with"
+ " his new owner.\nGoing out you had no idea you'd bring home a new friend.");
karma++;
}
if (choice == 2){
System.out.println("");
System.out.println("");
}
if (choice == 3){
}
}
// GAME ENDING
if (karma > 0) {
System.out.println("\nYou ended with " + karma + " karma. Good job!");
}
else if (karma == 0){
System.out.println("\nYou ended with " + karma + " karma. Neither good nor bad, a neutral state.");
}else{
System.out.println("\nYou ended with " + karma + " karma. Bad job!");
}
// CREDITS
System.out.println("\n\t# THANK YOU FOR PLAYING #");
System.out.println("\t# Game created by aliens from outer space #");
}
}

When I try to name the dog, the code skips the naming prompt because of the static String dogName.
No, the problem is unrelated to dogName being static. Instead, the problem is with the way you use the Scanner. When you do keyboard.nextInt() it reads just enough data to be able to return an int. So, if the user types 2 and Enter, the Scanner will read the 2 and return it as an int, leaving the newline character in the input buffer.
Then, when you go to read the dog's name with dogName = keyboard.nextLine(); the newline character that's already present causes it to return an empty string for the dog's name immediately, rather than wait for any user input.
You can fix this by doing another keyboard.nextLine() just before you ask for the dog's name:
case 2:
keyboard.nextLine();
dogName = keyboard.nextLine();
karma++;
The first nextLine() eats up the newline from the previous number that was typed, and the second nextLine() returns a line of text (sans newline) that can be assigned to dogName.
However, there are other problems you will run into with Scanner. If the player types anything other than a number, nextInt() will throw an InputMismatchException. It's possible to work around these problems, but they can end up giving you a headache.
You might be better off using keyboard.nextLine() every time to get a line from the player, and then checking to see if it contains a number and parsing that number.
Also, the convention in Java is to use lower case letters to begin variable names, so your variable Dandy should be named dandy. Others have given some sensible suggestions about splitting your program up into pieces rather than having one monolithic main method.

couple of things.
Separate your logic from your Main method class.
Create a POJO for Dog (I think you already have one) class that takes name in the constructor argument.
public class Dog {
private String dogName;
public Dog(String dogName)
this.dogName = dogName;
}
//getters setters..
}

Instead of putting everything in your main, you'll have to remove the static keyword, and make a new instance of the program, something like this:
public static void main(String[] args) {
Game game = new Game();
game.start();
}
Then the choice and dogName variable doesn't have to be static anymore.
For general remarks: start by splitting up your code into multiple methods, each grouped by functionality, for example, one method for handling the user input, one for printing the options, etc. That way your code will become less of a mess, and allows you to refactor later into different classes more easily.

#DavidConrad's answer covers your actual error, but I thought I'd add more on "what you could do better"
public static Scanner keyboard = new Scanner(System.in);
public static int choice;
// dogName is Dogs name forever a hundred times rick & morty
static String dogName;
Note how all these fields are static? This is only required because you are trying to use them from a static method (that method being main). With only the code you have posted, it would seem you could move those fields into the main method like where you create the Dog.
Also, a tiny pet-peeve of mine, but it's not actually a rule or anything, is "excessive" spacing - (like inbetween choice and dogName). One space is fine. Two is "too" many for my liking. ;)
public static void main(String[] args) {
int karma = 0;
// Dog stuff...
Dog Dandy;
Dandy = new Dog();
Grr, more spaces! But, more importantly is the line about Dog Dandy. Your variable name is capitalized, and it is best practice to name variables in lower-case (such as you did correctly for karma). You should also declare and initialize your Dog in the same line, like so: Dog dandy = new Dog();
With the prologue and chapters, you may consider separating these into a separate class. You may notice a pattern in each chapter.
some text is given
options are given
result of option is displayed
You could greatly improve the overall readability of your code by creating a class which could taken some introText, options, and then show an option depending on the choice made. If that seems over your head, then I wouldn't worry about it though - it's only your third week so I wouldn't expect you to have the differences between classes, methods, and fields down pat quite yet. If this is something you are seriously interested in, you could find all kind of tutorials covering those, it will be greatly beneficial when you truly understand what they can do and how they interact.

Related

Using enum with a switch case String for my assignment

I've made changes to the code and was able to successfully I hope use the switch case with a String. Now I just need help declaring two variables for the string getDirection. I need it to be declared as "Right" and "Left"
String quit= "exit";
String choice;
String getDirection= "Right";//I need it to be declared as both left and right
quit.equalsIgnoreCase("exit");
do
{
System.out.println("would you like the bug to move or turn around?");
System.out.println();
System.out.println("Or enter 'exit' to quit");
choice= scan.nextLine();
option options=option.MOVE;
switch(options)
{
case MOVE:
b.move();
if (getDirection.equals("Right"))
System.out.println("The bug moved 1 unit towards " + b.getDirection("Right ") + " and is now at position " + b.getPosition());
else if (getDirection.equals("Left"))
System.out.println("The bug moved 1 unit towards " + b.getDirection("Left ") + " and is now at position " + b.getPosition());
if (b.getDirection.equals("Right"))//this getDirection is showing up as an error
That's because there's no member variable called getDirection in class Bug.
You have defined a local variable called getDirection, which is unrelated to class Bug.
Probably you intended a method call, b.getDirection(), by analogy with your similar calls in the same section of code.
Incidentally, IMO variables should have noun phrases for names, not verb phrases. So, method getDirection() is well-named, variable getDirection is not.

Matching user input against a string array in java?

I am incredibly new to java and have been given the following task:
Write a Java Program to prompt a user for a 3 letter body part name which has to be in the 'official' list of 3 letter body parts. (Arm, Ear, Eye, Gum, Hip, Jaw, Leg, Lip, Rib, Toe)
If a user makes a guess correctly then display the correct guess as part of a list.
Allow the user to keep guessing until they have all 10.
If a body part is incorrect then display an appropriate message.
Display the number of guesses they have made including
the correct ones.
The advice given was to use Arrays and Collections as well as Exception Handling where appropriate but I don't know where to go from what I've coded so far. Any help would be appreciated so much, thank you.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] bodyparts = new String [10];
bodyparts[0] = "Arm";
bodyparts[1] = "Ear";
bodyparts[2] = "Eye";
bodyparts[3] = "Gum";
bodyparts[4] = "Hip";
bodyparts[5] = "Jaw";
bodyparts[6] = "Leg";
bodyparts[7] = "Lip";
bodyparts[8] = "Rib";
bodyparts[9] = "Toe";
Set<String> bodypartSet = new TreeSet<>();
Collections.addAll(bodypartSet, bodyparts);
System.out.println("Please enter a 3 letter body part: ");
String bodypart = input.nextLine();
if (bodypartSet.contains(bodypart)) {
System.out.println("Correct, " + bodypart + " is on the list!");
} else {
System.out.println("Nope, try again!");
}
}
There are a lot of way to do this. The following, isn't the best or the most efficient, but it should work...
First of all, you have to put your "official" list in a structure, like an array:
private static String[] offList={Arm, Ear, Eye, Gum, Hip, Jaw, Leg, Lip, Rib, Toe};
Now you have to write a method that can find a world in that "offList", like that:
private static boolean find(String word){
for( int i=0; i<offList.length; i++){
if(word.equals(offList[i])) //if "word" is in offList
return true;
}
return false;
}
Now, let's create this guessing game GUI:
public static void main(String[] args){
LinkedList<String> guessed=new LinkedList<>();
String s;
Scanner input = new Scanner(System.in);
while(guessed.size()<offList.length){
System.out.println("Guessed= "+guessed.toString()); //you have to change it, if you want a better look
System.out.print("Try:");
s=input.nextLine();
/*Here we ask to the user the same thing, unless the guessed list
contains all the words of offList.
Every time we print the guessed worlds list*/
if(find(s)){
System.out.println("This world is in offList!");
if(!guessed.contains(s)) //the world is counted only one time!
guessed.add(s);
}else
System.out.println("Sorry...");
}
System.out.println("The complete list is "+guessed.toString());
}
If you want to show this game in a window, you should have to study some Java Swing classes.
EDIT: I post my answer before the main post editing. First of all you have to understand the Collections advantages and usage... When you know all the LinkedList methods, for example, this assignment looks like a joke! ;)
You need a loop for that, otherwise it will only ask for input once.
Something like this should do:
ArrayList<String> bodyParts = new ArrayList<String>();
bodyParts.add("Arm");
bodyParts.add("Ear");
bodyParts.add("Eye");
bodyParts.add("Gum");
bodyParts.add("Hip");
bodyParts.add("Jaw");
bodyParts.add("Leg");
bodyParts.add("Lip");
bodyParts.add("Rib");
bodyParts.add("Toe");
String input = "";
int totalGuesses = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Start guessing...");
while (!bodyParts.isEmpty()) {
totalGuesses++;
input = sc.nextLine();
if (input.length() != 3 || !bodyParts.contains(input)) {
// incorrect, do nothing
System.out.println("Nope.");
} else {
// correct, remove entry
bodyParts.remove(input);
System.out.println("Correct! " + (10 - bodyParts.size()) + " correct guess" + ((10 - bodyParts.size()) != 1 ? "es" : ""));
}
}
System.out.println("Done. You have found them all after " + totalGuesses + " guesses.");
sc.close();
Also, this is case sensitive. It will not find Arm when typing arm. And if you need the number of all guesses you can simply add an int before the loop and increase it inside.
The result of my example:
Start guessing...
arm
Nope.
Arm
Correct! 1 correct guess
Arm
Nope.
Ear
Correct! 2 correct guesses
Eye
Correct! 3 correct guesses
(...)
Rib
Correct! 9 correct guesses
Toe
Correct! 10 correct guesses
Done. You have found them all after 12 guesses.

Adding someones input from JOptionPane into an Array

Hey everyone Someone might have asked this but Im trying to implement an ArrayList from a users answer I have done some research and it wont do. Here's my code < part of it
public class Breed
{
public static void cross_breed()
{
// Creates 3 strings named male_breed, female_breed, and cross_breed.
String male_breed;
String female_breed;
String cross_breed;
Cross_breed crossbreed;
List<String> clist = new ArrayList<String>();
while (true) // While the male_breed is a real breed continue on with the program
{
male_breed = JOptionPane.showInputDialog("What is the breed of the male?");
if (male_breed.length() == 0) break; // Makes it so if the male dog breed wasn't entered the program will exit
if (List_Breeds.blist.containsKey(male_breed)) //If the given input of the users is on the list of breeds continue with program
{
while (true) // Loops the female breed
{
female_breed = JOptionPane.showInputDialog("What is the breed of the Female");
if (List_Breeds.blist.containsKey(female_breed)) //
{
if (male_breed.equals(female_breed)) // if both breeds are the same
{
clist.add(JOptionPane.showMessageDialog(null, "Your dog is a Purebread " + male_breed));
break; //Ends the program
}
else
{
cross_breed = male_breed.substring(0, 3) + "a" + female_breed.substring(0, 3); //If both breeds arent the same take the
clist.add(JOptionPane.showMessageDialog(null, "Your dog breed is a " + cross_breed)); // first three letters of the male_breed and inserts
break; // Ends the program // an 'A' at the end.
}
Eclipse is giving me an error saying for both lines
clist.add(JOptionPane.showMessageDialog(null, "Your dog is a Purebread " + male_breed));
and
clist.add(JOptionPane.showMessageDialog(null, "Your dog breed is a " + cross_breed));
that states "the method add in the Type List is not applicable for the arguments (void)
if I'm doing this wrong please help... What I am trying to do is add the breed (or cross breed) name to an arraylist in which will be displayed in a second menu
"the method add in the Type List is not applicable for the arguments (void)" mean the method you're calling - JOptionPane.showMessageDialog(JComponent, String) does not return anything.
This is because showMessageDialog is for showing messages, not capturing input.
You need to take a look at the various flavours of JOptionPane.showInputDialog() in order to get input from the user.

How can i fix an if statement within an if statement?

I'm teaching myself java and I'm a few weeks in, decided to make a program with several options in it.
First part is to select between two animals, in this case a seal and hippo.
After that the part I'm having trouble with after selecting the seal is that I want options after selecting the seal, such as repeating the action, terminating it, or asking for proper input when user types something random.
Here's my code
import java.util.Scanner;
class animal {
//Animal variables
String name;
String type;
//Method or subroutine, something an object belonging to the class can do
void sound() {
System.out.println(name + " was petted! " + name + " went 'Gauuu!'");
}
}
public class Objectmethod {
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
Scanner scanner2 = new Scanner(System.in);
//Creating an object under the class of Animal
animal animal1 = new animal();
animal1.name = "Baby Elephant Seal";
animal1.type = "Seal";
//Creating second animal
animal animal2 = new animal();
animal2.name = "Hippopotawhateveritis";
animal2.type = "Hippopotamus or however you spell it";
//Beginning prompt for user input
System.out.println("Would you like to pet the seal, or the hippo?");
//The code to recieve input of the user
String select = scanner1.nextLine();
//check user input to select correct object
while(true)
if(select.equals("seal")){
//Command that the animal sounds has.
animal1.sound();
//Prompt if the user would like to repeat
System.out.println("Would you like to pet the seal again?");
//second input recieving from user
String input = scanner2.nextLine();
//Checks user input for yes no or random crap
if(input.equals("yes")){
continue;
}
else if(input.equals("no")){
break;
}
else{
System.out.println("Answer yes or no you derpface.");
input = scanner2.nextLine();
}
}
else if(select.equals("hippo")){
animal2.sound();
break;
}
else{
System.out.println("You cray cray. Just pick one.");
select = scanner1.nextLine();
}
System.out.println("Thank you for participating.");
}
}
Typing seal works fine
then when input gibberish to get the else response of "Answer yes or no you derpface"
it works the first time, then the second time it goes back up to the response.
This is what happens
Would you like to pet the seal, or the hippo?
seal
Baby Elephant Seal was petted! Baby Elephant Seal went 'Gauuu!'
Would you like to pet the seal again?
"randominput"
Answer yes or no you derpface.
"secondrandominput"
Baby Elephant Seal was petted! Baby Elephant Seal went 'Gauuu!'
Would you like to pet the seal again?
no
Thank you for participating.
What do I have wrong that causes it to go to the "if" instead of the "else"? -Solved-
New problem. Here is what the last part of the script looks like after my attempt at fixing it.
I believe the issue is occurring at the chunk of code before termination, however I'm not sure what exactly it is as I've tried to apply the aforementioned fix and it didn't work. (The else statement just above the "Thank you for participating" code) Solved
(The issue was that having moved the first "while(true)" above everything else. I moved it back to where it was originally below "scanner1" and it is now functioning properly
-Note- This is after applying the first "while(true)" to robustly repeat petting of animals.
else{
while(!select.equals("seal") && !select.equals("hippo")){
System.out.println("You cray cray. Just pick one.");
select = scanner1.nextLine();
}
Example of the issue: (Quotes represent user input.)
Would you like to pet the seal, or the hippo?
"neither"
You cray cray. Just pick one.
"neither"
You cray cray. Just pick one.
"seal"
Thank you for participating.
Would you like to pet the seal, or the hippo?
The way I want it to occur: (Quotes represent user input.)
Would you like to pet the seal, or the hippo?
"neither"
You cray cray. Just pick one.
"neither"
You cray cray. Just pick one.
"seal"
Baby Elephant Seal was petted! Baby Elephant Seal went 'Gauuu!'
Would you like to pet the seal again?
...
...
//Rest of the program (Confirming repeated petting, or termination of program)
This should fix one of your problems. Let me know if this isn't what you wanted.
else{
while (!input.equals("yes") && !input.equals("no")){
System.out.println("Answer yes or no you derpface.");
input = scanner2.nextLine();
}
}
You have another issue though. You poll for the user response before the while(true) loop.
NOTE: After reviewing your code further, it seems like this functionality was intended. If you want to make your code more robust to continually pet all animals, see the code below.
You should edit your code to be like this:
while(true) {
System.out.println("Would you like to pet the seal, or the hippo?");
//The code to recieve input of the user
String select = scanner1.nextLine();
.
.
.
// the rest of your code
Per OP's request, here should be the fully edited code:
import java.util.Scanner;
class animal {
// Animal variables
String name;
String type;
// Method or subroutine, something an object belonging to the class can do
void sound() {
System.out.println(name + " was petted! " + name + " went 'Gauuu!'");
}
}
public class Objectmethod {
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
Scanner scanner2 = new Scanner(System.in);
// Creating an object under the class of Animal
animal animal1 = new animal();
animal1.name = "Baby Elephant Seal";
animal1.type = "Seal";
// Creating second animal
animal animal2 = new animal();
animal2.name = "Hippopotawhateveritis";
animal2.type = "Hippopotamus or however you spell it";
// check user input to select correct object
while (true) {
// Beginning prompt for user input
System.out.println("Would you like to pet the seal, or the hippo?");
// The code to recieve input of the user
String select = scanner1.nextLine();
if (select.equals("seal")) {
// Command that the animal sounds has.
animal1.sound();
// Prompt if the user would like to repeat
System.out.println("Would you like another animal?");
// second input recieving from user
String input = scanner2.nextLine();
// Checks user input for yes no or random crap
if (input.equals("yes")) {
continue;
} else if (input.equals("no")) {
break;
} else {
while (!input.equals("yes") && !input.equals("no")) {
System.out.println("Answer yes or no you derpface.");
input = scanner2.nextLine();
}
}
} else if (select.equals("hippo")) {
animal2.sound();
break;
} else {
System.out.println("You cray cray. Just pick one.");
select = scanner1.nextLine();
}
}
System.out.println("Thank you for participating.");
}
}

New to string so how to manage this title applier

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.

Categories

Resources