Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

207
Visualizações
How can I use a user input String from one method in another?

This point of this program is to limit the character length of a username to 20 characters. It is one part of a larger program which currently only contains a Main method. In the interest of cleaning and clarifying my code, I would like to separate the various functions into distinct methods.

Currently, I'm trying to set class variables so that they can be used in multiple methods. This is what I have so far:


public class Program
{
    Scanner read = new Scanner(System.in);
    String firstName = read.nextLine();
    String lastName = read.nextLine();
    
    public void main(String[] args) {
        domainCharLimit();
    }
    
    public void domainCharLimit() {
        String firstNameNew = firstName.replace("'", "");
        String lastNameNew = lastName.replace("'", "");
        String domainUsername = firstNameNew + "." + lastNameNew;
        if (domainUsername.length()>20) {
                String cutName = domainUsername.substring(0, 20);
                domainUsername = cutName;
            }
        System.out.print(domainUsername);
    }    
}

I have tried setting one or both methods to static, which did not resolve the issue. In this state, when run, the program will not return an errors but rather give "no output"

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Main method has to be static! It is entry to your program and its signature has to be like that.

In order to call non static method inside it you need to instantiate an object and call it on that object. In your case something like

public static void main(String[] args) {
   Program p =  new Program();
   p.domainCharLimit();
}
over 4 years ago · Santiago Trujillo Relatório

0

First: Main Method should be always static.

Second: Because you are calling domainChatLimit() from Main(static) than it should be also static

Third: Because you used firstName, lastName attributes in a static method domainChatLimit() then they should be also static

Fourth: Scanner should be also static because you are using it to get firstName, lastName and they are both static.

NOTE: There is no need to define a new instance of this class to call an internal method

Solution should be like below (tested successfully):

import java.util.Scanner;

public class Program{

        // variables below should be defined as static because they are used in static method
       static Scanner read = new Scanner(System.in);
       static String firstName = read.nextLine();
       static String lastName = read.nextLine();
        
       // Main method is static
        public static void main(String[] args) {
            //There is no need to define a new instance of this class to call an internal method
            domainCharLimit();
        }
        
        // calling from main static method so it should be static
        public static void domainCharLimit() {
            String firstNameNew = firstName.replace("'", "");
            String lastNameNew = lastName.replace("'", "");
            String domainUsername = firstNameNew + "." + lastNameNew;
            if (domainUsername.length()>20) {
                    String cutName = domainUsername.substring(0, 20);
                    domainUsername = cutName;
                }
            System.out.print(domainUsername);
        }   
}

if you want to create a Generic Util for that functionality you can do below logic:

PogramUtil.java

import java.util.Scanner;

public class ProgramUtil {

    Scanner read = new Scanner(System.in);
    String firstName = read.nextLine();
    String lastName = read.nextLine();
    
    
    public void domainCharLimit() {
        String firstNameNew = firstName.replace("'", "");
        String lastNameNew = lastName.replace("'", "");
        String domainUsername = firstNameNew + "." + lastNameNew;
        if (domainUsername.length()>20) {
                String cutName = domainUsername.substring(0, 20);
                domainUsername = cutName;
            }
        System.out.print(domainUsername);
    }  
}

now you can call this way :

Program.java

public class Program{

       // Main method is static
        public static void main(String[] args) {
            ProgramUtil programUtil = new ProgramUtil();
            programUtil.domainCharLimit();
        }
 
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda