Comparing an array to two static values - java

So I am just doing something simple. I made a simple Java program where you enter your guess for what the roll will be which is stored in an array and then compared to two numbers generated randomly. So my question is how would I do the comparison of the array against the two number without referencing the exact index (i.e. not array[0]=number[1])? I am doing this mostly to figure out how array work. Also why is the else erroring?
public static void main (String [] args){
java.util.Scanner input = new java.util.Scanner(System.in);
int [] guess= new int [2];
System.out.print("Enter " + guess.length + " values: ");
for (int i=0; i<guess.length;i++)
guess[i] = input.nextInt();
method(guess);
}
public static String method(int [] that){
int number1 = (int)(Math.random() * 6);
int number2 = (int)(Math.random() * 6);
for (int i =0;i<that.length;i++){
if(that[i]==number1 and that[i]+1==number2)
{
return "You got it";
}
else
{
return "try again";
}//end else
} //end for
}//end method

You cannot write and like that , if you want to AND two conditions write &&. Also in your if condition I think you mean to increment your index that[i+1]==number2 , you were incrementing the random number itself. So your if condition would look like:-
if(that[i]==number1 && that[i+1]==number2)
{
return "You got it";
}
else{
..
}
Also want to add that you output You got it or try again will not be visible to user, since you are just calling the method method(guess); from main() which returns a String but does not do anything with returned String. You have to write it like this to make the ouput visible on console.
System.out.println(method(guess));

You can check whether the array contains the element or not like this
Arrays.asList(that).contains(number1)
It will return true if the array contains the element else as false

if you want comparison of the array against the two number without referencing the exact index then the first thing that you can do is use enhance for loop to avoid indexing of array like this
for(int number: that){
// do your comparison while iterating numbers in that(array) as "number"
}

Related

how to print Scanner element using parallel arrays in java?

I am new to learning about parallel arrays and want to know how to effectively print content/elements using parallel array only, I tried but couldn't get it to work and function the way I want.
The task is: The program inputs an integer from the user representing how many peoples’ information will be entered. Then, the program inputs the information one person at a time (name first, then age), storing this information in two related arrays.
Next, the program inputs an integer representing the person on the list whose information should be displayed (to get information for the first person, the user would enter ‘1’). The program makes a statement about the person’s name and age.
Although I got the name and age to work until the integer the user inputs, but after that I am not sure how to do
Sample input:
4
Vince
5
Alexina
8
Ahmed
4
Jorge
2
2 // I am confused about this part, how would I make it so that it prints the desired name,
//for example with this input, it should print:
Sample output:
Alexina is 8 years old
My code:
import java.util.Scanner;
class Example {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[keyboard.nextInt()];
for (int x = 0; x < num.length; x++){
String[] name = {keyboard.next()};
int[] age = {keyboard.nextInt()};
}
int num2 = keyboard.nextInt();
System.out.println(); // what would I say here?
}
}
You need to rewrite your code so your arrays aren't being assigned within the loop. You want to add values to the arrays, not reset them each time, and you want to be able to access them afterwards. Below is a modified version of your code:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
keyboard.nextLine(); //you also need to consume the newline character(s)
String[] name = new String[num]; //declare the arrays outside the loop
int[] age = new int[num];
for (int x = 0; x < num; x++){
name[x] = keyboard.nextLine(); //add a value instead of resetting the array
age[x] = keyboard.nextInt();
keyboard.nextLine(); //again, consume the newline character(s) every time you call nextInt()
}
int num2 = keyboard.nextInt() - 1; //subtract one (array indices start at 0)
System.out.println(name[num2] + " is " + age[num2] + " years old"); //construct your string with your now-visible arrays
}
As I think you have to think about the local and global variable usage in java.In brief,
Local variables can only use within the method or block, Local variable is available only to method or block in which it is declared.
For example:
{
int y[]=new Int[4];
}
this y array can be accessed within the block only.
Global Variable has to be declared anywhere in the class body but not inside any method or block. If a variable is declared as global, it can be used anywhere in the class.
In your code you try to create arrays and use them out of the For loop. But your arrays are valid only inside the For loop. After every loop runs all info is lost.there will be new array creation for every iteration of For loop.
therefore, In order to access and save the information you have to declare your arrays before the For loop and access and store data using iteration number as the index. finally, to print the data you gathered, you have to scan new input as integer variable.then you can access your arrays as you wanted.
//For example
int [] age=new int[4]; //global -Can access inside or outside the For loop
int[] numbers = new int[keyboard.nextInt()];
for (int x = 0; x < 4; x++){
age[x] = keyboard.nextInt(); //Local
}
int num2 = keyboard.nextInt();
System.out.println(age[num2]); // Here you have to access global arrays using num2 num2
}
}

