Simple Array: Check to see if value matches - java

I am simply trying to see if the inputted value matches a value that is already in the array and if it does return "Valid". I realize this is very simple but I cannot get this to work:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String[] accountNums = { "5658845", "8080152", "1005231", "4520125", "4562555",
"6545231", "7895122", "5552012", "3852085", "8777541",
"5050552", "7576651", "8451277", "7881200", "1302850",
"1250255", "4581002" };
String newAccount;
String test = "Invalid";
newAccount = keyboard.next();
for (int i = 0; i < accountNums.length; i++)
{
if(newAccount == accountNums[i])
{
test = "Valid";
}
}
System.out.println(test);
}
}
thank you for any assistance (and patience)

Use equals method. Check here why to.
if (newAccount.equals(accountNums[i]))

Jayamohan's answer is correct and working but I suggest working with integers rather than Strings. It is a more effective approach as CPUs handle numbers (integers) with a lot more ease than they handle Strings.
What has to be done in this case is change newAccount and accountNums to ints instead of Strings and also remove all the quotation marks from the accountNums initialization. Instead of calling keyboard.next() you can call keyboard.nextInt(), which returns an integer. The if-statement is fine as it is.

Why are you using an array?
List<String> accountNums = Arrays.asList( "5658845", "8080152", "1005231", "4520125", "4562555",
"6545231", "7895122", "5552012", "3852085", "8777541",
"5050552", "7576651", "8451277", "7881200", "1302850",
"1250255", "4581002" );
String test = "Invalid";
Then you just need this (no loop):
if (accountNums.contains(newAccount)) {
test = "Valid";
}
Plus, it's easier to read and understand.

You cannot compare strings with ==
You must use .equals()

Related

Java pass values into method/function

Ok, first of all: hello!
I'll be short.
public static Boolean or (boolean... args){
// some code to process args and return true or false
return hasArgs & kiekFalse!=args.length ? true : false;
}
Here I have a function called "or" and it has unknown amount of parameters that can be passed into it. I need it, cause I really can't know it.
so
I can use it like that
System.out.println(or(true,true,true,false,true,false));
BUT
what to do when I need to read values for example, for keyboard?
read and convert to Boolean array? does not work, it requires Boolean, not Boolean[]. Cannot resolve method 'or(java.lang.Boolean[]'
Pass one by one? nope, I need to pass none or required amount at once.
Any ideas or suggestions?
Ideally, I'd need to figure out how to pass N Booleans from keyboard to or function.. Else I'll just need to rewrite some (a lot of) code.
Create an overload which takes a Collection<Boolean>, converts it to a boolean[], then invokes the method:
Boolean or(Collection<Boolean> c) {
boolean[] b = new boolean[c.size()];
int i = 0;
for (Boolean cb : c) {
b[i++] = cb; // assuming no nulls.
}
return or(b);
}
(Or you can take a Boolean[] parameter; it makes little difference, you just have to use length instead of size().)
Then you can just read your booleans in from user input into a List, and invoke this method.
List<Boolean> listOfBooleans = new ArrayList<>();
// Read values, add to list
Boolean result = or(listOfBooleans);
If you're already using Guava, you can use Booleans.toArray():
or(Booleans.toArray(listOfBooleans))
You can read an entire line as a string and then parse it:
System.out.println("Enter some booleans (true/false) separated by spaces: ");
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
Boolean[] booleans =
Arrays.stream(line.split(" ")).map(Boolean::valueOf).toArray(Boolean[]::new);
You can pass an array of boolean to the method. I wrote a quick example of parsing a boolean from a string, storing it in an array and passing it to your or method:
public static void main(String[] args) {
boolean[] vals = new boolean[1];
vals[0] = Boolean.parseBoolean("false");
}
public static boolean or(boolean... args) {
return hasArgs & kiekFalse!=args.length ? true : false;
}
I would suggest to read the booleans line by line from the keyboard input and just pass then into an array or a list.
Hope it solves your problem.

Comparing Two strings with different order

