Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
¿Cómo puedo usar una cadena de entrada de usuario de un método en otro?

Este punto de este programa es limitar la longitud de caracteres de un nombre de usuario a 20 caracteres. Es una parte de un programa más grande que actualmente solo contiene un método principal. Con el fin de limpiar y aclarar mi código, me gustaría separar las distintas funciones en distintos métodos.

Actualmente, estoy tratando de establecer variables de clase para que puedan usarse en múltiples métodos. Esto es lo que tengo hasta ahora:

 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); } }

Intenté configurar uno o ambos métodos en estático, lo que no resolvió el problema. En este estado, cuando se ejecuta, el programa no devolverá un error sino que dará "sin salida".

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

¡ El método principal tiene que ser estático ! Es la entrada a tu programa y su firma tiene que ser así.

Para llamar al método no estático dentro de él, debe crear una instancia de un objeto y llamarlo en ese objeto. En tu caso algo como

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

0

Primero: el método principal debe ser siempre estático .

Segundo: debido a que está llamando a domainChatLimit() desde Main(static) , entonces también debería ser estático

Tercero: debido a que usó los atributos firstName , lastName en un método estático domainChatLimit() , entonces también deberían ser estáticos

Cuarto: el Scanner también debe ser estático porque lo está utilizando para obtener firstName , lastName y ambos son estáticos.

NOTA: No es necesario definir una nueva instancia de esta clase para llamar a un método interno

La solución debería ser como la siguiente (probada con éxito):

 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); } }

si desea crear una utilidad genérica para esa funcionalidad, puede hacerlo a continuación:

 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); } }

ahora puedes llamar de esta manera:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!