Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I convert Scanner Class into String?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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"));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading