Java Secret Word - java

I was given a assignment for my Intro to Computer Science class to make the user enter any word until they guess the secret word, once they get the secret word then the system will say "Stop!" So far I have the user trying once and I want the program to continue looping until the user enters the right word. I really need some help, this is what I have so far.
import java.util.Scanner;
public class HW2
{
public static void main(String[] args)
{
String input; //The users input
// New Scanner for keyboard input
Scanner keyboard = new Scanner(System.in);
//Tell the user to guess the word
System.out.print("Guess the secret word: ");
input = keyboard.nextLine();
if(input.equalsIgnoreCase("college"))
{
System.out.print("Stop !");
}
}
}

All you need is a do-while loop.
import java.util.Scanner;
public class HW2
{
public static void main(String[] args)
{
String input; //The users input
boolean hasGuessedCorrectly = false;
// New Scanner for keyboard input
Scanner keyboard = new Scanner(System.in);
//Tell the user to guess the word
do
{
System.out.print("Guess the secret word: ");
input = keyboard.nextLine();
if (input.equalsIgnoreCase("college"))
{
hasGuessedCorrectly = true;
System.out.print("Stop !");
}
} while (!hasGuessedCorrectly);
}
}

A do-while loop could be used for this task:
import java.util.Scanner;
public class Main {
private static final String SECRET_WORD = "college";
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
do {
System.out.print("Guess the secret word: ");
} while (!SECRET_WORD.equalsIgnoreCase(keyboard.nextLine()));
System.out.println("Stop!");
}
}
Live demo

Consider the while loop:
import java.util.Scanner;
public class HW2
{
public static void main(String[] args)
{
String input = ""; //The users input
// New Scanner for keyboard input
Scanner keyboard = new Scanner(System.in);
// The below code is run until the secret word is guessed.
while (!"college".equalsIgnoreCase(input))
{
//Tell the user to guess the word
System.out.print("Guess the secret word: ");
input = keyboard.nextLine();
/* if(input.equalsIgnoreCase("college"))
{
System.out.print("Stop !");
} This code is no longer necessary, as we have put the stop
condition in the while loop declaration. */
}
// This only runs after the loop has finished
System.out.println("Stop !");
}
}

Related

Is it possible detect single enterkey with java.util.Scanner?

I am trying to write a terminal-based toy app, which allows user to input product category and inventory.
Is it possible to implement a feature of pressing enter key to input the default inventory.
Here is the procedure/steps
app print "product category:"
user input a category, such as shoe
app print "Inventory(press enter key for 999):"
user press enterkey or input another number
app print product_category + product_inventory
here is my code
import java.util.Scanner;
public class ProductScanner {
public static void main(String[] args) {
System.out.print("product category: ");
Scanner scanner = new Scanner(System.in);
String product_category = scanner.next();
System.out.print("Inventory(press enter key for 999): ");
int product_inventory = scanner.nextInt();
scanner.close();
System.out.println(String.format("%s, %d", product_category, product_inventory));
}
}
this code does not support "enterkey for default" feature.
quesion
is it possible detect single enterkey with java.util.Scanner to implement the default input?
I also tried this code, even worse
import java.util.Scanner;
public class ProductScanner {
public static void main(String[] args) {
System.out.print("product category: ");
Scanner scanner = new Scanner(System.in);
String product_category = scanner.next();
scanner.close();
System.out.print("Inventory(press enter key for 999): ");
scanner = new Scanner(System.in);
String product_inventory_str = "999";
if(scanner.hasNext()){
System.out.println("hasNext");
product_inventory_str = scanner.nextLine();
}
else{
System.out.println("does not have Next");
}
int product_inventory = 999;
if(product_inventory_str.isEmpty()){
System.out.println("isEmpty");
}
else{
product_inventory = Integer.parseInt(product_inventory_str);
}
scanner.close();
System.out.println(String.format("%s, %d", product_category, product_inventory));
}
}
You could always read an entire line (because user will have to press Enter anyway) and then decide what to do with it, something like this:
public static void main(String[] args) {
System.out.print("product category: ");
Scanner scanner = new Scanner(System.in);
String product_category = scanner.nextLine();
System.out.print("Inventory(press enter key for 999): ");
String pi_string = scanner.nextLine();
int product_inventory = pi_string.isEmpty()?
999:Integer.parseInt(pi_string);
scanner.close();
System.out.println(String.format("%s, %d",
product_category, product_inventory));
}

how to stop taking user inputs and print out arraylist

