Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a scanner as a global variable [duplicate]

Tags:

java

Method at the top, is it declared as a global variable as its not actually taking in anything.

 public class java_1 {

   static Scanner stdin = new Scanner(System.in);

import java.util.Scanner;

Thats the code used to declare it, if you can declare it another way could i get a link to the documentation.

public class java_1 {

   static Scanner stdin = new Scanner(System.in);

   static String getLastName (String Name){
       String lastName;
       int spacePos,length;

       spacePos = fullName.indexOf("");
       length = fullName.length();
       lastName = fullName.substring(spacePos + 1);
       return lastName;
   }


   static String getInitial (String fullName){
       String initial;
       initial = fullName.substring(0,1); 
       return initial;

   }
    static String =Name (){

       String fullName;
       String userName;
       String initial;
       String lastName;

          System.out.println("name");
          fullName = stdin.nextLine();

          initial = getInitial(fullName);
          lastName = getLastName(fullName);

          userName = initial + lastName;

          System.out.println(userName);
          return userName;
      }

static String printuserName (){

       String fullName,userName,initial,lastName;

          System.out.println("enter name");
          fullName = stdin.nextLine();

          initial = getInitial(fullName);

          userName = initial + lastName;

          System.out.println("username: " + userName);
          return userName;
      }


   static int menu(){

          int choice;
            System.out.println("Input a number from the table, corresponding to the task required");
            System.out.println("1 = User name");
            System.out.println("2 = Factor");
            System.out.println("3 = Quit");

            choice = stdin.nextInt();

            while (choice != 1){
                System.out.println("Re enter");
                choice = stdin.nextInt();
        }
            return choice;
   }




      }
     }
    }
like image 241
user2860471 Avatar asked Aug 27 '26 23:08

user2860471


1 Answers

The problem is that when you read the menu option with stdin.nextInt(), there is still a newline character waiting in the scanner. When you call stdin.nextLine() some time later, you get the rest of the line - which is just an empty string. The name itself won't be read until the FOLLOWING call to nextLine().

To remedy this, you should call nextLine() immediately after your call to nextInt() in the Menu() method, just to clear out that extra newline character.

like image 148
Dawood ibn Kareem Avatar answered Aug 30 '26 13:08

Dawood ibn Kareem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!