How can I convert Scanner Class into String?

Advertisements
import java.util.Scanner;
public class Cond { 
    static ScannerClass usrID, pwdd;
    static String pass = "123456";
    static String usr = "ABCD";
    public static void main(String[] args) {
       
        System.out.println("Enter UserID: ");
        usrID = new ScannerClass();
        
        usrID.main();
        String o = usrID.toString();
        System.out.println("Enter password: ");
        pwdd = new ScannerClass();
        pwdd.main1();
        String t = pwdd.toString();

        
        if ((usr.equals(o)) && (pass.equals(t))) {
            System.out.println("You are logged in!");
        }
        else {
            System.out.println(("Please enter correct credentials"));
        }
    }
}

I made a seperate class which is :

import java.util.Scanner;


public class ScannerClass {
    static Scanner sc = new Scanner(System.in);
    public  void main(){
        
        String UserID = sc.nextLine();
    }
    public void main1(){
        String pwd = sc.nextLine();
    }
}

The code is not reunning as I expected . this is the problem:


Enter UserID:
ABCD
Enter password:
123456
Please enter correct credentials


I tried to convert the Scanner class using toString() I found this on internt but it is not working as you can see in the above results.

>Solution :

The method main inside ScannerClass reads from the user, creates a local variable with its contents and discard the variable. The first change inside your method is to return the local variable so you can access it in other places:

public class ScannerClass {
    static Scanner sc = new Scanner(System.in);

    public String getUserId(){
        String UserID = sc.nextLine();
        return UserID;
    }

    public void getPassword(){
        String pwd = sc.nextLine();
        return pwd;
    }
}

Then, in your Cond main method, you can do

ScannerClass scanner = new ScannerClass();
        
System.out.println("Enter UserID: ");
String usrID = scanner.getUserId();

System.out.println("Enter password: ");
String pwd = scanner.getPassword();

if ((usr.equals(usrID)) && (pass.equals(pwd))) {
    System.out.println("You are logged in!");
} else {
    System.out.println(("Please enter correct credentials"));
}

Leave a ReplyCancel reply