I am having a string of the form as
PosAttributes: FN,CT,ST;
Now when i compute some functionality i get a string as
PosAttributes1: FN,ST,CT;
Now though both the strings suggest the same thing and if use following equal function it returns false. I know both stings are not same, but the semantics are same. What should i do?
PosAttributes.equals(PosAttributes);
As the string is delimitered by commas you could use a String.split to give
String arr[] = PosAttributes.split (",");
String arr2[] = PosAttributes1.split (",");
then you just need to loop through the first arrays ensuring that ALL elements are in the second array. Also check that the sizes are identical.
You need to break out the individual sections of each String, and store them in some kind of Set - that's a structure where either there's no order, or where the order doesn't affect the outcome of the equals method. I'd write a method like this.
private static Set<String> attributeSet(String input) {
String[] attributes = input.split(",");
return new HashSet<String>(Arrays.asList(attributes));
}
This breaks a String into its segments, assuming the separator is a comma. Then it uses a standard trick to convert the resulting array into a HashSet, which is a commonly used type of Set.
Then when I want to compare two strings, I could write something like
if (attributeSet(string1).equals(attributeSet(string2))) {
// ...
}
So assuming that the example text is the full text, you need to remove the ; character, as this would change the contents of the String, split the String on the , character, sort the resulting arrays and compare them, something like...
String[] v1 = "FN,CT,ST;".replace(";", "").split(",");
String[] v2 = "FN,ST,CT;".replace(";", "").split(",");
Arrays.sort(v1);
Arrays.sort(v2);
System.out.println(Arrays.equals(v1, v2));
Which outputs true
What I might be tempted to do is write a method which returned a sorted array of the String, replicating all the common functionality...
public static String[] sorted(String value) {
String[] v1 = value.replace(";", "").split(",");
Arrays.sort(v1);
return v1;
}
And then you could simply call it, which would allow you to do a single like comparison...
System.out.println(Arrays.equals(sorted("FN,CT,ST;"), sorted("FN,ST,CT;")));
The next step might be to write a method which returns true, which called sorted and Arrays.equals to make it easier...
System.out.println(isEqual("FN,CT,ST;", "FN,ST,CT;"));
But, I'll leave that up to you ;)
You can either override the equal method or sort both string then compare them.
I have the same requirement at work right now and wanted to avoid using lists for the evaluation.
What I did was to check if the two string to compare are of equal length - this means that it is possible that they might be the same, just with different order.
Now remove one by one comma-separated string in the main string, found in the compare string. If the output of the main string is empty, that means the two are an exact math. Please see the pseudo-code below (I did not paste the actual code because it has some company specific info):
private static boolean isStringCombinationEqual(final String main, final String compare)
{
boolean result = false;
String modifiedMain = main;
// if not the same length, then cannot possibly be same combination in different order
if (main.length() == compare.length())
{
final String[] compareArr = // split compare using delimiter
for (int i = 0; i < compareArr.length; i++)
{
if (i > 0)
{
modifiedMain = // replace delimiter with empty string
}
modifiedMain = // replace compareArr[0] with empty string
}
if (//modifiedMain is empty)
{
result = true;
}
}
return result;
}

Returning the String at the index typed in by the user (ArrayList)

I'm trying to create a simple method. Basically, I want this method (called "returnIndex") to return the word at the ArrayList index number the user types in.
Example:
If the user types in "1", is should return whatever String is at index 1 in the ArrayList.
This is what I have so far:
public void returnIndex ()
{
Scanner in = new Scanner (System.in)
while (in.hasNextLine())
{
if (in.equals(1))
{
//return item at that index
}
}
}
I'm just not sure how to say "return the item at that index" in Java. Of course, I'll have to make the code work with any other number, not just '1'. But for now, I'm focusing on '1'. Not even sure if the in.equals(1) part is even 100% right.
My apologies if this question seems a little elementary. I'm still working on my Java. Just hints please, no complete answers. Thank you very much.
public String returnIndex(Scanner in, List<String> list) {
return list.get(in.nextInt());
}
Don't create new Scanners as it can cause subtle problems. Instead, create only one and keep using it. That means you should pass it into this function.
There's no need to use ArrayList when List will do (as it will here).
You need to make the function return String, not void, if you want it to return a String.
public static void main(String[] args) {
List<String> values = new ArrayList<String>();
values.add("One");
values.add("Two");
values.add("Three");
String result = getStringAtIndex(values);
System.out.println("The result:" + result);
}
public static String getStringAtIndex(List<String> list) {
Scanner scanner = new Scanner(System.in);
int index = 0;
index = scanner.nextInt();
return list.get(index-1);
}

Java, returning Strings error

I am very new to programming and am quite young.
I have no friends/family who can help me so I am seeking help on the internet. There is problem with my code as it isn't working as I intend it.
Instead of printing out what the variable "TheChoice", it just ends.
This isn't all the code and I have consised it so that it will be easier to read and maybe more people will be able to quickly answer.
However, this is definately the part of my code which I have messed up).
public String Choices(String value1, String value2)
{
Scanner x = new Scanner(System.in);
if(x.next() == value1){return value1;}
if(x.next() == value2){return value2;}
}
// Separate class...
ChoiceClass Object1 = new ChoiceClass();
String TheChoice = Object1.Choices("Ham", "Cheese");
System.out.println(TheChoice);
There's a number of issues with your code.
Firstly, you compare Strings with == instead of equals (there's
a ton of literature about String comparison and Object equality
in Java, I suggest you take a look here and here.
Secondly, you don't always return a value in your choices method. Your method must return a String (even in its default value, as null), but you're not considering user inputs other than given arguments.
Also your Scanner next wouldn't work as you're calling it twice,
when you only want to call it once.
Finally, you should take a look at Java naming conventions: method
names are camelBack. See here for code conventions.
Here's a snippet that'll probably help you out:
public static String choices(String value1, String value2) {
Scanner x = new Scanner(System.in);
System.out.println("Type your choice and ENTER...");
String input = x.nextLine();
if (input.equals(value1)) {
return value1;
}
else if (input.equals(value2)) {
return value2;
}
// handling other user inputs
else {
return "nothing";
}
}
public static void main(String[] args) {
// usage of method. Note that you could also refactor with varargs, as in:
// String... values in method signature.
// This way you could iterate over values and check an arbitrary number of values,
// instead of only 2.
System.out.println(choices("foo", "bar"));
}
Output:
Type your choice and ENTER...
... then either "foo" or "bar" or "nothing" according to input.
You can use something similar to this:-
public String Choices(String value1, String value2)
{
Scanner x = new Scanner(System.in);
String option=x.next();
if(option!=null)
{
if(option.equals(value1)) return value1;
else if (option.equals(value2)) return value2;
}
else return option;
}
If you want to compare Strings just use equals no need to use Scanner here.

Java array question

Sorry, silly question here, I have googled it but anything I search for seems to be returning methods of using binary search etc., but what I need is actually much simpler.
I have an array of languages. I am creating a scanner, asking for input. Trying to make it so that if the language input by the user isn't in the array, it displays an error and asks again. Should be simple, I have just drawn a blank.
Can anyone help please ? Here is what I have so far !
Scanner scan = new Scanner(System.in);
language = scan.next();
while( language NOT IN ARRAY languages) {
System.out.print("error!");
language = scan.next();
}
I understand your question better now. You should use a Set for sure. But you will want to use the contains() method of the set to check if the language exists.
Scanner scan = new Scanner(System.in);
language = scan.next();
while(!set.contains(language)) {
System.out.print("error!");
language = scan.next();
}
Old answer, still relevant info though:
What yo want to use is a Set collection type. A set does not allow duplicate entries.
From the Javadocs:
A collection that contains no duplicate elements.
Set<String> set = new HashSet<String>();
// will not add another entry if set contains language already
set.add(language);
Also, if you want to know if the value was rejected or not, you can use the return type of the add() method. It returns true if the item did not exist, and false otherwise.
You can do something like:
public static boolean contains(String language, String[] lang_array) {
for (int i = 0; i < lang_array.length; i++) {
if (lang_array[i].equals(language))
return true;
}
return false;
}
public static void main(String[] args) {
String[] lang_array = {"Java", "Python", "Ruby"};
Scanner scan = new Scanner(System.in);
String language = scan.next();
while(!contains(language, lang_array)) {
System.out.print("error!");
language = scan.next();
}
}
You can do this is you really need to use an array:
Arrays.sort(languages);
Scanner scan = new Scanner(System.in);
language = scan.next();
while( Arrays.binarySearch(languages, language) < 0) {
System.out.print("error!");
language = scan.next();
}
There are two things you can do:
Either iterate through the array and compare the contents on each element to what you're trying to see if it's there every time you add a language.
OR
Use a LinkedList or some other kind of Java Structure that has a .contains() method, this will, in a way, do something similar to what I mentioned for the Array.

Categories