How to make java scanner accept more than one string input? - java

Hello i'm currently a beginner in Java. The code below is a while loop that will keep executing until the user inputs something other than "yes". Is there a way to make the scanner accept more than one answer? E.g. yes,y,sure,test1,test2 etc.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ans = "yes";
while (ans.equals("yes"))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}

Use the or operator in your expression
while (ans.equals("yes") || ans.equals("sure") || ans.equals("test1"))
{
System.out.print("Test ");
ans = in.nextLine();
}
But if you are going to include many more options, it's better to provide a method that takes the input as argument, evaluates and returns True if the input is accepted.

Don't compare the user input against a value as loop condition?!
Respectively: change that loop condition to something like
while(! ans.trim().isEmpty()) {
In other words: keep looping while the user enters anything (so the loop stops when the user just hits enter).

You are looking for a method to check whether a given string is included in a List of string values. There are different ways to achieve this, one would be the use of the ArrayList contains() method to check whether your userinput in appears in a List of i.e. 'positive' answers you've defined.
Using ArrayList, your code could look like this:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<String> positiveAnswers = new ArrayList<String>();
positiveAnswers.add("yes");
positiveAnswers.add("sure");
positiveAnswers.add("y");
Scanner in = new Scanner(System.in);
String ans = "yes";
while (positiveAnswers.contains(ans))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}

Related

How to check if String contains values from an array

I am fairly new to Java and was trying to make a username check for profanities.
I have made an Array with 4 profanities and now I wanted to check the user's input for the bad words, however, I don't know how to form the if statement to check all items from the array.
public static void main(String[] args) {
Scanner character = new Scanner(System.in);
String[] profanities = {"asshole", "ass", "idiot", "stupid"};
System.out.println("What is your name");
String userName = character.next();
if (userName.contains(profanities[])) { //This Part is what i dont understand
System.out.println("Invalid name");
}
else {
System.out.println("Valid Name!");
}
}
Use a Set instead of an ArrayList and then profanities.contains(userName). Mind you, the user should have inputted the exact profanity as in the profanities Set, in order for the if statement to evaluate to true. If the user inputs something like 'userjackass', it will not be classed as profanity.
Without the need of creating further Collections, just your original array. As the set of invalid names would be previously set/known, the sort operation could only be performed once, when the program is started.
Once sorted, just call binarySearch on it for every input:
Arrays.sort(profanities); //--> if profanities is a static set, call this just once.
if (Arrays.binarySearch(profanities,username)>=0)
System.out.println("Invalid name");
else
System.out.println("Valid Name!");
//binarySearch will return >=0 if the value is found
This avoids the creation of sets, lists, or the implementation of loops.
If the set of invalid names may change (adding new ones, for example), this would require a second sort operation. In this scenario, the other answers provided would be a better approach. Use this method if the invalid names set is known and won't be altered during your program's execution.
I would do it like this..
import java.util.Scanner;
public class Profanities {
public static void main(String[] args) {
boolean allow = false;
Scanner scan = new Scanner(System.in);
String[] profanity_list = {"asshole", "ass", "idiot", "stupid"};
String test_input = "";
// do while until allow equals true..
while (!allow) {
System.out.println("What is your name?");
test_input = scan.nextLine();
byte memory = 0;
// compare the input with the elements of the array..
for (int pos = 0; pos < profanity_list.length; pos++) {
if (test_input.contains(profanity_list[pos]) == true) {
System.out.println("Invalid name. Let's start again..");
memory = 1;
break;
}
}
// if memory equals 1, it means that a profanity was found..
if(memory == 0){allow = true;}
}
String name = test_input;
System.out.println("That is a valid name. Thanks.");
}
}
Instead of using Array of String, use List of String from which you can easily use contains method. I modified you're code with List, refer below
public static void main(String[] args) {
Scanner character = new Scanner(System.in);
//String[] profanities = {"asshole", "ass", "idiot", "stupid"};
ArrayList<String> profanities = new ArrayList<String>();
profanities.add("asshole");
profanities.add("ass");
System.out.println("What is your name");
String userName = character.next();
if (profanities.contains(userName)) { //This Part is what i dont understand
System.out.println("Invalid name");
}
else {
System.out.println("Valid Name!");
}
}
One more advantage of using List is, it's dynamic, you can add elements to it in future without any issues
Try:
for(String string : profanities)
if(userName.contains(string))System.out.println("invalid name");
else System.out.println("valid name");
Note: the for loop iterates through every entry in the array and checks to see if the entry is contained within userName

How to get this piece of code into loop, so that it asks a user input each time until the result is "kill"?

I was practicing this piece of code from the book 'Head First Java' and I'm quite confused on the positioning of the loop here.The code is for creating a kind of game that has a random dotcom word(ex: abc.com) occupying some array elements. here I gave that dotcom word the positions from 3 to 5 in the array, and the user tries guessing the position.
import java.util.Scanner;
public class RunTheGame {
public static void main(String[] args) {
MainGameClass sampleObj= new MainGameClass();
int[] location = {3,4,5};
sampleObj.setdotcomLocationCells(location);
Scanner input= new Scanner(System.in);
System.out.println("Enter your guess");
int userGuess=input.nextInt();
String answer = sampleObj.checkForDotcom(userGuess);
System.out.println(answer);
}
}
package simpleDotComGame;
public class MainGameClass {
int[] DotcomLocationCells;
int numOfHits=0;
public void setdotcomLocationCells(int[] location) {
DotcomLocationCells= location;
}
public String checkForDotcom(int userGuess) {
String result="miss";
for(int cell:DotcomLocationCells) {
if(cell == userGuess) {
result ="hit";
numOfHits++;
break;
}
} // end for loop
if(numOfHits == DotcomLocationCells.length) {
result = "kill";
System.out.println("The number of tries= "+numOfHits);
}
}
do {
<insert code where answer result is created>
} while (!answer.equals("kill"))
upd.: but you must override the equals method for correct use, because if you see how method declared in Object.class you find
public boolean equals(Object obj) {
return (this == obj);
You are allowed to declare the variable before initializing it:
String answer;
do {
answer = sampleObj.checkForDotcom(userGuess);
System.out.println(answer);
} while (!answer.equals("kill");
Also beware of the semantics of Scanner.nextInt(): if it can't parse the input as an int (for example, it contains letters), it will throw an exception, but won't jump over the invalid input. You'll have to use Scanner.nextLine() to force-jump over it, otherwise you'll get an infinite loop.
Rachna, the loop will be positioned, around the following code:
Scanner input= new Scanner(System.in);
System.out.println("Enter your guess");
int userGuess=input.nextInt();
String answer=sampleObj.checkForDotcom(userGuess);
System.out.println(answer);
//For string you must use the equals
if ("kill".equals(answer)){
break;
}
The reason why is that the kill command must be evaluated inside the loop to break it, and the input to continuously ask the user input until he hits all targets.
Here's how the loop should be positioned.
String answer = "";
do{
System.out.println("Enter your guess");
int userGuess=input.nextInt();
answer=sampleObj.checkForDotcom(userGuess);
System.out.println(answer);
}
while(!answer.equals("kill"));
NOTE: Never Check for String equality using == in Java unless you know what you're doing (also read as, unless you know the concept of String Constant Pool).

How to match user input with arraylist

package BankingSystem;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Bank {
public static void main(String [] args){
List<String> AccountList = new ArrayList<String>();
AccountList.add("45678690");
Scanner AccountInput = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
AccountInput.nextLine();
for (int counter = 0; counter < AccountList.size(); counter++){
if (AccountInput.equals(AccountList.get(counter))){ //If Input = ArrayList number then display "hi"
System.out.println("Hi");
}
else { //If not = to ArrayList then display "Incorrect"
System.out.println("Incorrect");
}
}
}
}
Hi, in here I am trying to match the userInput to arrayList, if its correct then display "hi" if not display "Incorrect", for the incorrect part do I to use exception handling? and how can I get it to match the ArrayList number - 45678690?
.nextLine() returns a string which needs to be assigned to a variable ....
And then compare the variable with elements in the arraylist using .contains() method ...
If you also want the index position use .indexOf() method ...
String input = AccountInput.nextLine();
if(AccountList.contains(input))
// do something
else
// do something else
First things first you need to store your user's input into some string as you currently aren't doing that.
Instead of using a counter and iterating through your list you can instead just use
AccountList.contains(the string variable assigned to AccountInput)
If it's false then the entry isn't there, otherwise it's in there. The exception handling you might want to use in this scenario would be to handle a user inputting letters instead of numbers.
You have to store the input value in a string to check the number :
String value = AccountInput.nextLine();
if (value.equals(AccountList.get(counter))) ...
Start variables with lower case. Names that start with upper case is for Classes only in java. So use List<String> accountList , and not List<String> AccountList .
The main problem in your code is that you are comparing the elements in list with the Scanner-object. And that will always be false.
You also never store the input from the Scanner any place.
You need to place the return value somewhere, like
String input = scanner.nextLine();
and compare the strings in the list to this string, not the Scanner-object.
I've added a flag so that it works correctly with multiple items in the accountList.
List<String> accountList = new ArrayList<String>();
accountList.add("45678690");
accountList.add("1");
accountList.add("0");
Scanner scanner = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
String accountInput = scanner.nextLine();
boolean listContainsInput = false;
for (int counter = 0; counter < accountList.size(); counter++){
if (accountInput.equals(accountList.get(counter))){
listContainsInput = true;
break;
}
}
if(listContainsInput) {
System.out.println("Hi");
} else {
System.out.println("Incorrect");
}
You are comparing the instance of the Class Scanner
Scanner AccountInput = new Scanner(System.in);
To a String:
AccountInput.equals(AccountList.get(counter))
(ArrayList.get(int) returns a String or fires an Exception)
You need to start with comparing String to String first:
AccountInput.nextLine().equals(AccountList.get(counter))
If you need additional debbuging see how both strings look like(e.q. print 'em)
Here is documentation on Scanner:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Read it, scanner is important thing in programming languages.

Why does it not ask me for input?

import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner name = new Scanner(System.in); ## I am asking for input form user but it does not take imput
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
}else System.out.println("Well good meet");
}
}
Why does the program run the else and not ask for my input?
You should read your input by using scanner.nextLine():
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
if (name.equals("me") || name.equals("Me"))
{
System.out.println("Well, good for you smartass.");
} else {
System.out.println("Well good meet");
}
scanner.close();
You merely created a Scanner but did not tell it to read something from the standard input. You can do that by calling scanner.next() to read a token scanner.nextLine() to read a line, etc. As well you are comparing a Scanner to a String in the if-statement.
import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner s = new Scanner(System.in);
String name = s.next(); // get the token
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
} else System.out.println("Well good meet");
}
}
You've only created an instance of the Scanner object. You need to invoke a method such as Scanner#nextLine() to read input and then compare the read value to "me" or "Me".
Example:
Scanner name = new Scanner(System.in);
String input = name.nextLine();
if (...) // Compare input to something here.
You might want to use String#equalsIgnoreCase for case-insensitive matching too.

