W
W
WannaCreative2016-06-25 15:47:16
Java
WannaCreative, 2016-06-25 15:47:16

Where is the mistake in Java code?

Can't find an error.
The inscription should be displayed, but it does not work.

package com.examplepackage;

import java.util.Scanner;

public class Main{
    public static void main(String[]args){
        String myPass = new String("supermegalogic");
        System.out.print("Hello! Welcome to admin panel! \n");
        System.out.print("First of all, type down your password \n");
        Scanner scn = new Scanner(System.in);
        String typepass = scn.nextLine();
        if (typepass == myPass){
            System.out.print("YOU HAVE JUST CONNECTED.");
        }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
asurkis, 2016-06-25
@WannaCreative

You cannot test with the "==" operator because it compares references, not the objects themselves. The correct condition would be
More precisely, the "==" operator compares simple types, i.e. byte, short, int, long, float, double, char, as well as references, and for objects you need to use the equals function defined in the java.lang.Object class, from which all other classes are inherited . It is
also worth remembering that wrapper classes over simple types are not simple (that is, objects of type Integer (as well as Byte, Short, Long, Char, Float and Double) are exactly instances of the class that need to be compared for equality using equals) By the way, you can write
insteadnew String("supermegalogic")
Since an explicit constructor call actually creates 2 equivalent objects, and an explicit call slightly worsens the readability of the code

R
Rou1997, 2016-06-25
@Rou1997

Can't find an error.

It was necessary to debug, at least checking each construction by typing, this would make it clear that the problem is in the condition.
And yet, I'll insert "5 kopecks", replace
This no longer affects, but the code is more concise.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question