Matching user input against a string array in java? - 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.

Related

Stuck While Loop (Java)

all!
I'm a university freshman computer science major taking a programming course. While doing a homework question, I got stuck on a certain part of my code. Please be kind, as this is my first semester and we've only been doing Java for 3 weeks.
For context, my assignment is:
"Create a program that will ask the user to enter their name and to enter the number of steps they walked in a day. Then ask them if they want to continue. If the answer is "yes" ask them to enter another number of steps walked. Ask them again if they want to continue. If they type anything besides "yes" you should end the program by telling them "goodbye, [NAME]" and the sum of the number of steps that they have entered."
For the life of me, I can not get the while loop to end. It's ignoring the condition that I (probably in an incorrect way) set.
Can you please help me and tell me what I'm doing wrong?
import java.util.Scanner;
public class StepCounter
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
final String SENTINEL = "No";
String userName = "";
String moreNum = "";
int numStep = 0;
int totalStep = 0;
boolean done = false;
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
// Prompt for the user's name
System.out.print("Please enter your name: ");
userName = in.nextLine();
while(!done)
{
// Prompt for the number of steps taken
System.out.print("Please enter the number of steps you have taken: ");
// Read the value for the number of steps
numStep = in.nextInt();
// Prompt the user if they want to continue
System.out.print("Would you like to continue? Type Yes/No: ");
// Read if they want to continue
moreNum = in2.nextLine();
// Check for the Sentinel
if(moreNum != SENTINEL)
{
// add the running total of steps to the new value of steps
totalStep += numStep;
}
else
{
done = true;
// display results
System.out.println("Goodbye, " + userName + ". The total number of steps you entered is + " + totalStep + ".");
}
}
}
}
To compare the contents of String objects you should use compareTo function.
moreNum.compareTo(SENTINEL) return 0 if they are equal.
== operator is used to check whether they are referring to same object or not.
one more issue with addition of steps, addition should be done in case of "No" entered also
Use
if(!moreNum.equals(SENTINEL))
Instead of
if(moreNum != SENTINEL)
Also, make sure to add: totalStep += numStep; into your else statement so your program will actually add the steps together.

Java - How to print() output to previous line after input

I'm kind of new to Java and I'm still trying to get the hang of it, so I apologize if this is a stupid question, but I was wondering how to print the output on the same line as the input. For example, I'm programming a simple game where the user tries to guess a 4-digit number (rather like Mastermind). I've got the mechanics all figured out, but I'm having a hard time displaying it on the console. In the beginning it might look something like: (a)
Turn Guess Bulls Cows
----------------------------
1
Then, the user would input their guess: (b)
Turn Guess Bulls Cows
----------------------------
1 1234
And as soon as the user hits enter, the program should check their guess against the secret number and output the number of "bulls" (digits in their guess that match the secret number exactly) and "cows" (digits in their guess that are part of the number but in the wrong position), and then start a new line and again await user input. So if the secret number were, say, 4321... (c)
Turn Guess Bulls Cows
----------------------------
1 1234 0 4
2
Trouble is, I can't for the life of me figure out how to get the output to display on the same line as the input. Here's a snippet of what I have so far (stripped-down because the full code is much uglier):
number = "4321";
String guess;
int attempts = 1;
do
{
System.out.print(attempts + "\t\t");
guess = keyboard.next();
attempts++;
int bulls = checkBulls(guess, number);
int cows = checkCows(guess, number);
System.out.print("\t\t" + bulls + "\t\t" + cows + "\n");
}
while (!guess.equals(number));
Which gets me as far as (b), but then when I hit enter, this happens:
Turn Guess Bulls Cows
----------------------------
1 1234 // so far so good
0 4 // ack! These should've been on the previous line!
2
I know this isn't really essential to the game and is probably just me making things more complicated than necessary, but it's driving me nuts. I suppose what's happening is that when you hit enter after typing in your guess, the program starts a new line and then prints the bulls and cows. Is there any way to get around this?
You should look into Ansi Escape Codes.
Something like:
public void update() {
final String guessString = keyboard.next();
System.out.println("\033[1A\033[" + guessString.length() + 'C'
+ "\t{next col}");
}
will result in:
1234 {next col}
(where 1234, followed by {RETURN} was entered by the user; in an appropriately supporting console.
"\033[1A" moves the cursor up 1 row; and "\033[xC" moves the cursor x to the right (where above we calculate x as the length of their guess).
Another option that you have with this approach is to clear the console ("\033[2J") so that you can just completely re-draw the table (which is probably easier to maintain).
Your problem is clear the console or clear a line which depend on the console you are working on and is SO dependend!
See Java Clear Console or Java clear Line
Anyway this example clear the lines and it works on Unix bash shell. (Not in Eclipse console)
It uses "\b" to clear a char ( backslash)
public static void main(String[] args) throws Exception {
int i=0;
while (true)
{
String hello="Good morning"+i;
System.out.print(hello+i);
int j=0;
while(j<=hello.length()){
System.out.print("\b");
j++;
}
i++;
Thread.sleep(1000);
if(i==100)
break;
}
}
The problem in your case is that you need to clear also the new line since you read input and theere is no easy way to read input without new line.
See How to read a single char from the console in Java (as the user types it)?
I know this isn't your implementation but it might suffice. What you can do is print the progress of the game after each input. Then you can see the progress of the game after each attempt and the board will be updated each time.
ArrayList<String> turns = new ArrayList<>();
turns.add("Turn\t\tGuess\t\tBulls\t\tCows\n");
turns.add("----------------------------------------------------");
Scanner keyboard = new Scanner(System.in);
String number = "1234";
String guess = "";
int attempts = 0;
while(!number.equals(guess))
{
for(String line : turns)
System.out.println(line);
System.out.println("Guess the magic number...");
guess = keyboard.nextLine();
attempts++;
int bulls = checkBulls(guess, number);
int cows = checkCows(guess, number);
String attemptOutput = attempts + "\t\t" + guess + "\t\t" + bulls + "\t\t" + cows + "\n";
turns.add(attemptOutput);
}
Here is a different implementation that will achieve the same goal from display perspective but you should note that I am clearing screen by multiple new lines so the final effect is still same i.e. ...
user will enter number under Guess column
each attempt will be displayed immediately after user presses ENTER as you wanted.
NOTE: I have hard-coded bulls and cows value for running the program.
import java.util.ArrayList;
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
ArrayList<String> attempts = new ArrayList<String>();
attempts.add("Turn\t\tGuess\t\tBulls\t\tCows\n");
attempts.add("----------------------------------------------------");
Scanner keyboard = new Scanner(System.in);
String number = "1234";
String guess = "";
int turn = 1;
while (!number.equals(guess)) {
// multiple new lines to clear screen
System.out.println("\n\n\n\n\n\n\n\n");
for (String line : attempts)
System.out.println(line);
System.out.print(turn + "\t\t");
guess = keyboard.nextLine();
// checkbull implementation
int bulls = 0;
// checkcow implementation
int cows = 4;
String attemptOutput = turn + "\t\t" + guess + "\t\t" + bulls
+ "\t\t" + cows;
turn++;
attempts.add(attemptOutput);
}
}
}
Sample Run