How do I set the statement if to read letters instead of numbers?

"if" statement only allows to put numbers in it.
Is there a way to make it read letters?
I'm only in my fifth lesson of Java (I study in a uni and the teacher is very slow but I want to learn things fast)
for example.
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
int answer1;
System.out.println("Do you like Java?");
answer1 = scan.nextInt();
if (answer1 == yes)
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I want to put "yes" instead of the number 5.
So if the user types "yes" it will print "correct".
P.S. I didn't find a clear answer to that in the search engine.
It's not a duplicated thread as I'm trying to find a clear answer to that.
I need a detailed explanation about it.
I'm still a beginner, using those "high tech java words" won't help me.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's now a String. See this answer for more on comparing Strings.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner; public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
} }
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's
now a String. See this answer for more on comparing Strings.
Ok, what if you want the program to read both words and numbers:
Here's my program (more in depth, when you see the full thing), but this is one of 5 parts (that look a like) where I'm having the program...
public static void Gdr1() {
try {
System.out.print("[Code: Gdr1] Grade 1: %");
Scanner gdr1 = new Scanner(System.in);
Z = gdr1.next();
Z = Double.toString(Grd1);
Grd1 = Double.parseDouble(Z);
if ((Grd1<100)&&(Grd1>=5)) {
Gdr2();
} else if ((Grd1>=100)&&(Grd1<125)) {
System.out.println(" System> Great Job "+Stu+"!");
Gdr2();
} else if (Grd1<5) {
System.out.println("I'm sorry, the lowest grade I am allowed to compute is 5...");
Gdr1();
} else if (Z.equalsIgnoreCase("restart")) {
restart01();
} else {
System.out.println("("+Z+") cannot be resolved in my system...");
Gdr1();
}
} catch (Exception e) {}
}
Now everything works in the program, besides for when the End-User's input = "restart", I know some of the code in the program seems complicated, but it does work (most of it), can anyone help me try to figure this out, its for my portfolio at my school due latest by 1/25/2017 # 11:59 pm.
The things like Z (constant String), ""+Stu+"" (variable input), and [Code: Gdr1] are there for a purpose...

Categories

Resources