Here is the code:
import java.util.Scanner;
public class Finder {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String [] names = new String[5];
String searchTerm = "";
for (int i = 0; i <= names.length - 1; i++) {
System.out.print("Enter a name: ");
names[i] = scnr.next();
}
System.out.println();
System.out.print("Enter a name to search for: ");
searchTerm = scnr.next();
for (int i = 0; i <= names.length - 1; i++) {
if (searchTerm.equals(names[i])) {
System.out.println(searchTerm + " found!!");
}
else {
System.out.println(searchTerm + " not found!!");
}
}
}
}
I am working on the if/else statement in the second for loop and when I add the else part of the statement, it returns:
Enter a name: Luke
Enter a name: Kassy
Enter a name: Chloe
Enter a name: Jon
Enter a name: Jake
Enter a name to search for: Chloe
Chloe not found!!
Chloe not found!!
Chloe found!!
Chloe not found!!
Chloe not found!!
I am not sure why it just doesn't say "Chloe found!!" instead of what it says?
With your code now, when you're looping to find the element "Chloe" in the names array, you're going through each element and printing a statement out no matter what. "Chloe" is names[2] but your loop checks names[0] and names[1] first. Since they are not "Chloe", it will print "Chloe not found" (the else part of your if statement). Once it gets to names[2], it will then have found "Chloe" and the if part of your if statement will be executed, printing out "Chloe found". However your loop does not stop there, so the loop will look at names[3] and names[4] and print out "Chloe not found" because none of them equals "Chloe". The simple fix is to only print "Chloe not found" when the loop ends without finding "Chloe" and to only print "Chloe found" when in the middle of the loop, "Chloe" is found. There are many ways to do this but one way I propose is using a boolean variable to check after the loop is done to see if "Chloe" was found or not.
boolean termFound = false;
for (int i = 0; i <= names.length - 1; i++) {
if (searchTerm.equals(names[i])) {
System.out.println(searchTerm + " found!!");
termFound = true;
break;//if term is found, you can break out of the loop early
}
}
if(!termFound){ //if searchTerm was not found
System.out.println(sertTerm + " not found!!");
}
Related
I refactored a working project to practice creating callable methods when I broke the app. This app includes a simple String array with a method that matches user input with the array and prints the element name and index.
If I don't include a break at the end of the if else statements the app can match valid input but runs both if and else statements. It actually prints the if statement in the order of the index and prints the else output the number of times as the length of the array. In the attached pic, the input was index 0. if statement output In the pic index 0 was matched and printed with the number of else outputs as in the array. It seems the else statement is reading the array length.
If I add the break, the app only recognizes index 0 and will run the if statement as expected, but also runs the else statement. But only prints out if else output once. I hope this is clear. Trainers have simply said it is impossible to for a for loop to print of which I understand, yet I'm having a different experience.
Here is the code:
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("What are you looking for? ");
//String product = scan.nextLine();
String[] aisles = {"apples", "bananas", "candy", "chocolate", "coffee", "tea"};
searchProduct(aisles);
}
public static void searchProduct(String[] aisles) {
String product = scan.nextLine();
for (int i = 0; i < aisles.length; i++) {
if (product.equals(aisles[i])) {
System.out.println("We have " + aisles[i] + " in aisle " + i);
} else {
System.out.println("Sorry we do not have that product");
}
}
}
}
I expect to match valid user input and run the if statement or run the else statement.
Here is a suggestion.
Change your method to return an int (aisle if the product exists or -1 if not).
Don't do any I/O in the method. Just pass the target of the search as an argument.
String[] aisles = {
"apples","bananas","candy","chocolate","coffee","tea"
};
System.out.println("What are you looking for? ");
String product = scan.nextLine();
int aisle = searchProduct(product, aisles);
if (aisle >= 0) {
System.out.println("We have " + product + " in aisle " + aisle);
} else {
System.out.println("Sorry we do not have that product");
}
public static int searchProduct(String product, String[] aisles) {
for (int aisle = 0; aisle < aisles.length; aisle++) {
if (product.equals(aisles[aisle])) {
return aisle;
}
}
return -1;
}
I'm trying to take my Scanner input and use it to find the index of the location of a object/name in an ArrayList of Objects.
The code is made up of two Classes, constructor(setter/getter) and tester class
The array list was created using the following code as example;
List<Detail> details = new ArrayList<>();
details.add(new Detail("Anthony", 26) );; note i used public void setName(String name) and public void setNumber(long number) to identify the objects added to the ArrayList
The arraylist output looks like this
Name: Anthony Age: 26
Name: Thomas Age: 30
Name: Shaun Age: 29
Name: James Age: 28
The code below is what i'm trying to use to find the index location. This code wont compile because i dont know what to put in the parenthesis of details.indexOf())
System.out.print("Type in one of the names listed above to find index of it's location: ");
String name = s.nextLine();
for (Detail d : details){
if (details.contains(s.nextLine()))
System.out.println("The index location of " +(scanner input/name here) " is " + details.indexOf());
My intended output is
The index location of Thomas is 1
I Know how to get the index of an element whenit's defined into the code, id use something like int location = details.get(2);, i believe this would return Name: Shaun Age: 29, but i dont know how to take the input from the Scanner Shaun and return only the Location of 2
Am I going about this in silly way? What am I doing wrong?
You can use the below approach to find the index of the name in the list.
Here,
I have iterated over the list and check the input with the names from the list, once found , assign that index and break from the loop.
If user input not found, then user will be notified with the message "name not found".
Code:
With For loop
public class Test {
public static void main(String[] args) {
List<Detail> list = Arrays.asList(new Detail("Anthony",26),
new Detail("Thomas",30),
new Detail("Shaun",29),
new Detail("James",28));
System.out.print("Type in one of the names listed above to find index of it's location: ");
Scanner s = new Scanner(System.in);
String name = s.nextLine();
int index = -1;
for(int i = 0 ; i < list.size(); i++){
if(name.equals(list.get(i).getName())){
index = i;
break;
}
}
if(index == -1) {
System.out.println("name not found");
} else {
System.out.println("The index location of " + name + " is " + index);
}
}
}
With enhanced For loop
public class Test {
public static void main(String[] args) {
List<Detail> list = Arrays.asList(new Detail("Anthony",26),
new Detail("Thomas",30),
new Detail("Shaun",29),
new Detail("James",28));
System.out.print("Type in one of the names listed above to find index of it's location: ");
Scanner s = new Scanner(System.in);
String name = s.nextLine();
int index = -1;
int counter = 0;
for(Detail d : list){
if(name.equals(d.getName())){
index = counter;
break;
}
counter++;
}
if(index == -1) {
System.out.println("name not found");
} else {
System.out.println("The index location of " + name + " is " + index);
}
}
}
Output::
Input:: Thomas
Output:: The index location of Thomas is 1
Input:: Test
Output:: name not found
im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 1; i >= 1; i--) {
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax < scores[j]) {
currentMax = scores[j];
currentMaxIndex = j;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}
I have an assignment for a beginner Java course that has asked me to create a class called Hangman. The program is supposed to prompt a user (player one) to input a String, then print dashes on the screen for each character in the screen. The program then asks a second user (player two) to take guesses one character at a time until either the word has been guessed, or they have six failed attempts. As each correct guess is verified, the corresponding dash in the string is replaced with the correct letter.
At this point I have created code that will scan in a user String, and replace the String with dashes. The code also prompts the second user for a comparison letter. The code will also replace the first correct guess in the dash String.
The problem I have at this point is that I can't seem to find a way to prompt the user for additional input after the first guess. The program will accept the first correct guess, replace it, and then terminate. I removed a portion of code that checked how many incorrect / correct guesses had been input, because at this point the code would run through constantly incrementing the count and terminate the program. Any help with this problem would be greatly appreciated.
Update:
I have reworked my code to remove unwanted / unnecessary branches. Here is my updated code. At this point, I am receiving too many incorrect guesses. The code is counting every iteration through the array that does not match as incorrect. I appreciate any help you can offer.
public class Hangman
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
String word;
String letter = "";
boolean gameOver = false;
int correct = 0;
int incorrect = 0;
int index = 0;
Scanner userIn = new Scanner(System.in);
System.out.print("Player 1 enter a word: ");
word = userIn.nextLine();
String[] wordArray = word.split("");
int wordLength = word.length();
String[] wrong = {};
String[] right = {};
String[] dashes = new String[wordLength];
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
for(int i = 0; i < wordLength; i++)
{
dashes[i] = "-";
}
for(int i= 0; i < wordLength; i++)
{
System.out.print(dashes[i] +" ");
}
System.out.println();
while(incorrect < 6)
{
System.out.print("Player 2 enter a letter: ");
letter = userIn.nextLine();
letter = letter.toLowerCase();
if(letter.length() > 1)
{
System.out.println("ERROR: You have entered more than one letter.");
System.out.print("Player 2 enter a letter: ");
letter = userIn.nextLine();
}
for(int i = 0; i < wordLength; i++)
{
if( wordArray[i].equals(letter))
{
dashes[i] = letter;
System.out.println("Correct!");
for( i= 0; i < wordLength; i++)
{
System.out.print(dashes[i] +" ");
}
correct++;
}
else
{
incorrect++;
}
}
}
if(correct == wordLength)
{
System.out.println();
System.out.println("You Win!!");
System.out.println();
}
if(incorrect == 6)
{
System.out.println("You Lose.");
System.out.println("The word was " +word);
System.out.println();
}
}
}
So, that's a hefty amount of code. And I see some interesting decisions all over the place. So since you're learning I'll help you help yourself.
Before taking on an application like this you should think about your logic first (psuedo-code) before actually coding. So for a hangman game you probably want something like:
player 1 enters phrase
while wrong_guesses < max_incorrect:
prompt player 2 for a letter
check the phrase for that letter
if found
replace dashes with the letter
else
wrong_guesses++
print status message
Just glancing at your code I can see multiple places where you're asking for new input. This means you are not effectively using your loops. Your application has a lot of unnecessary branches and cleaning it up will help you debug. As an exercise, you can walk through your code and write its' psuedo-code, then compare it to mine.
Good luck!
Update:
With respect to the new and much improved code, your check loop is wrong. It should look more like this:
boolean found = false;
for(int i = 0; i < wordLength; i++)
{
if( wordArray[i].equals(letter))
{
found = true;
// replace dashes, and you don't need to loop here,
// do it after the check for better efficiency
}
}
//Outside of the loop
if (!found)
{
incorrect++;
}
//Print the current status here then
Also, your check for only 1 letter can be subverted (enter aa, then aa again). That block should be:
if(letter.length() > 1)
{
System.out.println("ERROR: You have entered more than one letter.");
System.out.print("Player 2 enter a letter: ");
//letter = userIn.nextLine();
continue; //This tells java to restart the loop
}
When I test it, it builds fine. But when I run it only the intro and user output questions come up (which is what it's supposed to do), but when I input an answer an error comes up:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50
at statecapitals.StateCapitals.main(StateCapitals.java:141)
Now I know i'm new at this but what I think the error is, is that my arrays are not corresponding and i'm not sure what I did wrong. Any help would much appreciated. Here is what I have:
String[] stateName = new String[50];
String[] capName = new String[50];
int i;
for(i=0; i < 50; i++)
{
stateName[0] = "Alabama";
stateName[1] = "Alaska";
.....
capName[0] = "Montgomery";
capName[1] = "Juneau";
.....
}
boolean found = false;
Scanner keyboard = new Scanner(System.in);
System.out.println("This program is designed...");
System.out.println("Please enter the name of a U.S. state (please enter capitalized):");
stateName[i] = keyboard.nextLine();
for(i=0; (!found) && (i < stateName.lenth); i++)
if(stateName[i].matches(capName[i]) )
System.out.print(The capital of " + stateName + " is " + capName);
found = true;
if(!found)
System.out.println("The name you entered was not on the list.");
*Updated & edited:
the line of code that was having the most trouble was:
stateName[i] = keyboard.nextLine();
Thank you for everyone's help, i've made some changes:
int i;
for(i=0; i < 49; i++)
{
stateName[i+1]
.....
capName[i+1]
...
}
Plus I added the curly brackets to my for loop at the bottom. Now when I run it, it stops on the line:
if(capName[i].matches(stateName[i]) )
and the error this time is:
Exception in thread "main" java.lang.NullPointerException
at statecapitals.StateCapitals.main(StateCapitals.java:146)
Thank you again for everyone's input.
Since i is not initizalized (in the snippet)
stateName[i] = keyboard.nextLine();
should be something like:
searchState = keyboard.nextLine();
And this comparison is pointless since it would never match (should be searchState from above):
if(stateName[i].matches(capName[i]) )
problem 1
stateName[i] = keyboard.nextLine();
problem 2
for(i=0; i < 50; i++)
{
stateName[0] = "Alabama";
stateName[1] = "Alaska";
.....
capName[0] = "Montgomery";
capName[1] = "Juneau";
.....
}
i think this should be stateName[i] = "Alabama";
Problem 3
You missed the "{" "}" in the for loop
for(i=0; (!found) && (i < stateName.length); i++){
if(stateName[i].matches(capName[i]) ){
System.out.print(The capital of " + stateName + " is " + capName);
found = true;
}
}
if(!found)
System.out.println("The name you entered was not on the list.");
You've had a lot of good suggestions to improve your code that I would try to implement.
The reason for the error is your for loop.
for(i=0; (!found) && (i < stateName.lenth); i++)
The length of the array is going to return 50, but your indexes go from 0 - 49 and because you never find a match, it goes through the whole loop.