How to use a method to return a double array of user input values?

I want to create a method that returns a double array of user input values. I've figured out how to create a method to ask the user to pick how many elements an array should hold, then pass off the size to next method, which is to spit out a double array of user's input values.
My goal here is to practice learning how to use basic methods (just public static methods) to divide and conquer the problem at hand.
...java
package array_exercises;
import java.util.Scanner;
public class Array_Exercises {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Get number of elements to store values from the user
int number = numOfElements();
System.out.println(valueOfElements(number));
}
public static int numOfElements () {
// Create a Scanner object to get the user's input
Scanner input = new Scanner (System.in);
// Get the input from the user
System.out.print("Enter how many number of the type double do you want"
+ " to store in your array? ");
return input.nextInt();
}
public static double[] valueOfElements (int num) {
// Create a Scanner object to get the user's value for each element
Scanner input = new Scanner (System.in);
// Declare an array of doubles
double[] double_array = new double[num];
// Loop through the elements of double array
for (int i = 0; i < double_array.length; i++) {
System.out.print("Enter a value #" + (i + 1) + ": ");
double_array[i] = input.nextDouble();
}
return double_array;
}
}
The expected output should print out all values of the double array in the main method.
All I got was this:
run:
Enter how many number of the type double do you want to store in your array? 2
Enter a value #1: 1.234567
Enter a value #2: 2.345678
[D#55f96302
Why is this? What am I doing wrong here? I'm only a beginner, I'm taking a class on Java this semester, so everything is new to me.
An array is an object in java and therefore it is printed by calling its toString() method. This method is not very helpful for the array class and doesn't print the arrays contents. To print the array content you can call Arrays.toString(yourArray) which will return a string representation of the array contents.
You should replace
System.out.println(valueOfElements(number));
with
System.out.println(Arrays.toString(valueOfElements(number)));
and add the following import statement:
import java.util.Arrays;
First you have to understand that in java an array variable is a reference. This means that when you try an print out an array variable, it prints out a memory address, not elements of the array. The way to fix your issue is to save the return value of the function into the array, and then for loop through every element in the array.
double[] values = valueOfElements(number);
for(int i = 0; i < values.length; i++){
System.out.println(values[i]);
}
The [] dereferences the double, so you are accessing the double value, and not the memory address value.

Finding if given Integer is in Array or not using Arraylist contains ()

Having problem to check if the given input is in Array or not. Below is just the sample code I wrote. For some reason no matter what I input it outputs "not Okay" even if the number is in array. Any Suggestion or help will be appreciated.
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int array [] = new int[10];
System.out.println("Please enter the 10 positive integers for BST:");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
System.out.println("Enter node to delete");
if (Arrays.asList(array).contains(input.nextInt())){
System.out.println("ok");
} else
System.out.println("not Okay");
}
Arrays.asList(array) will convert the int[] array into a List<int[]>, then List<int[]>#contains will try to search an Integer. As noted, it will never find it.
Ways to solve this:
Change int[] to Integer[].
Create a method that receives an int and search the element in the array.
(Code won't be shown in the answer since the question looks like a homework exercise).
You can use Arrays.binarySearch(). It returns the index of the key, if it is contained in the array; otherwise, (-(insertion point) - 1). You must use sort() method before:
Arrays.sort(array);
if (Arrays.binarySearch(array, input.nextInt()>=0)

Add two strings containing binary numbers

I'm teaching myself how to code with java and I use exercises I find in the Internet to practice what I learn.
Anyway, I'm in a middle of an exercise that asks me to build a method that get two strings containing only the characters "0" and "1" from the user and returns one string of them both (binary)combined
example:
BinaryAdder("0","0") - > "0"
BinaryAdder("1","1") - > "10"
BinaryAdder("10100","111") - > "11011"
what I did is:
import java.util.Scanner;
public class assigment03
{
private static String whichIsBigger(String a, String b)
{
if(a.length()>b.length())
return a;
if(a.length()<b.length())
return b;
if(a.length()==b.length())
return a;
else return null;
}
private static String binaryAdder(String a,String b)
{
int[] binaryResult= new int[maxlength(a,b)+1];
String result="";
if(whichIsBigger(a,b)==a)
{
for(int i=0;i<b.length();i++)
{
binaryResult[i]=a.charAt(i)+b.charAt(i);
}
for(int i=b.length();i<a.length();i++)
{
binaryResult[i]+=a.charAt(i);
}
}
else
{
for(int i=0;i<a.length();i++)
{
binaryResult[i]=b.charAt(i)+a.charAt(i);
}
for(int i=a.length();i<b.length();i++)
{
binaryResult[i]+=b.charAt(i);
}
}
for(int i=0;i<binaryResult.length-1;i++)
{
if(binaryResult[i]>=2)
{
binaryResult[i]=binaryResult[i]%2;
binaryResult[i+1]++;
}
}
for(int i=binaryResult.length-1;i>=0;i--)
{
result+=Integer.toString(binaryResult[i]);
}
return result;
}
private static int maxlength(String a, String b)
{
if(a.length()>b.length())
return a.length();
else
return b.length();
}
public static void main(String[] args)
{
Scanner temp= new Scanner(System.in);
System.out.print(binaryAdder(temp.next(),temp.next()));
}
}
But it doesn't return the right result.
Do you mind help me out here?
thanks a lot!
Reading your question, I understood that you might be looking for some help implementing the methods to actually add two binary numbers, and then giving back the result in base two (which btw might be complicated in Java). However, I believe that this exercise lacks of a very important restriction like the what is max length allowed for the binary numbers to be read (overflows can arise while processing the values with primitive data types like int or String). Also this exercise needs some planning when dealing with none significant zeroes like in these cases because "00110b" = "0110b" = "0110b" and when dealing with rolling over the carry of any addition that yields 2 ("10b") or 3 ("11b"). More information on those topics can be found here, in chapter 2.
At least in Java, when tackling these type of exercises, an option is to avoid dealing with such restrictions and conditions. Java provides a class called BigInteger that takes care of huge values, none significant zeroes, and the carries taking away the burden of dealing with those things from the programmers. Java BigInteger also offers a constructor that can initialize their objects in any base. (Well not any, there are some restrictions to this too, please see this link for more information).
With that said, here is my solution to this exercise:
import java.util.Scanner;
import java.util.ArrayList;
import java.math.BigInteger;
public class BinaryAdder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> numbers = new ArrayList<String>();
String number = "";
int count = 1;
System.out.print("Instructions:\nPlease enter a set of binary numbers. When you are ready to calculate their addition, enter \"done\",\n\n");
System.out.print("Number " + count + ": ");
while(!(number = scanner.next()).equals("done")){
numbers.add(number);
count++;
System.out.print("Number " + count + ": ");
}
System.out.print("Result = " + binaryAdder(numbers) + "b");
scanner.close();
}
public static String binaryAdder(ArrayList<String> numbers){
BigInteger accumulator = new BigInteger("0");
for(String number: numbers){
accumulator = accumulator.add(new BigInteger(number, 2));
}
return accumulator.toString(2);
}
}
Example:
Instructions: Please enter a set of binary numbers. When you are ready
to calculate their addition, enter "done",
Number 1: 00001
Number 2: 011
Number 3: done
Result = 100b
Between lines 8-11 some variables are declared: a scanner to read the binary numbers entered, an array list to store the binary numbers entered, a string to hold a number once is entered, and a int to keep track of how many numbers have been entered, since I extended this solution to add 0,1,2,3,...,n numbers).
Line 13 prints the instructions of this solution. Line 14 only prints "Number 1: ".
The while loop between lines 16-20 sets the value entered to the variable number and checks if it is equal to "done". Given the case it steps out of the loop, otherwise, it adds the number to the array list.
Line 22 prints the result of the addition of all the binary numbers entered.
But the "magic" really happens between lines 27-35 in the method "binaryAdder" (Note that "binaryAdder" receives that ArrayList holding all the numbers entered as a parameter). At line 28 an accumulator of type BigInteger is initialized to zero to hold the addition of all the numbers in the ArrayList. Then, a for loop travels through all the numbers in the array list to add them to the accumulator. Finally, the accumulated value is returned in base two.

