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
Related
The repl.it link below takes you to a piece of code which I am currently working on. It is a test for creating a 2D array and searching through it for specific values. I would like to implement this into other code to allow a user to input an email, username and password while signing up and store it in a 2D array as a new account. Then during a login it will search for the password associated with the email entered and compare it to the password which is entered.
The code in main method is to allow me to create the 2D array which will store three accounts and enter test information. It then prints the 2D array to prove it has been created. The search method is meant to then search through the array for the password associated with an email which I enter. However, there is a problem with the code so that it never finds the email in the array. I have ensured it cycles through the array by making it print the email which it is meant to be comparing the value being searched for and then prints next. It does cycle through this array.
I believe the problem is when the code compares the entered value to the value the code has found. I do not know how to fix this as the code should find the email and be able to print the password.
This is likely an easy fix but I need some help.
Thank you for any responses.
https://repl.it/#Griff0408/ArrayTestCurrent#Main.java
import java.util.Scanner;
import java.util.Arrays;
class Main {
static int rowNumber = 3;
static int colNumber = 3;
static String[][] Accounts = new String[3][3];
public static void main(String[] args) {
for (int row=0;row<rowNumber;row++) {
for (int col=0;col<colNumber;col++){
Scanner sc = new Scanner(System.in);
if (col==0) {
System.out.println("Enter e-mail:");
String yourEmail = sc.nextLine();
Accounts[row][col] = yourEmail;
} else if (col==1) {
System.out.println("Enter Name:");
String yourName = sc.nextLine();
Accounts[row][col] = yourName;
} else {
System.out.println("Enter password:");
String yourPassword = sc.nextLine();
Accounts[row][col] = yourPassword;
}
}
}
System.out.println(Arrays.deepToString(Accounts));
search();
}
public static void search() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter email:");
String searchEmail = sc.nextLine();
boolean found = false;
int currentRow = 0;
while (found==false){
if (currentRow < rowNumber) {
String arrayEmail = Accounts[currentRow][0];
System.out.println(arrayEmail);
if (arrayEmail == searchEmail){
found = true;
System.out.println("Email: " + Accounts[currentRow][0] + "\nPassword: " + Accounts[currentRow][2]);
} else {
currentRow++;
System.out.println("next");
}
} else {
System.out.println("Email not found.");
found = true;
}
}
}
}
Strings in java are actually objects! So unlike primitive data types when two strings are compared with the equality operator we just compare whether those are the same object.
Fortunately there is a simple way to fix this. The equals method.
if (arrayEmail.equals(searchEmail)){
found = true;
System.out.println("Email: " + Accounts[currentRow][0] + "\nPassword: " + Accounts[currentRow][2]);
}
I have also provided a working REPL https://repl.it/#dehan/ArrayTestCurrent#Main.java
You are using == which is reference comparision parameter.
If you want to compare content use equals method.
The problem is most likely due to the fact that you use "==" to compare the strings.
"==" does not compare string values, it checks whether the two strings are the same object.
Instead of if (arrayEmail == searchEmail) use if (arrayEmail.equals(searchEmail))
When I run this program, it does not return anything yet no errors occur. I'm trying to create a method that will return the number of words I previously entered into the array once I enter "".
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayCounter {
public static int CountItems(ArrayList<String> list ) {
int i = list.size();
return i;
}
public static void main (String args[]) {
ArrayList<String> Names = new ArrayList<String>();
Scanner input = new Scanner(System.in);
while(true) {
System.out.println("Hey gimme a word");
String word = input.nextLine();
if (word.equals("")) {
System.out.println("The number of values entered were:");
break;
} else {
Names.add(word);
}
}
CountItems(Names);
input.close();
}
}
You're ignoring the result returned from CountItems.
The println should be:
System.out.println("The number of values entered were: " + CountItems(Names));
As an aside, methods names in Java should start with a lowercase, so CountItems should instead be countItems.
Your CountItems method returns the item count, but you are ignoring the result. You need some kind of System.out.println(CountItems(Names)) to print the result to the console.
Also, please consider renaming CountItems to countItems and Names to names to follow the naming conventions for 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();
}
}
}
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.
The program does one thing, depending on the users input, it removes an arraylist object and will ask you if u you want to remove another object, however, if the same object tries to be removed, i need the program to know and output 'such object does not exist', for example, 'remove "3"', then remove "3" again, the program output's "3" does not exist, the problem is that i have no idea how to implement it, what i have does not do much either. My theory is that you have to use boolean to check if the arraylist object is there in the first place, if it is: remove it, if not: output "not there".
here's what i have:
String[] id1 = { "1", "studentA" };
ArrayList<String> jim = new ArrayList<String>(Arrays.asList(id1));
System.out.println("would you like to remove an id? if so type in "
+ "the id number, otherwise type: no");
Scanner sc = new Scanner(System.in);
String i = sc.next();
int position = -1;
position = jim.indexOf(sc) - 1;
if (position == -1) {
System.out.println("not found in list");
} else {
System.out.println("found and removed");
jim.remove(i);
}
System.out
.println("would you like to remove another id? if so type in "
+ "the id number, otherwise type: no");
Scanner sc2 = new Scanner(System.in);
String j = sc.next();
int position2 = -1;
position2 = jim.indexOf(sc) - 1;
if (position2 == -1) {
System.out.println("not found in list");
} else {
System.out.println("found and removed");
jim.remove(j);
}
If you want your program to keep on asking for user input, you need a loop, for example a while-loop, which will only terminate if the user inputs no. In addition to that, you can simply use List.remove() for removing the element, and inspect the return value (true if the item was in the list and was removed) to give the correct feedback to the user:
String[] elements = { "1", "studentA" };
ArrayList<String> list = new ArrayList<String>(Arrays.asList(elements));
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("would you like to remove an id? if so type in "
+ "the id, otherwise type: no");
String input = sc.next();
if ("no".equalsIgnoreCase(input)) {
break; // exit the loop
}
if (list.remove(input)) {
System.out.println("found and removed");
} else {
System.out.println("not found in list");
}
}
I would suggest using public boolean remove(Object o) and this will return either true or false if the element is apart of the ArrayList or not respectively. You can set some boolean variable to equal that, and use an if statement to output your desired response.
boolean contains(Object o) would check if the ArrayList contains the object, you could scan through the list and check if it is there or not. You could also use the E get(int index) to scan through and check if the strings are equal to each other using a loop.