About a sentence that contains if statements in an array of for statements

Asked 2 years ago, Updated 2 years ago, 102 views

Thank you for browsing.
I am currently learning java by myself and am a beginner in programming.

I would like to enter a number from the keyboard and write a code that says "Answer!" if the number matches any of the numbers in the array, and if it doesn't match, I don't know how to write it, so I asked you.

public class Aaaa{

    public static void main(String[]args) {
        // TODO AUTOMATICALLY GENERATED METHOD STUB
        int[] numbers = {3,4,9};

        System.out.println("Please enter a single line of digits");
        int input = new java.util.Scanner(System.in).nextInt();


        for (inta:number) {
            if(a==input){
                System.out.println("Attack!");
            }   
            if(a!=input){
                System.out.println("missing");
            }
        }

    }
}

This is the code I wrote, but if you type "9",

Missing
Missing
Oh my gosh!

will be displayed as .
How can I improve it so that it can only be displayed as a hit?

I think it's a basic question, but I'd appreciate it if someone could tell me.
Thank you for your cooperation.

java array

2022-09-29 22:09

2 Answers

Solution

numbers should print "miss" only after you know it is not equal to all elements contained in it.

experiment

Experiment with specific values to see how the program works.

For example, suppose the number entered was 9.This is included in {3,4,9}, so the expected output is "Attack!"

Look at the program's for statement in the question statement.

 for (inta:number) {
    if(a==input){
        System.out.println("Attack!");
    }   
    if(a!=input){
        System.out.println("missing");
    }
}

This for tries the array numbers, or {3,4,9} first to see if it equals 9.

Now, since {3,4,9} starts with 3, a is first substituted with 3 to make sure that the first if statement is a==input, and 9 are not executed equal to .

The second if statement then verifies that it is a!=input.Because this is true, the contents of the if statement are executed and the output is "missed."...Oh, it's different from what I expected :-(

Also, it returns to the beginning of the for statement and a is substituted with 4 to print ズmissing 」.Finally, a is substituted with 9, and this time a==input, so "Attack!" is printed.

So overall, the actual output is

missing
failure
Oh my gosh!

and three lines of output.

Cause

The reason for this is that the number output of before is for all contents of the array.In the current program, based on the comparison of only one element, we have repeatedly printed "hit!" and "miss."

Resolution

Therefore, only after you know that numbers does not equal all the elements contained in it should you print "miss".

For example, before you turn the for statement, prepare a boolean variable indicating whether it was a hit or not and initialize it with false.Also, if you only play with this variable in the for statement and print "Answer!" or "Failure" only once based on true/false after the for statement, you will find the action.

I will hide the sample code below (shown by holding the mouse cursor up), so please refer to it if necessary.

boolean flag=false;
for (inta:number) {
    if(a==input){
        flag = true;
        break;
    }
}
if(flag){
    System.out.println("Attack!");
} else {
    System.out.println("missing";
}


2022-09-29 22:09

Organizing Algorithms

If the int-type array numbers contain the int-type value input, a hit is displayed, and if not, a failure is outputted.There are several ways in which procedures can be described to meet this requirement
(To save space, please read {} that is not java-like.)

Program 1

Program 1 is a method of writing down the above algorithm directly, and it is probably fast.
The following method uses break, and it is efficient because it leaves for as soon as it finds a hit.
This direct writing of algorithms can be described as instructional programming.

class Aaa{
    public static void main(String[]args) {
        int[] numbers = {3,4,9};
        int input = new java.util.Scanner(System.in).nextInt();
        for (inti=0; i<numbers.length;i++) {
            if(number[i]==input){System.out.println("Attack!");break;}
            if(i==number.length-1) {System.out.println("Failed!");}
}}}

The above algorithm does not use the extended for statement, or for (inta: numbers).
Why? Because the processing needs to be branched in the last element of the array.
(It is necessary to state that there was no hit)
An extended for statement does not work if it is necessary to state that only certain elements change the process.
For your reference, I will list the following URL.(The technique is to use the concept of an iterator to change the processing of only the last element, but I think it is better to write a for sentence honestly.)
https://hacknote.jp/archives/20420/

Program 2

Program 1 works fast, but it's very disturbing.Is the index specification incorrect or is there a bug?
We'd like to write a more predictable and bug-free program.
Actually, it would be nice to have what Python and SQL call in operators, but java doesn't have them.

Arrays.asList(number).contains(input)

Actually, it would be nice to be able to make the decision as above, but java doesn't cast int-type arrays (or, to be exact, primitive-type arrays) well on the list.(List of length 1 with the above array as an element, so this description does not yield the expected results.)
Write another URL for your reference.
https://stackoverflow.com/questions/1128723/how-can-i-test-if-an-array-contains-a-certain-value
This question and answer is very high, but in summary,

class Aaa{
    public static void main(String[]args) {
        int[] numbers = {3,4,9};
        int input = new java.util.Scanner(System.in).nextInt();
        if(java.util.stream.IntStream.of(number).anyMatch(a->a==input)) 
            {System.out.println("Attack");}
        else
            {System.out.println("missing");}
}

It suggests that it is a good idea to describe thatEspecially important is the if statement.
First, the int-type array numbers are cast into the int-type stream.You can imagine that a stream is like extracting elements one by one from your head, such as an array.
A->a==input is what we call the lambda expression, which is just a short description of a function in which the input is a bool-type number with a output a==input.You can imagine that the specific values of a are three, four, and nine.
In the lambda expression (function), a stream of inputs 3, 4, 9 is replaced with a stream of false, false, and true.
The anyMatch function replaces False, False, and True flows with True.
AnyMatch, for example, is a function that breaks the calculation and returns True when it first finds out that it is true, so the efficiency is not so bad.
A writing style like Program 2 is sometimes called a declarative program.The programmer does not specify the details of the algorithm (index, branch, etc.) and simply says "hit" if any of the numbers have input and ==, or "miss" if not.

Which one is better

Basically, a writing method such as program 2 is recommended.Because the stream API can describe a program with high versatility briefly and avoid specifying fine branches.But it's also important to know statements like Program 1.


2022-09-29 22:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.