I am trying to create a program that takes user inputs stores them into an Arraylist and the prints the Arraylist out after user inputs a certain string. my current problem is that i cant get the user inputs to stop and print out. i think what i have currently have is a strong base, i cant see what is wrong.
import java.util.ArrayList;
import java.util.Scanner;
public class GroceryArraylist {
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter end to stop ");
while (!input.equals("end")) {
Grocerylist.add(input.next());
if (Grocerylist.equals("end")){
for(String str:Grocerylist)
System.out.println(str);
}
}
}
}
Here is the mistake:
Grocerylist.equals("end")
GroceryList is of type ArrayList and it will never be equal to the string "end". It's like comparing apples with oranges.
You could try this instead:
while (!input.equals("end")) {
String input = input.next();
Grocerylist.add(input);
if ("end".equals(input)){
for(String str:Grocerylist)
System.out.println(str);
}
break;
}
You can use hasNext command to avoid including "end" into the array.
public class GroceryArraylist {
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter \"end\" to stop ");
while (input.hasNext()) {
Grocerylist.add(input.next());
if(input.hasNext("end")) {
System.out.println(Grocerylist);
break;
}
}
}
}
Or you can use a do-while loop instead of:
public class GroceryArraylist{
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter \"end\" to stop ");
do {Grocerylist.add(input.next());}
while (!input.hasNext("end"));
System.out.println(Grocerylist);
System.exit(0);
}
}

How to get and print string in java

I can get and print the integer value in java but I am confuse how to get and print string. Can someone help
package hello;
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
int integer;
System.out.println("Please Enter Integer");
Scanner sc = new Scanner(System.in);
integer = sc.nextInt();
sc.close();
System.out.println("you entered : " +integer);
}
}
Program output
Please Enter Integer
5
you entered : 5
I am stuck in this program. I don't understand how to get string and print on screen
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
int name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextInt();
sc.close();
System.out.println("Your name"+name);
}
}
You need to change your type value name from int to String. And replace sc.nextInt() by sc.nextLine() or sc.next().
Example
public static void main(String[] args) {
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextLine();
sc.close();
System.out.println("Your name " + name);
}
Use sc.nextLine() for reading string inputs
or
sc.next() (But this will read only a word before it encounters a space)
You can also use InputStreamReader for this purpose
eg.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in()));
String input = br.readLine();
name = sc.nextInt(); doesn't work for strings, only for integers, you should use sc.nextline instead.
And also you have to change int name to String name, due to other type of variable.
Your code should look like this:
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextLine();
sc.close();
System.out.println("Your name"+name);
}
}
change int name to string name and use sc.nextLine()
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextLine();
sc.close();
System.out.println("Your name"+name);
}
}

how do i make java code that reads a word and tells me if is starts with the letter a or not? i am lost

import java.util.Scanner;
public class IfAndString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word:");
String line = input.next();
char a = line.charAt(2);
char b = line.charAt(2);
if (a < b)
System.out.printf("%s starts with 'a'.",a);
else if (a > b)
System.out.printf("\n%s does not start with 'a'.",b);
}
}
You can use the startsWith() method
Example:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word:");
String line = input.next();
if (line.startsWith("a"))
{
System.out.println(line + ": starts with a");
}
else
{
System.out.println("does not start with a");
}
}
Also if you wanted to check for an a even if they entered an uppercase A you could change your line variable to lower case in the if check to account for both lowercase and uppercase a.
Example:
if (line.toLowerCase().startsWith("a"))
Anwser to your question in the headline. Simply use the Method boolean startsWith(String string) method from the String class, e.g. like this:
import java.util.Scanner;
public class IfAndString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word:");
String line = input.next();
if (line.startsWith("a")){
System.out.printf("%s starts with 'a'.",a);
} else{
System.out.printf("\n%s does not start with 'a'.",b);
}
}
}
When you want to compare chars do something like this:
"abc".charAt(0) == 'a'; // String implement CharSequence.

Ask user to enter word until they enter "exit"

Ask user to enter word until they enter "exit", when they enter exit display all of their entered words without the "exit".
I'm confused how to combine all of their words and display it at the end, I know I will need another loop for that
import java.util.*;
public class testprac {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a word: ");
String word = input.nextLine();
if (word.equals("exit")) {
System.out.println("Exited");
System.out.println("You entered: ");
break;
}
}
}
}
You can use array or List to store the inputs and then loop through the list or array to print.You can also to toString() method to print.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Temp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<String> inputs = new ArrayList<>();
while (true) {
System.out.println("Enter a word: ");
String word = input.nextLine();
if (word.equals("exit")) {
System.out.println("Exited");
System.out.println("You entered: "+inputs);
break;
} else {
inputs.add(word);
}
}
}
}
This should work:
import java.util.*;
public class testprac {
public static void main(String[] args) {
System.out.println("Enter a word:");
Scanner inputScanner = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
while (inputScanner.hasNextLine()) {
String line = inputScanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
String s = lineScanner.nextLine();
if (s.equalsIgnoreCase("exit")) {
System.out.println("Exited");
System.out.println("You entered: ");
System.out.println(sb.toString());
lineScanner.close();
System.exit(0);
} else {
sb.append(s);
}
}
}
inputScanner.close();
}

Categories