Java pass values into method/function - java

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.

Related

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.

Return multiple arrays to the main method

My program is suppose to take a text file, read the first four names, create a random number between 1-4, and then assign the names to 4 different teams based on what the random number was. For instance, if the number was 3, then the first name would go to team 3, second name to team 4, etc. etc.(repeat process until there are no more names) I believe I have all of the code for that correct, the problem is I can't figure out how to return all the names I have put into the arrays that were brought into the method. Here is my code:
public static void main(String args[]) throws IOException
{
BufferedReader girlFile = new BufferedReader(new FileReader("girls40.txt"));
PrintWriter teamFile = new PrintWriter(new FileWriter("xxxxxxx-teamlist.txt"));
String team1[] = new String[20];
String team2[] = new String[20];
String team3[] = new String[20];
String team4[] = new String[20];
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
}
public static String[] loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile)
{
int n;
int random;
String name1;
String name2;
String name3;
String name4;
while((name1=girlFile.readLine())!=null)
{
name2=girlFile.readLine();
name3=girlFile.readLine();
name4=girlFile.readLine();
random = 1 + (int)(Math.random() * 4);
if(random==1)
{
team1[n]=name1;
team2[n]=name2;
team3[n]=name3;
team4[n]=name4;
}
if(random==2)
{
team1[n]=name4;
team2[n]=name1;
team3[n]=name2;
team4[n]=name3;
}
if(random==3)
{
team1[n]=name3;
team2[n]=name4;
team3[n]=name1;
team4[n]=name2;
}
if(random==4)
{
team1[n]=name2;
team2[n]=name3;
team3[n]=name4;
team4[n]=name1;
}
n++;
}
return team1[],team2[],team3[],team4[];
}`
The main method was given to me, so it cannot be changed.
If there is more code in main method than you've posted here. You'll have to mention what is the variable n and how is it being used else follow the answer.
main Method can't be changed
In your main method,
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
} // End of Main Method
You have not used returned value n for nothing. So it really doesn't matter what you return from method loadTeams() as long as it is an int.
Also, here loadTeams() returns an String[] which can't be assigned be int n, you'll have to change return type of loadTeams() to int as
public static int loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile) {
/*
...
*/
return 0; // whatever, it isn't being used
}
This the solution if you can't change the main method.
The call to loadTeams() expects a return value of type int. Not an array or multiple arrays. If you can't change the main method then loadTeams should return an integer.
// ...
int n;
n = loadTeams(team1,team2,team3,team4,girlFile);
// ...
you don't have to return anything, arrays created in main() will be passed to your method by reference, you can fill them there, and after execution of your method, values will be kept in these arrays
The loadTeams should return an int and not String[].
There is no need to return arrays. Changes made in the arrays in the loadTeams methods will be reflected back to the array in main method.

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

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