I am trying to write a code that will prompt the user to enter some instructions. If the user inputs the command "echo" + word, it will be displaying the word itself on the next line. Then the prompt will appear again waiting for another input.
The program should display an error if the command that was entered is unknown. I'm having issues here as the program is not displaying the error message.
In addition, if the user does not type anything and just press enter, it should just simply display again the prompt on the next line, however it's not doing it.
Hopefully, you can help me..
import java.util.Scanner;
import java.io.*;
public class Prompter {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String sInstruct, sTerm;
System.out.print("Enter:> ");
sInstruct = sc.next();
sTerm = sc.nextLine();
try {
if (sInstruct.equals("")){
while(sInstruct.equals(""))
{
System.out.print("Enter:> ");
sInstruct = sc.next();
}
} else if (sInstruct.equals("echo")){
while (sInstruct.equals("echo"))
{
sayWord(sInstruct, sTerm);
System.out.print("Enter:> ");
sInstruct = sc.next();
sTerm = sc.nextLine();
}
}
}
catch(Exception error){
System.out.print("Invalid command " + sInstruct);
}
sc.close();
}
public static void sayWord (String sInstruct, String sTerm){
System.out.println(sTerm);
}
}
Output should be:
Enter:> echo hello brown fox
hello brown fox
Enter:>
Enter:>
Enter:> eccoh hello
Invalid command eccoh
Enter:>
I see some problems in your code:
Using sInstruct and sTerm at the same time is an overkill, you should use only sTerm since it will contain the complete instruction
The while loop must be outside the if conditions and should check for a sc.hasNextLine()
To check if the entered string is empty, you should do it using sTerm.isEmpty()
To check if the entered string starts with echo, you should do it using sTerm.startsWith("echo")
The check for an invalid instruction, must be set inside the while loop.
The try-catch clause is not needed.
See the proposed solution:
import java.util.Scanner;
import java.io.*;
public class Prompter {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String sTerm;
System.out.print("Enter:> ");
while(sc.hasNextLine()) {
sTerm = sc.nextLine();
if(sTerm.isEmpty()) {
} else if (sTerm.startsWith("echo")) {
sayWord(sTerm.substring(5));
} else {
System.out.println("Invalid command " + sTerm.split(" ")[0]);
}
System.out.print("Enter:> ");
}
sc.close();
}
public static void sayWord (String sTerm){
System.out.println(sTerm);
}
}
Or, if you prefer, the if-else clauses could be even more compacted:
if (sTerm.startsWith("echo")) {
sayWord(sTerm.substring(5));
} else if(!sTerm.isEmpty()) {
System.out.println("Invalid command " + sTerm.split(" ")[0]);
}
Related
I just started to learn how to write programs. In this program. I'm trying to find a word in a sentence while using the scanner. However, I ran into a problem. my code is below:
import java.util.Scanner;
public class TestOne {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
if (pick == 5) {
String sentenceFive = "i see you";
String wordFive = "you";
if (sentenceFive.contains(wordFive)) {
System.out.println("Keyword matched the string");
}
else {
System.out.println("No match");
}
} else if (pick == 6) {
System.out.println("Please enter a sentence");
String sentenceFive = scn.nextLine();
scn.nextLine();
System.out.println("Please enter a word");
String wordFive = scn.nextLine();
if (sentenceFive.contains(wordFive)) {
System.out.println("Keyword matched the string");
}
else {
System.out.println("No match");
}
}
}
}
(pick==5) works totally fine but (pick==6) returns "No match".
The if & else statements are both the same and my inputs for (pick==6) are also the same as the strings in (pick==5). So I guess it's because of the scanner, right?
Below code worked, Please refer the comments
import java.util.Scanner;
public class Main {
public static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Please enter a sentence");
String sentenceFive = scn.nextLine();
// scn.nextLine(); Not needed unless reading another line
System.out.println("Please enter a word");
String wordFive = scn.nextLine();
if (sentenceFive.contains(wordFive)) {
System.out.println("Keyword matched the string");
}
else {
System.out.println("No match");
}
}
}
OUTPUT
PS C:\TEMP\Projects\BU> java Main
Please enter a sentence
i am sam
Please enter a word
am
Keyword matched the string
PS C:\TEMP\Projects\BU>
I'm creating a login page for a class assignment and having trouble exiting out of a while loop after a method takes in the username and password then searches through a multi-line text file for a match. It can find a match but goes back to the input area in the main method and asked for the username again. Hope this makes sense.
Any help would be extremely appreciated. As you can tell, I'm new to Java since this code is all over the place and probably a ton of mistakes. I've been up all night trying to figure this out but with no luck. Thanks!
package course.registration;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Welcome {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Course Registration System" + "\n");
System.out.print("Please type Login or Register: ");
String choice = input.nextLine();
while (choice.equalsIgnoreCase("Login")){
System.out.print("Please enter email address to log in: ");
String email = input.nextLine();
System.out.print("Please enter password: ");
String password = input.nextLine();
//goes to method to search and match inputs
VerifyLogin verify = new VerifyLogin();
verify.VerifyInfo(email, password);
}
if (choice.equalsIgnoreCase("Register")) {
System.out.println("Going to registration Page...");
}
input.close();
}
}
Here is the method that searches the text file and tries to find a match for the inputs. I feel like the problem is when the method exits and goes back to the while loop in the main method. I can't figure out a way to exit out of the while loop. Here is how the strings look in the "students_logins.txt" file:
jthomas#gmail.com,1234
kwatson#time.com,3333
legal#prog.com,d567
lavern#shirley.com,34
kwatson#gmail.com,12200
package course.registration;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class VerifyLogin {
private String tempUsername;
private String tempPassword;
public void VerifyInfo(String email, String password) throws FileNotFoundException {
boolean login = false;
File file = new File("student_logins.txt");
Scanner info = new Scanner(file);
info.useDelimiter("[,\n]");
while (info.hasNextLine()) {
tempUsername = info.next();
tempPassword = info.next();
if (tempUsername.trim().equals(email.trim()) && (tempPassword.trim().equals(password.trim()))) {
System.out.println("Email Address or Password Works!!");
break;
}
}
if (!login) {
System.out.println("Email Address or Password is Invalid.");
}
info.close();
}
}
Just move condition insede while loop, and if selected condition is final, e.g. user has enterd valid login and password, then use break to exit the loop. Otherwise, loop will be continued:
public class Welcome {
public static void main(String... args) throws IOException {
final LoginValidator loginValidator = new LoginValidator(Welcome.class.getResourceAsStream("student_logins.txt"));
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Welcome to the Course Registration System");
int choice = 0;
while (choice >= 0) {
System.out.println();
System.out.println("1: LoginPlease");
System.out.println("2: Register");
System.out.print("Your choice: ");
choice = scan.nextInt();
scan.nextLine();
if (choice == 1) {
System.out.print("Please enter email address to log in: ");
String email = scan.nextLine();
System.out.print("Please enter password: ");
String password = scan.nextLine();
if (loginValidator.isValid(email, password)) {
System.out.println("Email Address or Password Works!!");
break;
} else
System.out.println("Email Address or Password is Invalid.");
} else if (choice == 2) {
System.out.println("Going to registration Page...");
break;
}
}
}
}
}
For Validation, it is better to load all logins from file at the application start, and then use it just check Map:
final class LoginValidator {
private final Map<String, String> map = new HashMap<>();
public LoginValidator(InputStream in) {
try (Scanner scan = new Scanner(in)) {
scan.useDelimiter("[,\n]");
while (scan.hasNextLine()) {
map.put(scan.next(), scan.next());
scan.nextLine();
}
}
}
public boolean isValid(String email, String password) {
return map.containsKey(email) && map.get(email).equals(password);
}
}
In the main method you are always staying in the while loop, because you're never obtaining input again.
Before while loop you have:
String choice = input.nextLine();
So when you provide Login as an input while condition is always true , so you are staying in this while loop.
If you want to ask user for correct input Login/Register till he/she provides it, you can try to use my version of Welcome class:
public class Welcome {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Course Registration System" + "\n");
System.out.print("Please type Login or Register: ");
String choice = input.nextLine();
while (!choice.equalsIgnoreCase("Login") && !choice.equalsIgnoreCase("Register")) {
choice = input.nextLine();
}
if(choice.equalsIgnoreCase("Login")){
System.out.print("Please enter email address to log in: ");
String email = input.nextLine();
System.out.print("Please enter password: ");
String password = input.nextLine();
//goes to method to search and match inputs
VerifyLogin verify = new VerifyLogin();
verify.VerifyInfo(email, password);
}
if (choice.equalsIgnoreCase("Register")) {
System.out.println("Going to registration Page...");
}
input.close();
}
}
This program needs to print a.b.c. but it prints a.b.c...
How do I eliminate the last dot in output.
The program has to work with user ending loop with "."
import java.util.Scanner;
public class dots1 {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String input;
String output = "";
System.out.println("Hello! I print out an acronym. ");
do {
System.out.println("Please Enter a Character");
input = s.nextLine();
output = output+input+".";
} while (!input.equals("."));
System.out.println(output);
}
}
Because your exit condition is "." and you add it to output and add another dot. Try following:
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String input = "";
String output = "";
System.out.println("Hello! I print out an acronym. ");
while (true) {
System.out.println("Please Enter a Character");
input = s.nextLine();
if(input.equals("."))
break;
output = output + input + ".";
} ;
System.out.println(output);
}
I use a little trick using a simple check to see if its not the first read.
boolean isFirst=true;
do{
System.out.println("Please Enter a Character");
input = s.nextLine();
if(!isFirst) output="."+output;
isFirst=false;
output = output+input;
}while(!input.equals("."));
Instead of the do... while, you should use the the while function.
while (!input.equals(".") {
}
You have to use substring function in java and remove the last character of the String.
your loop end while you enter a dot in input.
Example given below.
Try this
import java.util.Scanner;
public class dots1 {
Scanner s = new Scanner(System.in);
String input;
String output = "";
System.out.println("Hello! I print out an acronym. ");
do{
System.out.println("Please Enter a Character");
input = s.nextLine();
output = output+input+".";
}while(!input.contains("."));
System.out.println(output.substring(0, output.length() - 2));
}
}
Output of Single Input
output of Multiple Inputs
I have been going thorough some practice problems and have a question on this code. I was able to figure it out using a different method, but I don't understand why this example doesn't work.The code asks for input until the user enters the same input twice, where it should then display the duplicate input before ending the program.
I am getting:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: any>
Error on the last line with the word variable. Any ideas?
import java.util.ArrayList;
import java.util.Scanner;
public class MoreThanOnce {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// create here the ArrayList
ArrayList<String> words = new ArrayList<String>();
while (true){
System.out.print("Type a word: ");
String word = reader.nextLine();
if(!words.contains(word)){
words.add(word);
}else{
break;
}
}
System.out.println("You gave the word " + word + " twice");
}
}
Your code does not compile. The variable "word" you want to display at the end is not in the right scope : you declare it in the while loop but try to use it outside this loop.
Just change thing like this :
import java.util.ArrayList;
import java.util.Scanner;
public class MoreThanOnce {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// create here the ArrayList
String word; //variable declared before loop
ArrayList<String> words = new ArrayList<String>();
while (true){
System.out.print("Type a word: ");
word = reader.nextLine();
if(!words.contains(word)){
words.add(word);
}else{
break;
}
}
System.out.println("You gave the word " + word + " twice");
}
Hope it helps.
Mathias
Are you using NetBeans ?
If yes then there is an open bug
Declare "String word" variable before while loop.
import java.util.ArrayList;
import java.util.Scanner;
public class MoreThanOnce {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// create here the ArrayList
String word;
ArrayList<String> words = new ArrayList<String>();
while (true) {
System.out.print("Type a word: ");
word = reader.nextLine();
if (!words.contains(word)) {
words.add(word);
} else {
break;
}
}
System.out.println("You gave the word " + word + " twice");
}
}
So I'm trying to use if-else statement dependant upon the user's input. It works when the user's input is only one word, however, multiple word inputs go unrecognized and triggers the else statement. How can i resolve this?
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
String answer;
System.out.println("Catch the tiger or run away?");
answer = myScanner.next();
if (answer.equals("Catch the tiger" )) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
answer = myScanner.next();
} else {
System.out.println("run away");
}
}
}
Replace:
answer = myScanner.next();
With:
answer = myScanner.nextLine();
next will only read in the next value until it reaches a space or newline. You want to read in the full line before making the comparison
try this :
Scanner scanner = new Scanner(System.in);
int choice = 0;
while (scanner.hasNext()){
if (scanner.hasNextInt()){
choice = scanner.nextInt();
break;
} else {
scanner.next(); // Just discard this, not interested...
}
}
Reference :
Flush/Clear System.in (stdin) before reading
Try this
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
System.out.println("Catch the tiger or run away?");
if (myScanner.hasNext("Catch the tiger")) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
} else {
System.out.println("run away");
}
}
}