Java array question - java

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.

Related

Java HashSet object adding

I am trying to go through a text from a file, get each Word and save it as a Word object in a HashSet but i am alway getting the size 1 for the HashSet,it stores only the first object, i dont know maybe there is some really easy way to do it, or maybe i have made some stupid mistake here are you the code:
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\Taner\\Desktop\\words.txt");
Scanner input = new Scanner(file);
HashSet<Word> wordHash = new HashSet<>();
while (input.hasNextLine()) {
String line = input.nextLine();
for (String retval: line.split(" ", 0)){
wordTree.add(new Word(retval));
}
}
input.close();
System.out.println(wordTree);
}
This can happen if Word has a broken implementation of hashCode and equals:
it would seem that all the values added in the HashSet are the same.
Check the implementations of those methods in Word.
If you use an IDE like Eclipse or IntelliJ,
it can generate correct implementations for hashCode and equals.
I suggest you use that.

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.

Simple Array: Check to see if value matches

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()

How do I add an element to the end of my array?

I don't know if this is right, so I need your comments guys. I have an array of employee names. It will be displayed on the console, then will prompt if the user wants to insert another name. The name should be added on the end of the array(index 4) and will display again the array but with the new name already added. How do I do that? Btw, here's my code. And I'm stuck. I don't even know if writing the null there is valid.
public static void list() {
String[] employees = new String[5];
employees[0] = "egay";
employees[1] = "ciara";
employees[2] = "alura";
employees[3] = "flora";
employees[4] = null;
for(int i = 0; i < employees.length; i++) {
System.out.println(employees[i]);
}
}
public static void toDo() {
Scanner input = new Scanner(System.in);
System.out.println("What do you want to do?");
System.out.println("1 Insert");
int choice = input.nextInt();
if(choice == 1) {
System.out.print("Enter name: ");
String name = input.nextLine();
You can't, basically.
Arrays have a fixed size when they've been constructed. You could create a new array with the required size, copy all the existing elements into it, then the new element... or you could use a List<String> implementation instead, such as ArrayList<String>. I'd strongly advise the latter approach.
I suggest you read the collections tutorial to learn more about the various collections available in Java.
Also note that you've currently just got a local variable in the list method. You'll probably want a field instead. Ideally an instance field (e.g. in a class called Company or something similar) - but if you're just experimenting, you could use a static field at the moment. Static fields represent global state and are generally a bad idea for mutable values, but it looks like at the moment all your methods are static too...
Arrays are fixed in size. Once you declare you can not modify it's size.
Use Collection java.util.List or java.util.Set. Example ArrayList which is dynamic grow-able and backed by array.
If you really have to use arrays then you will have to increase the size of the array by using an intermediate copy.
String[] array = new String[employees.length + 1];
System.arraycopy(employees, 0, array, 0, employees.length);
array[employees.length] = newName;
employees = array;
However, the best way would be to use a List implementation.
It depends on whether the user can enter more than 4 employee names. If they can then using ArrayList is the better choice. Also the employees variable needs to be a static property of your class since being used in a static method.
private static String[] employees = new String[5];
static {
employees[0] = "egay";
employees[1] = "ciara";
employees[2] = "alura";
employees[3] = "flora";
employees[4] = null;
}
public static void list() {
for(int i = 0; i < employees.length; i++) {
System.out.println(employees[i]);
}
}
public static void addEmployeeName(String name, int index) {
employees[index] = name;
}
Here you are using static array which is fixed at the time of creation.I think you should use
java.util.Arraylist which will provide you facility of dynamic array.

Categories