Java text analysis program

The following requisites are those for the program I'm currently having an issue with:
The program must be able to open any text file specified by the user, and analyze the frequency of verbal ticks in the text. Since there are many different kinds of verbal ticks (such as "like", "uh", "um", "you know", etc) the program must ask the user what ticks to look for. A user can enter multiple ticks, separated by commas.
The program should output:
the total number of tics found in the text
the density of tics (proportion of all words in the text that are tics)
the frequency of each of the verbal tics
the percentage that each tic represents out of all the total number of tics
My program is working very well, but what I basically need to do is that I must use separate methods for each component of the analysis. So I think the idea is that I need to split up the program in a few parts, which I have done by using the comments // because I'm basically having problems determining which type I should return, I know the last part (// public static void output(){)
should definitely be void because it returns nothing and only prints out.
public static void main(String[] args) throws FileNotFoundException {
double totalwords = 0; // double so density (totalwords/totalticks) returned can be double
int totalticks = 0;
System.out.println("What file would you like to open?");
Scanner sc = new Scanner(System.in);
String files = sc.nextLine();
Scanner input = new Scanner(new File(files));
// public static int[] initialise()
System.out.println("What words would you like to search for? (please separate with a comma)");
String ticks = sc.nextLine();
ticks = ticks.toLowerCase();
String[] keys = ticks.split(",");
int[] values = new int[keys.length];
// public static int[] processing(){?
for (int z=0; z<keys.length; z++){
values[z] = 0;
}
while (input.hasNext()){
String next = input.next();
totalwords++;
for (int x = 0; x<keys.length; x++){
if (next.toLowerCase().equals(keys[x])){
values[x]+=1;
}
}
}
for (Integer u : values) {
totalticks += u;
}
//public static void output(){
System.out.println("Total number of tics :"+totalticks);
System.out.printf("Density of tics (in percent): %.2f \n", ((totalticks/totalwords)*100));
System.out.println(".........Tick Breakdown.......");
for (int z = 0; z<keys.length; z++){
System.out.println(keys[z] + " / "+ values[z]+" occurences /" + (values[z]*100/totalticks) + "% of all tics");
}
}
Essentially the problem I'm having is the scope of the variables because Eclipse (my IDE) no longer recognizes the variables within each method once I get them out of comments - I know I need to use some static variables but would really like a hand as to how I could hook my program up together using methods.
Thanks a bunch,
M
You should do an object (class) decomposition. First ask the question "What objects do I have". (At a quick glance you might have "Text" and "Ticks" objects. You then want to see what methods you want to use for each object. For example in Text have countTicks(Ticks). Conotinue in this fashion to decompose your program.
First, please indent your code more consistently, with the first line of a block three spaces farther to the right, such as
for(...) {
//Do stuff
if(...) {
//Do stuff
}
}
It is hard to read what you've posted (luckily someone spruced it up for you!).
Consider re-writing your program from scratch, instead of trying to fix what you already have. Your current knowledge of the problem should allow you to recreate it pretty quickly. You will probably be able to cut and paste bits and pieces from your original code as well.
How about starting small, with something like
Scanner sc = getInputScannerFromUserInput();
private static final Scanner getInputScannerFromUserInput() {
System.out.println("What file would you like to open?");
return new Scanner(System.in);
}
and just go from there. Bit by bit. Good luck!

Add and Subtract

I feel like I've tried everything, searched everything I know to search, and I've been working on this for about 6 classes now.
I'm trying to make a program that accepts a string input like "6 + 6 -3+ 2", and can add/subtract everything to output the correct answer. I got it to work with either addition or subtraction at one time (can't do anything like "6 + 6 - 3") and there also always have to be a space between any digit. It also can't add multi-digit numbers, but I'll worry about that once it can correctly add/subtract in the first place.
So I don't think I'm understand how Scanner and delimiters work, (since that's what the chapter is on) but I can't seem to find anything online that's helped me understand what I'm doing wrong.
This is what I have so far:
package addEmUp;
import java.util.*;
public class TesterShell {
public static void main(String[] args){
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter some addition/subtraction problem: ");
String s = kbIn.nextLine();
Scanner numChecker = new Scanner(s);
Scanner valueChecker = new Scanner(s);
numChecker.useDelimiter("\\s*\\+\\s*|\\s*\\-\\s*");
int sum = 0;
while(numChecker.hasNext()){
if(valueChecker.next().equals("-")){
sum = sum - numChecker.nextInt();
}
else{
sum = sum + numChecker.nextInt();
}
System.out.println(sum); //Just for checking what's going on, will remove in the end
}
System.out.println("Sum = " + sum);
}
}
Based on the other questions I've found on StackOverflow, a better way to do this would be to use index, but the Chapter I'm in set me up with a shell program using strings and scanner.
What am I missing here? What did I misunderstand/not understand at all?
For plain addition/subtraction you can do something simple like
String[] nums = s.replaceAll(" ", "").replaceAll("\\+", " ")
.replaceAll("-", " -").split(" ");
int res = 0;
for (String n : nums) {
if (!n.isEmpty())
res += Integer.parseInt(n);
}

Print formatting while taking user input

I have a college assignment where I need to print out items sold by a hardware store, take input from a user, perform some calculations on that input, and then print out an invoice.
I have been able to successfully print out the items sold by the hardware store, but am encountering problems with the while loop that takes the input.
The program asks the user to enter a CODE and then asks for the corresponding QUANTITY. This works fine on the first iteration of the loop, but on the second iteration the user prompts for "CODE:" and "QUANTITY:" appear on the same line, despite my use of println when prompting the user.
I would greatly appreciate a detailed response appropriate for someone new in programming.
Here's the code:
import java.util.Scanner;
class HardwareStore {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO THE HARDWARE STORE!");
System.out.println("----------------------------------------------------------------------");
String sticky = "G22";
String keyring = "K13";
String screwy = "S21";
String padlock = "I30";
int stickyprice = 10989;
int keyringprice = 5655;
int screwyprice = 1099;
int padlockprice = 4005;
System.out.println("CODE\t\tDESCRIPTION\t\t\t\t\tPRICE");
System.out.println("----\t\t-----------\t\t\t\t\t-----");
System.out.println(sticky + "\t\tSTICKY Construction Glue, Heavy Duty, \n\t\t7oz, 12 Pack \t\t\t\t\t$" + stickyprice);
System.out.println(keyring + "\t\tCAR-LO Key Ring, Quick Release, \n\t\t1 Pack\t\t\t\t\t\t$ " + keyringprice);
System.out.println(screwy + "\t\t!GREAT DEAL! SCREW-DUP Screwy Screws, \n\t\tDry Wall Screws, 3 in. Long, 50 Pack\t\t$ " + screwyprice);
System.out.println(padlock + "\t\tLET-IT-RAIN, Weather Proof Padlock, \n\t\tPortable, One Push Functionality\t\t$ " + padlockprice);
System.out.println("----------------------------------------------------------------------");
int i = 10000;
String [] usercode = new String[i];
int [] userquantity = new int[i];
System.out.println("PLEASE ENTER YOUR ORDER:");
while (true) {
System.out.println("CODE: (X to terminate)");
usercode[i] = in.nextLine();
if (usercode[i].equalsIgnoreCase("x")) {
break;
}
System.out.println("QUANTITY: ");
userquantity[i] = in.nextInt();
}
}
}
when you enter the QUANTITY you're pressing enter. That newline character isn't used by in.nextInt();, it remains in the scanner buffer, until you roll around to in.nextLine() again.
At that point in.nextLine() reads until it finds a newline character, which just happens to be the next one in the buffer. So it skips straight to QUANTITY again.

Categories

Resources