How to make it so only ints from the array can be chosen? Also how to find biggest integer from integers chosen?

I am making a program that prompts the user for 3 integers and prints out the biggest one chosen. I am stuck with 2 problems at the moment. I would like to know how I can make the program so that the user can only choose integers from the array. I would also like to know how to find and print out the biggest integer from the ones that the user chose. I'm quite new to programming so all feedback is appreciated.
Thanks!
import java.util.Scanner;
public class Lab14C // name of class file
{
public static void main(String [] args)
{
int[] array = {0,1,2,3,4,5,6,7,8,9};
for(int i=0; i<array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println("\n");
Scanner array1 = new Scanner(System.in);
System.out.println("What is your first integer? ");
double array11 = array1.nextInt();
Scanner array2 = new Scanner(System.in);
System.out.println("What is your second integer? ");
double array22 = array2.nextInt();
Scanner array3 = new Scanner(System.in);
System.out.println("What is your third integer? ");
double array33 = array3.nextInt();
System.out.println("\n");
}
}
I don't think there is a way to force a user to input an element. Few things you could do is :
Tell the user he has to select a number in a particular range.
Keep the input statement in a loop. If the entered element exists in array , go ahead. Else tell the user to enter again.
Printing the biggest integer can be done using Math.max(double,double) function. For three elements you can try System.out.println("Max of three is "+Math.max(array11,Math.max(array22,array33)))
You can do it yourself if you want instead of built in function like:
if(array1>array2&&array1>array3)
//print max as array1
else if(array2>array1&&array2>array3)
//print max as array2
else //print array3 as max
Also change your element types to int as you are reading integer.
1) There is no need to create a new Scanner all the time.
Just create one Scanner (which I would just call input or scanner or something that makes sense).
2) If you're reading int's why are you storing them in doubles?
3) To check for a certain condition you use if(*condition*) { /*do something */ }. So if you want to check if x is smaller than y you do if(x < y) { /* do something */ }. (In your case you'll want to check if current input is greater than biggest input and if so set the biggest input to current input.)
4) For a sorted array you can use Arrays.binarySearch(array, elementToSearch) which will return the index of the element when found, or a negative number if not found (the negative number is (-(insertionPoint)-1)). (So you can check if the number entered by the user is in the array and keep asking for a new number if is not.)
1) How I can make the program so that the user can only choose integers from the array.?
You are declaring array variable as int[] so it stores only integer values. Whenever you retrives the value from this array, it returns int value only so you don't have to worry about it.
2)how to find and print out the biggest integer from the ones that the user chose.?
To find the maximum or minimum from a set of values, Java provide a function name Math#max(). You can use it like this :
int maxValue = Math.max(Math.max(array11,array22),array33);
Here is the doc for Math library.

Categories