I've done everything but i just don't know why it is not even accepting it...this is my code i think that it doesnt have nothing to do with it but ill send it anyways. Any help is appreciated!
public class Exercicio2 {
public static String mcaracteres(String[] array) {
int maxLength = 0;
String maiscaracteres = null;
for (String s : array) {
if (s.length() > maxLength) {
maxLength = s.length();
maiscaracteres = s;
}
}
return maiscaracteres;
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String[] array = new String[10];
System.out.println("Insira 10 linhas");
for (int i = 0; i < array.length; i ) {
array[i] = scn.nextLine();
if (array[i].equals("")) break;
}
int choice = 0;
while (choice != 6) {
System.out.println(".......................MENU........................");
System.out.print("Opcao: ");
choice = scn.nextInt();
System.out.println();
if (choice > 6 || choice < 0) {
System.out.println("Escolha invalida.Tente uma opcao entre 1 e 6");
}
if (choice == 1) {
; String maiscaracteres = mcaracteres(array);
System.out.format("Linha com mais caracteres: '%s'\n", maiscaracteres);
}
else if (choice == 4) {
System.out.println("Insira a linha que deseja verificar");
Scanner sc = new Scanner(System.in);
String verify = sc.next();
if (array.contains(verify))
System.out.println(verify " já existe.");
else {
System.out.println("A linha ainda nao existe");
}
}
}
}
}
I'm sorry if this is a dumb question but i'm new to java and i'm trying to figure it out little by little
CodePudding user response:
Your example code has two main flaws and will not compile:
- it does not
import java.util.Scanner;
on top array
is - as the name correctly says - an array. Arrays don't have the methodcontains
, maybe you wanted to use anjava.util.ArrayList
instead?
But for the second flaw there is also a "cheap" solution, you can convert the array to a list just for the call of the contains
. No good performance, don't do this for real software, but for your example it could work:
if (Arrays.asList(array).contains(verify))
You have to add another import to use Arrays
: import java.util.Arrays;
CodePudding user response:
I believe the problem is not an import. You are calling contains() on an array and not on a list. Please replace
array.contains(verify)
with
Arrays.asList(array).contains(verify)
and you should be ok