Jump to content

Scanner - Java


Hercles
 Share

Go to solution Solved by alexandre1985,

Recommended Posts

na verdade o que eu quero e fazer, é o código abaixo, receber um numero tipo: 999 e saber se ele é Palíndromo (Palíndromo, quando visto de trás pra frente tem o mesmo valor => 123321 ... 121121.. 2222

public class Palindromo {

public static void main(String[] args) {

	Scanner n1 = new Scanner(System.in);
	String b = n1.nextLine();
	int n2 = n1.nextInt();
	int n = b.length();
	char vet[] = new char[n];
	int i;
	for (i = 0; i < n; i++) {
		vet[i] = args[0].charAt(i);
	}

	if (testa(vet)) {
		System.err.println("É Palindromo");
	} else {
		System.err.println("Não é Palodromio");
	}

}

public static boolean testa(char[] vet) {
	int i, n = vet.length;
	for (i = 0; i < n / 2; i++) {
		if (vet[i] != vet[n - 1 - i]) {
			return false;
		}
	}
	return true;
}
}

o método testa(char[] vet) funciona o que não estou conseguindo é fazer entrar os dados pelo método main (usando a classe scanner).

Edited by Hercles
Link to comment
Share on other sites

Faz assim

public class Palindromo {

public static void main(String[] args) {

	if (testa(arg[0])) {
		System.err.println("É Palindromo");
	} else {
		System.err.println("Não é Palodromio");
	}

}

public static boolean testa(String vet) {
	int n = vet.length();
	for (int i = 0; i < n / 2; i++) {
		if (vet.charAt(i) != vet.charAt(n - 1 - i)) {
			return false;
		}
	}
	return true;
}
}

E depois na linha de comandos fazes:

java -jar prog.jar 9999
Edited by alexandre1985
Link to comment
Share on other sites

  • Solution

entao nao precisas de usar o args[0] para nada.

Com scanner faz assim:

public class Palindromo {

public static void main(String[] args) {

	Scanner n1 = new Scanner(System.in);
	String b = n1.nextLine();
	if (testa(b)) {
		System.err.println("É Palindromo");
	} else {
		System.err.println("Não é Palodromio");
	}
}

public static boolean testa(String vet) {
	int i, n = vet.length();
	for (i = 0; i < n / 2; i++) {
		if (vet.charAt(i) != vet.charAt(n - 1 - i)) {
			return false;
		}
	}
	return true;
}
}
Edited by alexandre1985
  • Vote 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.