ClassCastException: java.lang.String cannot be added to Ljava.lang.String

I get this error->

java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.String; 

From the code inserted below.

 public class LoginAttemps extends Setup { public void testSearchCountry() throws Exception { driver.get("http://www.wikipedia.org/wiki/Main_Page"); ReadExcelDemo readXls = new ReadExcelDemo(); List dataList = readXls.getData(); for (int i = 1; i < dataList.size(); i++) { String[] testCase = new String[5]; String[] test = (String[]) dataList.get(i); String countryName = test[0]; String countryDesc = test[1]; driver.findElement(By.id("searchInput")).clear(); driver.findElement(By.id("searchInput")).sendKeys(countryName); driver.findElement(By.id("searchButton")).click(); String str = driver.findElement( By.xpath("//h1[@id='firstHeading']/span")).getText(); System.out.println(countryDesc); Assert.assertTrue(str.contains(countryName)); } } } 

I think the problem is with String[] test = (String[]) dataList.get(i);

But I'm not sure if this exception will be resolved .. Any clues?

+6
source share
4 answers

You cannot include "String" in "Array of Strings".

You can only put a string in a slot inside the array.

What can you do:

  String theString = "whatever"; String[] myStrings = { theString }; 
+9
source

Looking at the code, I find that you are trying to convert the List into an array , so your line "problem" should be as follows:

 String[] test = (String[]) dataList.toArray(new String[dataList.size]); 
+1
source

Reason: the item at position "i" has a type string. However, you are trying to pass it to an array of strings.

Direct solution: remove [] on both sides, i.e. change from:

 String[] test = (String[]) dataList.get(i); 

To:

 String test = (String) dataList.get(i); 

This will work if your list does not contain an array of any type.

0
source

Thanks guys. Yes, I am trying to use List objects in String Arrays. I found a problem. The corrected code.

  public void testSearchCountry() throws Exception { driver.get("http://www.wikipedia.org/wiki/Main_Page"); ReadExcelDemo readXls = new ReadExcelDemo(); List dataList = readXls.getData(); String[] test = new String[dataList.size()]; for (int i = 1; i < dataList.size(); i++) { String[] testCase = new String[5]; test[i] = dataList.get(i).toString(); String countryName = test[0]; String countryDesc = test[1]; driver.findElement(By.id("searchInput")).clear(); driver.findElement(By.id("searchInput")).sendKeys(countryName); driver.findElement(By.id("searchButton")).click(); String str = driver.findElement( By.xpath("//h1[@id='firstHeading']/span")).getText(); System.out.println(countryDesc); Assert.assertTrue(str.contains(countryName)); } } 

and it worked.

0
source

Source: https://habr.com/ru/post/984181/


All Articles