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))
Related
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
I have the following code that gets a user input:
456589 maths 7.8 english 8.6 end
654564 literature 7.5 physics 5.5 chemistry 9.5 end
and stores the code at the beginning of the sentence in an array called grades and the code in another array called person. I need to use these two arrays in order to display later each person's average grade in each lesson.
My code is the following
import java.util.Scanner;
public class Student
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String currentAnswer = "";
String userWords = "";
String am = "";
String subj = "";
float grad;
float[] grades = new float[100];
String[] person = new String[100];
System.out.println("Enter your a.m. as well as the subjects which you sat in finals");
while(!currentAnswer.equals("end"))
{
currentAnswer = s.nextLine(); // reads the number or word
userWords += currentAnswer + " ";
if(currentAnswer.equals("000000"))
{
System.out.println("The sequence of numbers you entered is: "+userWords);
System.out.println("Exiting...");
System.exit(0);
}
String[] wordsplit = currentAnswer.split(" ");
for (String str : wordsplit)
{
try
{
grade = Float.parseFloat(str);
}
catch(NumberFormatException ex)
{
person = str;
}
}
}
System.out.println("Enter your a.m. as well as the subjects which you sat in finals");
}
}
The error message concers the lines
grades = Float.parseFloat(str);
person = str` --> `String cannot be converted to String[]`<br>
Seems that converting a String into a String array is prohibited. What can I do in order to avoid this?
thank you!!
Look again on the code
grade = Float.parseFloat(str); and vars declaration
float grad; float[] grades = new float[100]
Cannot see any grade !
This cannot compile for sure !
Well, the error message speaks for itself, you are trying to assign String into String[], since it is an array, you want to call something like person[0] = str, same thing with grade, you want to call grade[0] = Float.parseFloat(str)
... but ofc you probably want to store number of persons inserted into the array, so you create an int inserted = 0 and then call grade[inserted] = Float.parseFloat(str) and also call inserted++ after that (or simply call grade[inserted++] = Float.parseFloat(str).. I assume you will need one integer for persons and one for grades
Try using ArrayLists, there are more forgiving than arrays, and simple to learn. You can see more about them here:
https://www.w3schools.com/java/java_arraylist.asp
If you want to use ArrayList, you must include this in begging of your file.
import java.util.ArrayList;
You defined grad and used grade
Initially when you defined you used the variable name grad
float grad;
But you used grade here
grade = Float.parseFloat(str);
Also try to use ArrayList instead of String array
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).
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.
I need to write a program that will have a user enter a list of tutor names. Only up to 10 peer tutors may be hired. Then, the program will present each name, based on a list alphabetized by last name. This is what I have so far, but it does not work and I don't know what to do. I need it to continue to run until I stop it and continue with more of the program.
import javax.swing.JOptionPane;
import java.util.Arrays;
public class Report {
public static void main(String[] args) {
int numTutors = 10;
String[] listNames = getTutorNames();
}
public static String[] getTutorNames() {
String firstName;
String lastName;
String[] listNames = new String[10];
for (int x = 0; x < listNames.length; x++) {
firstName = JOptionPane.showInputDialog(null, "Enter Tutor's First Name: ");
lastName = JOptionPane.showInputDialog(null, "Enter Tutor's Last Name: ");
if (firstName.equals("")) && lastName.equals("")) {
break; // loop end
}
listNames[x] = lastName + ", " + firstName;
}
return listNames;
}
}
Well, this is a first. IntelliJ didn't format the code correctly when I edited it, and I soon discovered this hit-list of errors. Just bear in mind - the code won't even compile, let alone run, until these are fixed.
int numTutors comes out of nowhere. If you want to define it, then do so outside of the method call and set it to an appropriate value.
public static void main(String[] args) {
int numTutors = 10;
String[] listNames = getTutorNames(numTutors);
}
These declarations are invalid:
String = firstName;
String = lastName;
You need some sort of variable name in between String and =.
You're also not matching the contract for what you're passing in to getTutorNames - either what you pass in or what you accept must change. I'm thinking that it's the latter.
You can't use == to compare String. You have to use .equals(). Which leads me to...
Your break is outside of your loop. Move it inside of the loop.
for (int x = 0; x < listNames.length; x++) {
firstName = JOptionPane.showInputDialog(null, "Enter Tutor's First Name: ");
lastName = JOptionPane.showInputDialog(null, "Enter Tutor's Last Name: ");
if (firstName.equals(" "))&&lastName.equals(" ")){
break; // loop end
}
}
..and that leads me to...
You don't put the values anywhere through the loop! You're just running the same code ten times! Place them into the array.
// after you check to see if the firstName and lastName are blank
listNames[x] = firstName + lastName; // I don't know what you want to do with them from here.
There is no .add() for an array. The above is how you enter elements into an array.
Your return is outside of your method block entirely. Move it into your method.
Now, these are the issues that I could find. Work on the compilation issues first, then one may talk about errors in code logic. If you can, snag a quiet moment and ensure you understand variable declaration and String comparison. I would strongly recommend the reading material found in the Java wiki tag.
So sorry for making an answer for something this small but your
If (firstName.equals("")) && lastName.equals("")) {
Should be replaced by
If ((firstName.equals("")) && lastName.equals(""))) {