Error incompatible types string cannot be converted to string

I'm working on Java project - Playing Cards. And, in this Card.java class, I've declared and initialized variables and array list. I've come across this error. These errors are under each getter and

I bet you generated the getters and setters and the constructor for the initial set of fields which are these.

// private String suit;
// private String name;
// private int value;

But after changing them to

private String[] suit = { "spades", "hearts", "clubs", "diamonds" };
private String[] name = { "Ace", "Jack", "Queen", "King" };
private int[] value = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };

you forgot to modify them accordingly. You need to change your getters and setters and constructors to something like this. The same goes with the toString() method.

public class Card {

    private String[] suit = { "spades", "hearts", "clubs", "diamonds" };
    private String[] name = { "Ace", "Jack", "Queen", "King" };
    private int[] value = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };

    public Card(String[] suit, String[] name, int[] value) {
        super();
        this.suit = suit;
        this.name = name;
        this.value = value;
    }

    public String[] getSuit() {
        return suit;
    }

    public void setSuit(String[] suit) {
        this.suit = suit;
    }

    public String[] getName() {
        return name;
    }

    public void setName(String[] name) {
        this.name = name;
    }

    public int[] getValue() {
        return value;
    }

    public void setValue(int[] value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Card [suit=" + Arrays.toString(suit) + ", name="
            + Arrays.toString(name) + ", value=" + Arrays.toString(value)
            + "]";
    }
}

Always remember to generate fresh getters, setters, constructor, toString() methods, if you happen to change the fields in the class.

I tried taking input of a 6 by 6 matrix in java using the string split function when the string is input in the following way, and to print the matrix.

1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6

The output that I get is

Main.java:24: error: incompatible types: String[] cannot be converted to String
                                c[j] = b[i].split(" ");

my code:

import java.util.*;
import java.io.*;

class Solution {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        int a[][] = new int[6][6];
        String b[] = new String[6];

        for (int i = 0; i < 6; i++) {
            b[i] = s.nextLine();
        }

        // initializing the 2d array a[][]
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 6; j++) {
                String c[] = new String[6];
                c[j] = b[i].split(" ");
                a[i][j] = Integer.parseInt(c[j]);
            }
        }

        // printing the input array
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 6; j++) {
                System.out.print("ta[i][j]t");
            }
        }
    }
}

pls, suggest how I can overcome this error

Community's user avatar

asked Aug 10, 2020 at 4:01

Apptrixie's user avatar

1

When we call split function of String return the String[]. So c[j] (which is of type String) can’t be equal to String[].

Below code should be replaced as:

// initializing the 2d array a[][]
for (int i = 0; i < 6; i++) {
    String[] c = b[i].split(" ");
    for (int j = 0; j < 6; j++) {
        a[i][j] = Integer.parseInt(c[j]);
    }
}

Community's user avatar

answered Aug 10, 2020 at 4:17

Gaurav Jeswani's user avatar

Gaurav JeswaniGaurav Jeswani

4,1876 gold badges23 silver badges46 bronze badges

The return type of split() function is type of array. Because you are asking java to give me each value as separate which is separated by " " (space). So java will create an array of each value and returns you the array. For storing the array you need an variable of type array. here c represent an array, but c[j] represents an single index of the array.

You can change your code like:

for (int i = 0; i < 6; i++) {
    String c[] = b[i].split(" ");
    for (int k = 0; k < c.length; k++) {
        a[i][k] = Integer.parseInt(c[k]);
    }
}

The the inputs are integer and you are converting them to integer later, I would suggest you to take input as integer like below:

class Solution {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        int a[][] = new int[6][6];

        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 6; j++) {
                a[i][j] = s.nextInt();
            }
        }

        // printing the input array
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 6; j++) {
                System.out.print("ta[i][j]t");
            }
        }
    }
}

Community's user avatar

answered Aug 10, 2020 at 4:16

Deepak Kumar's user avatar

Deepak KumarDeepak Kumar

1,21813 silver badges36 bronze badges

I’m taking a Java class for college, and was working on some given tasks. This is the code I wrote for it.

public class String
{
 public static void main(String[] args)
 {
  String city = "San Francisco";
  int stringLength = city.length();
  char oneChar = city.charAt(0);
  String upperCity = city.toUpperCase();
  String lowerCity = city.toLowerCase();

  System.out.println(city);
  System.out.println(stringLength);
  System.out.println(oneChar);
  System.out.println(upperCity);
  System.out.println();
  }
 }

which yielded these results

C:UserssamDocumentsJava>javac String.java
String.java:8: error: incompatible types: java.lang.String cannot be 
converted to String
          String city = "San Franciso";
                        ^
String.java:9: error: cannot find symbol
            int stringLength = city.length();
                                   ^
symbol:   method length()
location: variable city of type String
String.java:10: error: cannot find symbol
            char oneChar = city.charAt(0);
                               ^
symbol:   method charAt(int)
location: variable city of type String
String.java:11: error: cannot find symbol
            String upperCity = city.toUpperCase();
                                   ^
symbol:   method toUpperCase()
location: variable city of type String
String.java:12: error: cannot find symbol
            String lowerCity = city.toLowerCase();
                                   ^
symbol:   method toLowerCase()
location: variable city of type String
5 errors

I’ve tried searching for an answer but I didn’t really find anything that helps. Any help is appreciated, thanks.

asked Jan 26, 2018 at 9:19

2

Since your class is named String, unqualified type reference in String city is taken as reference to your own class.

Either rename the class to some other name, or you’ll have to write java.lang.String wherever you reference the «built-in» Java String class.

answered Jan 26, 2018 at 9:21

Jiri Tousek's user avatar

Jiri TousekJiri Tousek

12.1k5 gold badges30 silver badges43 bronze badges

It is conflict between system class java.lang.String and your class named String. Rename your class String to say MyString, i.e. replace line:

public class String

with

public class MyString

And rename file String.java containing this class to MyString.java.

answered Jan 26, 2018 at 9:37

Anton Tupy's user avatar

Anton TupyAnton Tupy

9415 silver badges16 bronze badges

Introduction to Data Types & Type Conversion

Variables are memory containers used to store information. In Java, every variable has a data type and stores a value of that type. Data types, or types for short, are divided into two categories: primitive and non-primitive. There are eight primitive types in Java: byte, short, int, long, float, double, boolean and char. These built-in types describe variables that store single values of a predefined format and size. Non-primitive types, also known as reference types, hold references to objects stored somewhere in memory. The number of reference types is unlimited, as they are user-defined. A few reference types are already baked into the language and include String, as well as wrapper classes for all primitive types, like Integer for int and Boolean for boolean. All reference types are subclasses of java.lang.Object [1].

In programming, it is commonplace to convert certain data types to others in order to allow for the storing, processing, and exchanging of data between different modules, components, libraries, APIs, etc. Java is a statically typed language, and as such has certain rules and constraints in regard to working with types. While it is possible to convert to and from certain types with relative ease, like converting a char to an int and vice versa with type casting [2], it is not very straightforward to convert between other types, such as between certain primitive and reference types, like converting a String to an int, or one user-defined type to another. In fact, many of these cases would be indicative of a logical error and require careful consideration as to what is being converted and how, or whether the conversion is warranted in the first place. Aside from type casting, another common mechanism for performing type conversion is parsing [3], and Java has some predefined methods for performing this operation on built-in types.

double myDouble = 9; // Automatic casting (int to double)
int myInt = (int) 9.87d; // Manual casting (double to int)
boolean myBoolean = Boolean.parseBoolean("True"); // Parsing with a native method (String to boolean)

System.out.println(myDouble);   // 9.0
System.out.println(myInt);      // 9
System.out.println(myBoolean);  // true

Incompatible Types Error: What, Why & How?

The incompatible types error indicates a situation where there is some expression that yields a value of a certain data type different from the one expected. This error implies that the Java compiler is unable to resolve a value assigned to a variable or returned by a method, because its type is incompatible with the one declared on the variable or method in question. Incompatible, in this context, means that the source type is both different from and unconvertible (by means of automatic type casting) to the declared type.

This might seem like a syntax error, but it is a logical error discovered in the semantic phase of compilation. The error message generated by the compiler indicates the line and the position where the type mismatch has occurred and specifies the incompatible types it has detected. This error is a generalization of the method X in class Y cannot be applied to given types and the constructor X in class Y cannot be applied to given types errors discussed in [4].

The incompatible types error most often occurs when manual or explicit conversion between types is required, but it can also happen by accident when using an incorrect API, usually involving the use of an incorrect reference type or the invocation of an incorrect method with an identical or similar name.

Incompatible Types Error Examples

Explicit type casting

Assigning a value of one primitive type to another can happen in one of two directions. Either from a type of a smaller size to one of a larger size (upcasting), or from a larger-sized type to a smaller-sized type (downcasting). In the case of the former, the data will take up more space but will be intact as the larger type can accommodate any value of the smaller type. So the conversion here is done automatically. However, converting from a larger-sized type to a smaller one necessitates explicit casting because some data may be lost in the process.

Fig. 1(a) shows how attempting to assign the values of the two double variables a and b to the int variables x and y results in the incompatible types error at compile-time. Prefixing the variables on the right-hand side of the assignment with the int data type in parenthesis (lines 10 & 11 in Fig. 1(b)) fixes the issue. Note how both variables lost their decimal part as a result of the conversion, but only one kept its original value—this is exactly why the error message reads possible lossy conversion from double to int and why the incompatible types error is raised in this scenario. By capturing this error, the compiler prevents accidental loss of data and forces the programmer to be deliberate about the conversion. The same principle applies to downcasting reference types, although the process is slightly different as polymorphism gets involved [5].

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class IncompatibleTypesCasting {

  public static void main(String... args) {
    double a = 10.5;
    double b = 5.0;
    System.out.println("a: " + a + "tb: " + b);

    int x = a;
    int y = b;
    System.out.println("x: " + x + "ty: " + y);
  }
}
IncompatibleTypesCasting.java:10: error: incompatible types: possible lossy conversion from double to int
    int x = a;
            ^
IncompatibleTypesCasting.java:11: error: incompatible types: possible lossy conversion from double to int
    int y = b;
            ^
2 errors

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class IncompatibleTypesCasting {

  public static void main(String... args) {
    double a = 10.5;
    double b = 5.0;
    System.out.println("a: " + a + "tb: " + b);

    int x = (int) a;
    int y = (int) b;
    System.out.println("x: " + x + "ty: " + y);
  }
}
a: 10.5 b: 5.0
x: 10   y: 5
Figure 1: Incompatible types when downcasting (a) error and (b) resolution

Explicit parsing

Parsing is a more complex process than type casting as it involves analyzing the underlying structure of a given data before converting it into a specific format or type. For instance, programmers often deal with incoming streams of characters, usually contained in a string that needs to be converted into specific types to make use of in the code. A common scenario is extracting numeric values from a string for further processing, which is where parsing is routinely used.

The main method in Fig. 2(a) declares the variable date which holds the current date as a String in the yyyy-MM-dd format. In order to get the year value into a separate variable it is necessary to “parse” the first 4 characters of the string, and this can be accomplished by splitting the string by specifying the “-” character as a delimiter and then accessing the first element (line 9 in Fig. 2(a)). With this, the year value has been successfully parsed and stored into a new variable. Attempting to increase the value of this new variable and store the resulting value in a separate int variable triggers the incompatible types error (line 10 in Fig. 2(a)). This is because even though the year has been isolated from the date and parsed into a new variable, it is impossible to perform arithmetic operations on a variable of type String. Therefore, it is necessary to represent this value as a numeric type. The best way to do this is to use Java’s built-in Integer::parseInt method which takes a String argument and converts it to an int (line 10 in Fig. 2(b)). (Note that if the given argument is not a valid integer value, this method will throw an exception.) Now that the year has been manually and explicitly parsed from the initial date string into an integer value that can be incremented, the program compiles and prints the expected message, as shown in Fig. 2(b).

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.time.LocalDate;

public class IncompatibleTypesParsing {

 public static void main(String... args) {
   String date = LocalDate.now().toString(); // "2021-12-21"
   String year = date.split("-")[0]; // "2021"
   int newYear = year + 1;
   System.out.println("Happy New Year " + newYear + "!");
 }
}
IncompatibleTypesParsing.java:10: error: incompatible types: String cannot be converted to int
    int newYear = year + 1;
                       ^
1 error

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.time.LocalDate;

public class IncompatibleTypesParsing {

  public static void main(String... args) {
    String date = LocalDate.now().toString();
    String year = date.split("-")[0];
    int newYear = Integer.parseInt(year) + 1;
    System.out.println("Happy New Year " + newYear + "!");
  }
}
Happy New Year 2022!
Figure 2: Incompatible types when parsing (a) error and (b) resolution

Incorrect type assignments

Sometimes, the incompatible types error can occur due to basic negligence, where the only mistake is an accidental mis-declaration of a variable’s type (Fig. 3(a)). In these instances, the issue is quite obvious and simply correcting the type declaration solves the problem (Fig. 3(b)).

(a)

package rollbar;

public class IncompatibleTypesAssignment {

 public static void main(String... args) {
   int greeting = "Merry Christmas!";
   System.out.println(greeting);
 }
}
IncompatibleTypesAssignment.java:6: error: incompatible types: String cannot be converted to int
    int greeting = "Merry Christmas!";
                   ^
1 error

(b)

package rollbar;

public class IncompatibleTypesAssignment {

 public static void main(String... args) {
   String greeting = "Merry Christmas!";
   System.out.println(greeting);
 }
}
Merry Christmas!
Figure 3: Incompatible types with incorrect assignment (a) error and (b) resolution

Incorrect method return types

A slightly less common but non-surprising occurence of the incompatible types error, especially when refactoring is involved, can be found in method return types. Namely, sometimes a method’s return statement ends up returning a value that doesn’t match the method’s declared return type (Fig. 4(a)). This issue has two possible remedies; either make the value returned match the return type (Fig. 4(b)), or change the method’s return type to match the actual value returned (Fig. 4(c)). And in the case of void methods (methods with no return type), one can simply get rid of the return statement if the return value is never used, as is the case with the example in Fig. 4.

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

public class IncompatibleTypesReturn {

 public static void main(String... args) {
   printGreeting();
 }

 static void printGreeting() {
   System.out.println("Happy Holidays");
   return true;
 }
}
IncompatibleTypesReturn.java:11: error: incompatible types: unexpected return value
    return true;
           ^
1 error

(b)

1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;

public class IncompatibleTypesReturn {

 public static void main(String... args) {
   printGreeting();
 }

 static void printGreeting() {
   System.out.println("Happy Holidays");
 }
}
Happy Holidays!

(c)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

public class IncompatibleTypesReturn {

 public static void main(String... args) {
   printGreeting();
 }

 static boolean printGreeting() {
   System.out.println("Happy Holidays");
   return true;
 }
}
Happy Holidays!
Figure 4: Incompatible types with incorrect return type (a) error and (b)(c) two solutions

Incorrect imports and similarly named reference types

It is not uncommon to come across classes or other reference types with the same or a similar name. In fact, this happens even within the standard Java API, and can baffle many programmers, beginners and experts alike. One such case is the List class which represents one of Java’s main collection data structures [6]. This reference type can easily come into collision with another type of the same name, but from a different package. Namely, that’s the java.awt.List class that is part of Java’s built-in AWT API for creating graphical user interfaces [7]. All it takes is accidentally importing the wrong package, and the compiler immediately complains about the type mismatch, raising the incompatible types error, as demonstrated in Fig. 5(a). Fixing the import on line 5, as shown in Fig. 5(b), sorts things out.

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.util.ArrayList;
import java.util.Arrays;
import java.awt.List;

public class IncompatibleTypesList {

 public static void main(String... args) {
   List songs = new ArrayList<String>(Arrays.asList("Silent Night", "Deck the Halls", "Jingle Bells", "Winter Wonderland"));
   System.out.println(songs);
 }
}
IncompatibleTypesList.java:10: error: incompatible types: ArrayList<String> cannot be converted to List
    List songs = new ArrayList<String>(Arrays.asList("Silent Night", "Deck the Halls", "Jingle Bells", "Winter Wonderland"));
                 ^
1 error

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class IncompatibleTypesList {

 public static void main(String... args) {
   List songs = new ArrayList<String>(Arrays.asList("Silent Night", "Deck the Halls", "Jingle Bells", "Winter Wonderland"));
   System.out.println(songs);
 }
}
[Silent Night, Deck the Halls, Jingle Bells, Winter Wonderland]
Figure 5: Incompatible types incorrect reference type (a) error and (b) resolution

Popular external libraries are also prone to naming their reference types similarly, so whenever relying on such a library for a certain feature or functionality it is important to pick one, or be careful not to confuse one for another, if multiple libraries are already being used.

Fig. 6(a) shows an example of passing a JSON type object to a method as an argument. Here, the method printJson expects an argument of type JsonObject, but the calling method tries to pass in an instance of the similarly named JSONObject reference type, part of a different library altogether. This results in the incompatible types error being raised by the compiler, with the alert org.json.JSONObject cannot be converted to javax.json.JsonObject pointing to the erroneous method call. Swapping the inappropriate constructor call with an instance of the correct type solves the issue, as shown in Fig. 6(b).

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;

import org.json.JSONObject;
import javax.json.JsonObject;
import java.util.Map;

public class IncompatibleTypesJson {

  public static void main(String... args) {
    Map<String, Object> jsonMap = Map.of(
        "name", "Saint Nicholas",
        "nicknames", new String[]{"Santa Claus", "Father Christmas"},
        "location", "North Pole"
    );

    JsonObject json = Json.createObjectBuilder(jsonMap).build();

    printJson(json);
}

  static void printJson(JSONObject jsonObject) {
    System.out.println(jsonObject.toString(4));
  }
}
IncompatibleTypesJson.java:18: error: incompatible types: 
javax.json.JsonObject cannot be converted to org.json.JSONObject
    printJson(json);
              ^

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;

import javax.json.Json;
import javax.json.JsonObject;
import java.util.Map;

public class IncompatibleTypesJson {

  public static void main(String... args) {
    Map<String, Object> jsonMap = Map.of(
        "name", "Saint Nicholas",
        "nicknames", new String[]{"Santa Claus", "Father Christmas"},
        "location", "North Pole"
    );

    JSONObject json = new JSONObject(jsonMap);

    printJson(json);
  }

  static void printJson(JSONObject jsonObject) {
    System.out.println(jsonObject.toString(4));
  }
}
{
    "name": "Saint Nicholas",
    "location": "North Pole",
    "nicknames": [
        "Santa Claus",
        "Father Christmas"
    ]
}
Figure 6: Incompatible types incorrect reference type (a) error and (b) resolution

Fig. 6 also serves as an example to show how the incompatible types error is, in fact, a generalization of the method X in class Y cannot be applied to given types error explored in [4]. Depending on the specific compiler that is being used and its configuration settings, either of these errors could be triggered in this kind of scenario.

Summary

As a strongly typed language, Java has strict rules regarding data types and how they interoperate. These rules affect variable assignment, method invocation, return values, etc. This makes Java code verbose, but at the same time quite secure, as it allows for many errors to be detected during compilation. One such error is the incompatible types error, which is directly tied to Java’s type system. This article provides some background into Java types and dives into the symptoms and causes behind the incompatible types error, by presenting a series of relevant examples tailored to bring clarity in understanding and successfully managing this error.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

References

[1] R. Liguori and P. Liguori, 2017. Java Pocket Guide, 4th ed. Sebastopol, CA: O’Reilly Media, pp. 23-46.

[2] W3schools.com, 2021. Java Type Casting. Refsnes Data. [Online]. Available: https://www.w3schools.com/java/java_type_casting.asp. [Accessed: Dec. 18, 2021]

[3] D. Capka, 2021. Lesson 3 — Variables, type system and parsing in Java, Ictdemy.com. [Online]. Available: https://www.ictdemy.com/java/basics/variables-type-system-and-parsing-in-java. [Accessed: Dec. 19, 2021]

[4] Rollbar, 2021. How to Fix Method/Constructor X in Class Y Cannot be Applied to Given Types in Java, Rollbar Editorial Team. [Online]. Available: https://rollbar.com/blog/how-to-fix-method-constructor-in-class-cannot-be-applied-to-given-types-in-java/. [Accessed: Dec. 21, 2021]

[5] W3schools.com, 2021. Java Type Casting. Refsnes Data. [Online]. Available: https://www.w3schools.com/java/java_type_casting.asp. [Accessed: Dec. 21, 2021]

[6] Oracle.com, 2021. Lesson: Implementations (The Java™ Tutorials > Collections). [Online]. Available: https://docs.oracle.com/javase/tutorial/collections/implementations/index.html. [Accessed: Dec. 21, 2021]

[7] Oracle.com, 2020. Package java.awt (Java SE 15 & JDK 15). Oracle and/or its affiliates [Online]. Available: https://docs.oracle.com/en/java/javase/15/docs/api/java.desktop/java/awt/package-summary.html. [Accessed: Dec. 21, 2021]

java: incompatible types: java.lang.String cannot be converted to char ошибка

Уважаемые сокурсники и старшаки,

Помогите с кодом. Пишет ошибку: java: incompatible types: java.lang.String cannot be converted to char к строке 24 и 27.

package com.javarush.task.jdk13.task06.task0634;

import sun.lwawt.macosx.CSystemTray;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/*
Шахматная доска
*/

public class Solution {
public static char[][] array;

public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(reader.readLine());
array = new char[a][a];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if ((i + j) % 2 == 0) {
array[i][j] = «#»;
}
else {
array[i][j] = » «;
}
}
}

for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}

//напишите тут ваш код
}
}

Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

I am using netbeans and have an error that reads «incompatible types: String cannot be converted to List<String>»

I don’t understand why I am receiving the error. I thought that .next() returned a String?

Thankyou for all your help


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Nico Fish wrote:I am using netbeans and have an error that reads «incompatible types: String cannot be converted to List<String>»

I don’t understand why I am receiving the error. I thought that .next() returned a String?

Thankyou for all your help

not sure i can be much help because I’m quite new to this, but I’d remove that line and output tempStringScanner.next() to the console to see what you get. might help you spot a problem.

Nico Fish

Greenhorn

Posts: 20


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Sorry, I am very new what do you mean by output it to the next console?

nick woodward

Ranch Hand

Posts: 386


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Nico Fish wrote:Sorry, I am very new what do you mean by output it to the next console?

i think your problem is actually the declaration of the list, not the line where you add the string to the list

I’m just having a play with it now myself

anyway, here’s what i meant about outputting to the console:

remove the line where you get the error, and type «System.out.println(tempStringScanner.next());»

instead of adding the String to the arrayList at position i, it should print that value to the screen.

i’m pretty sure that isn’t your problem. but its worth checking to see if tempStringScanner.next() is working correctly. narrows down the problem i guess.

like i said, i’m new so probably not much help, but you might as well keep working on it while you wait for someone with a lot more knowledge!

nick woodward

Ranch Hand

Posts: 386


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

have you tried just using a declaration like:

ArrayList<> fileDArr = new ArrayList<>();

?

Nico Fish

Greenhorn

Posts: 20


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

I did that prior to your post to check and it printed the text file so that is not the problem.

I’ll wait for someone else. I already spent an embarrassing amount of time trying to figure it out myself.

Thanks, for the help

nick woodward

Ranch Hand

Posts: 386


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Nico Fish wrote:I did that prior to your post to check and it printed the text file so that is not the problem.

I’ll wait for someone else. I already spent an embarrassing amount of time trying to figure it out myself.

Thanks, for the help

no problem buddy. one more try ;)

this creates a list containing a list of strings.

so fileDArr refers to a list of lists, so you can’t add a string at position i, because it expects a list, not a string.

try

that’s my guess anyway, and it seems to be what the compiler is telling you too!

Nico Fish

Greenhorn

Posts: 20


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Hmmm if that is the problem then how do I fix it?

I think I will use a HashMap instead

Im getting a different error now

This is my output:

«number of files: 6

Exception in thread «main» java.util.NoSuchElementException

at java.util.Scanner.throwFor(Scanner.java:907)

at java.util.Scanner.next(Scanner.java:1416)

at rna.sort.RNASort.FileSearch(RNASort.java:50)

at rna.sort.RNASort.main(RNASort.java:67)

Java Result: 1

BUILD SUCCESSFUL (total time: 0 seconds)

«

nick woodward

Ranch Hand

Posts: 386


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

remove this ^

and put: ArrayList<String> fileDArr = new ArrayList<String>();

OR

I guess you could try List<String>fileDArr; rather than List<List<String>>.

you see what i mean about a list of lists? whatever is in the angular brackets is what the compiler expects the list to contain, and you’ve written <List<String>>, so fileDArr is a list of lists, where each list contains a string.

so fileDArr cannot take a string at position i, because each element in the fileDArr list contains a list itself, whose elements contain strings

hope that was clear enough/correct!

Nico Fish

Greenhorn

Posts: 20


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

I understand what you mean about list of list. However, I need a 2d list as I am dealing with multiple files. I think the HashMap could work as I can assign each file a key.

nick woodward

Ranch Hand

Posts: 386


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Nico Fish wrote:I understand what you mean about list of list. However, I need a 2d list as I am dealing with multiple files. I think the HashMap could work as I can assign each file a key.

well as far as i can see in your original code you’ve created the list fileDArr, but you haven’t populated the list itself with other lists.

you’d then have to add the strings to each element/list in the list. if it was a 2dArray it would be something like: fileDArr[x].add(i, tempStringScanner.next());

in an arraylist you’d use an iterator to help you achieve the same thing i guess.

sorry i couldn’t be more help buddy.

Nico Fish

Greenhorn

Posts: 20


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

I feel very incompetent now. I see what you mean I did not need a 2d list. I fixed that and took care of the other error by using a BufferedReader instead of a scanner (not sure why that fixed the problem but it did)

Nico Fish

Greenhorn

Posts: 20


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

I feel very dumb.

Thank you very much Nick. I fixed the code and it runs perfectly now!

nick woodward

Ranch Hand

Posts: 386


posted 8 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Nico Fish wrote:I feel very dumb.

Thank you very much Nick. I fixed the code and it runs perfectly now!

no worries, glad it helped!

Я новичок в программировании и очень новичок в Java, поэтому я уверен, что этот вопрос (и все мои другие ошибки) будет очевиден для любого, у кого есть опыт. Я точно не знаю, что делаю. Моим заданием было преобразовать код Python в Java. Ниже мой код.

Мои два кода ошибки:

Assignment1.java:37: error: incompatible types: String cannot be
converted to int 
response = reader.nextLine();
Assignment1.java:38: error: incompatible types: int cannot be converted to String 
num = Integer.parseInt(response);

Для пояснения я использую JGrasp, но не хочу.

Спасибо за продвинутую помощь. ~ JBOrunon

import java.util.Scanner;
public class Assignment1 {
      public static void main(String[] args) {

         int num, response, min, max, range, sum, count, avg;
         Scanner reader = new Scanner(System.in);
         String reportTitle;


         //title
         System.out.println();
         System.out.println("Enter a title for this report");
         reportTitle = reader.nextLine();
         System.out.println();


         //data input
         System.out.println("Enter a series of numebr, ending with a 0");

         num = 0;
         sum = 0;
         response = 1;
         count = 0;
         max = 0;
         min = 0;
         range = 0;

         while (true)
         {
            if (response < 1)
            {
               System.out.println("End of Data");
               break;
            }

          System.out.println("Enter number => ");
          response = reader.nextLine();
          num = Integer.parseInt(response);

          sum += num;
          count += 1;

          if (num>max)
          {
            max = num;
          }
          if (num<min)
          {
            min = num;
          }

         }

         //crunch
         avg = sum / count;
         range = max - min;

         //report
         System.out.println();
         System.out.println(reportTitle);
         System.out.println();
         System.out.println("Sum: => "+sum);
         System.out.println("Average: => "+avg);
         System.out.println("Smallest: => "+min);
         System.out.println("Largest: => "+max);
         System.out.println("Range: => "+range);


    }

}

2 ответа

Лучший ответ

response — это int, а метод nextLine() из Scanner возвращает … ну, строку, представленную String . Вы не можете назначить String на int — как бы вы это сделали? String может быть любым, от "some text" до " a 5 0 ". Как бы вы преобразовали первый и / или второй в int?

Вероятно, вы хотели:

System.out.println("Enter number => ");
response = reader.nextInt();
// notice this        ^^^

Вместо того:

System.out.println("Enter number => ");
response = reader.nextLine();
// instead of this    ^^^^

Метод nextInt() ожидает последовательность цифр и / или символов, которые могут представлять число, например: 123, -50, 0 и так далее …

Однако вы должны знать об одной важной проблеме — смешивание nextLine() и nextInt() может привести к нежелательным результатам. Например:

Scanner sc = new Scanner(System.in);
String s;
int a = sc.nextInt();
s = sc.nextLine();
System.out.println(s);

Напечатает ничего , потому что при вводе числа вы вводите, например, 123 и нажимаете enter , вы дополнительно вводите символ новой строки . Затем nextLine() сработает и просканирует каждый символ до первого введенного символа новой строки или конца файла , который, очевидно, все еще там , не использованный { {X2}}. Чтобы исправить это и узнать больше об этом, перейдите здесь


1

Fureeish
19 Янв 2018 в 19:34

Чтобы прочитать целое число из файла, вы можете просто использовать такой пример:

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

Однако вы не даете дополнительной информации о своей файловой структуре, поэтому я советую еще раз заглянуть в документацию, чтобы найти то, что вам больше всего подходит. Вы можете найти документацию по сканеру здесь.


1

Rudziankoŭ
31 Янв 2018 в 13:47

Перейти к контенту

I bet you generated the getters and setters and the constructor for the initial set of fields which are these.

// private String suit;
// private String name;
// private int value;

But after changing them to

private String[] suit = { "spades", "hearts", "clubs", "diamonds" };
private String[] name = { "Ace", "Jack", "Queen", "King" };
private int[] value = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };

you forgot to modify them accordingly. You need to change your getters and setters and constructors to something like this. The same goes with the toString() method.

public class Card {

    private String[] suit = { "spades", "hearts", "clubs", "diamonds" };
    private String[] name = { "Ace", "Jack", "Queen", "King" };
    private int[] value = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };

    public Card(String[] suit, String[] name, int[] value) {
        super();
        this.suit = suit;
        this.name = name;
        this.value = value;
    }

    public String[] getSuit() {
        return suit;
    }

    public void setSuit(String[] suit) {
        this.suit = suit;
    }

    public String[] getName() {
        return name;
    }

    public void setName(String[] name) {
        this.name = name;
    }

    public int[] getValue() {
        return value;
    }

    public void setValue(int[] value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Card [suit=" + Arrays.toString(suit) + ", name="
            + Arrays.toString(name) + ", value=" + Arrays.toString(value)
            + "]";
    }
}

Always remember to generate fresh getters, setters, constructor, toString() methods, if you happen to change the fields in the class.

I tried taking input of a 6 by 6 matrix in java using the string split function when the string is input in the following way, and to print the matrix.

1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6

The output that I get is

Main.java:24: error: incompatible types: String[] cannot be converted to String
                                c[j] = b[i].split(" ");

my code:

import java.util.*;
import java.io.*;

class Solution {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        int a[][] = new int[6][6];
        String b[] = new String[6];

        for (int i = 0; i < 6; i++) {
            b[i] = s.nextLine();
        }

        // initializing the 2d array a[][]
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 6; j++) {
                String c[] = new String[6];
                c[j] = b[i].split(" ");
                a[i][j] = Integer.parseInt(c[j]);
            }
        }

        // printing the input array
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 6; j++) {
                System.out.print("ta[i][j]t");
            }
        }
    }
}

pls, suggest how I can overcome this error

Community's user avatar

asked Aug 10, 2020 at 4:01

Apptrixie's user avatar

1

When we call split function of String return the String[]. So c[j] (which is of type String) can’t be equal to String[].

Below code should be replaced as:

// initializing the 2d array a[][]
for (int i = 0; i < 6; i++) {
    String[] c = b[i].split(" ");
    for (int j = 0; j < 6; j++) {
        a[i][j] = Integer.parseInt(c[j]);
    }
}

Community's user avatar

answered Aug 10, 2020 at 4:17

Gaurav Jeswani's user avatar

Gaurav JeswaniGaurav Jeswani

4,1876 gold badges23 silver badges46 bronze badges

The return type of split() function is type of array. Because you are asking java to give me each value as separate which is separated by " " (space). So java will create an array of each value and returns you the array. For storing the array you need an variable of type array. here c represent an array, but c[j] represents an single index of the array.

You can change your code like:

for (int i = 0; i < 6; i++) {
    String c[] = b[i].split(" ");
    for (int k = 0; k < c.length; k++) {
        a[i][k] = Integer.parseInt(c[k]);
    }
}

The the inputs are integer and you are converting them to integer later, I would suggest you to take input as integer like below:

class Solution {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        int a[][] = new int[6][6];

        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 6; j++) {
                a[i][j] = s.nextInt();
            }
        }

        // printing the input array
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 6; j++) {
                System.out.print("ta[i][j]t");
            }
        }
    }
}

Community's user avatar

answered Aug 10, 2020 at 4:16

Deepak Kumar's user avatar

Deepak KumarDeepak Kumar

1,21713 silver badges36 bronze badges

I’m taking a Java class for college, and was working on some given tasks. This is the code I wrote for it.

public class String
{
 public static void main(String[] args)
 {
  String city = "San Francisco";
  int stringLength = city.length();
  char oneChar = city.charAt(0);
  String upperCity = city.toUpperCase();
  String lowerCity = city.toLowerCase();

  System.out.println(city);
  System.out.println(stringLength);
  System.out.println(oneChar);
  System.out.println(upperCity);
  System.out.println();
  }
 }

which yielded these results

C:UserssamDocumentsJava>javac String.java
String.java:8: error: incompatible types: java.lang.String cannot be 
converted to String
          String city = "San Franciso";
                        ^
String.java:9: error: cannot find symbol
            int stringLength = city.length();
                                   ^
symbol:   method length()
location: variable city of type String
String.java:10: error: cannot find symbol
            char oneChar = city.charAt(0);
                               ^
symbol:   method charAt(int)
location: variable city of type String
String.java:11: error: cannot find symbol
            String upperCity = city.toUpperCase();
                                   ^
symbol:   method toUpperCase()
location: variable city of type String
String.java:12: error: cannot find symbol
            String lowerCity = city.toLowerCase();
                                   ^
symbol:   method toLowerCase()
location: variable city of type String
5 errors

I’ve tried searching for an answer but I didn’t really find anything that helps. Any help is appreciated, thanks.

asked Jan 26, 2018 at 9:19

2

Since your class is named String, unqualified type reference in String city is taken as reference to your own class.

Either rename the class to some other name, or you’ll have to write java.lang.String wherever you reference the «built-in» Java String class.

answered Jan 26, 2018 at 9:21

Jiri Tousek's user avatar

Jiri TousekJiri Tousek

12.1k5 gold badges30 silver badges43 bronze badges

It is conflict between system class java.lang.String and your class named String. Rename your class String to say MyString, i.e. replace line:

public class String

with

public class MyString

And rename file String.java containing this class to MyString.java.

answered Jan 26, 2018 at 9:37

Anton Tupy's user avatar

Anton TupyAnton Tupy

9415 silver badges16 bronze badges

  • Remove From My Forums
  • Question

  • msg = Console.ReadLine();           

                for (i = 0; i < msg.Length; i++)
                    p[i] = msg[i];

    //Here msg is an array of type string

Answers

  • You shoulddo it like:

    string msg = Console.ReadLine();
    string[]array = msg.Split(' ');
    
    

    or if you want to put every user`s input into an array:

    string[] array = null;
    int i = 1;
    while(true)
    {
     Console.WriteLine("Enter new insertion:"); 
     string msg = Console.ReadLine();
     Array.Resize(ref array, i++);
     array[i - 1] = msg; 
     Console.WriteLine("Do you want a new insertion? Type yes, or no);
     msg = Console.ReadLine();
     if(msg == "no")
      break;
    }
    

    Hope it helps,

    Mitja

    • Edited by

      Friday, March 25, 2011 10:50 AM
      Ups, sorry it was a typo (I did the code by my heart).

    • Marked as answer by
      Lie You
      Monday, April 4, 2011 4:25 AM
  • Hello Techis,

    Welcome to the MSDN Forum.

    I want to know what’s your “p[i]”.

    Here is my code, it works well 
    on my machine.

                   
    string
    msg =Console.ReadLine();

               
    string[] p= new
    string [msg.Length+1];

    StringBuilder sb =
    new StringBuilder();//this is also OK.

               
    for (int i = 0; i < msg.Length; i++)

               
    {

     
    sb.Append(msg[i]);//for StringBuilder

                   
    p[i] = msg[i].ToString();//here, if I don’t use ToString, there is always an error “Cannot implicitly convert type
    ‘char’ to ‘string’ 

               
    }

               
    foreach (string 
    c in p)

               
    {

                   
    Console.Write(c);

               
    }

               
    Console.ReadLine();

    I hope this will help resolve your problem

    If you have any difficulty in future programming, we welcome you to post here again. There are many enthusiastic community members
    here to provide their help and suggestions.


    Best Regards,
    Rocky Yue[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by
      Lie You
      Monday, April 4, 2011 4:25 AM
  • Forum
  • Beginners
  • cannot convert string to string*

cannot convert string to string*

Error 1 error C2440: ‘initializing’ : cannot convert from ‘std::string’ to ‘std::string *’

1
2
3
4
5
6
7
cout<<"Please enter book name:"<<endl;								
cin>>bookName;                     //user enters book name
string *addBookOne=bookName;      //string pointer is created
reservationFile<<*addBookOne;	//  pointer string added to file				

//write book name to reservationFile file
				

Good thing you spotted the error, right? So, uh, if you aren’t asking for help why are you posting here?

i’m wondering how to fix it haha

Oh, well. Judging by the error, I will guess that

bookName

is a

string

, right? If so, why are you trying to assign a string to a string pointer without referencing it (&)? Also, why do you even need the string pointer at all if you’re just going to write it to the file either way? Can’t you just do reservationFile << bookName;?

i need to have it displayed «couted» later

Topic archived. No new replies allowed.

// hey guys pls I need your help with this 

String EmailAdresses = AstraProperties.getProperties(AstraProperties.EMAIL_NOTIFICATIONS);


// when I print out EmailAdresses, it returns a long string of addresses
//jamesb@live.com,jbrowm@yahoo.com,cmsw@msn.com
// then I want to split it and place it in EmailArray


String[] EmailArrray = EmailAdresses.Split(",")

// but I get the error: Cannot implicitly convert type 'string' to 'string[]' 


// thanks for the help


Solution 1

Try:

String[] EmailArrray = EmailAdresses.Split(',');

Comments

Solution 2

String[] EmailArray = EmailAdresses.Split(',');

Problem is you are trying to use the wrong overload of the split function.

Comments

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Print

Answers RSS

Top Experts
Last 24hrs This month

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

java: incompatible types: java.lang.String cannot be converted to char ошибка

Уважаемые сокурсники и старшаки,

Помогите с кодом. Пишет ошибку: java: incompatible types: java.lang.String cannot be converted to char к строке 24 и 27.

package com.javarush.task.jdk13.task06.task0634;

import sun.lwawt.macosx.CSystemTray;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/*
Шахматная доска
*/

public class Solution {
public static char[][] array;

public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(reader.readLine());
array = new char[a][a];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
if ((i + j) % 2 == 0) {
array[i][j] = «#»;
}
else {
array[i][j] = » «;
}
}
}

for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}

//напишите тут ваш код
}
}

Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.

gwiden

3 / 3 / 0

Регистрация: 13.11.2016

Сообщений: 37

1

23.09.2017, 13:34. Показов 1055. Ответов 3

Метки нет (Все метки)


Подчеркивает «inn.nextLine()» в 17 строке и пишет — «Type mismatch: cannot convert from String to String[]». Помогите пожалуйста с ошибкой? Я хотел передавать в массив символы пол очереди и дальше уже выполнять над ними действия но застопорился уже тут.
P.S. Только начал изучать JAVA.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package laba_2;
import java.util.Scanner;
public class Laba2 
{
    public static void main(String[] args) 
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Введите размер массива: ");
        int n = in.nextInt();
        System.out.println("Удаление букв 'O' стоящих на нечетных местах ");
        System.out.println("Введите по букве строку символов ");    
        String[] arr = new String[n];
        for (int i=0;i<n;i++)
        {
            Scanner inn = new Scanner(System.in);
            System.out.print("Введите массив состоящий из букв: ");
            arr = inn.nextLine();
        }
    }
 
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

no_way

Заблокирован

23.09.2017, 13:57

2

Цитата
Сообщение от gwiden
Посмотреть сообщение

arr = inn.nextLine();

К элементу массив надо обращаться через [].
И два сканнеры не понятно зачем создаешь. И не закрываешь их.

0

3 / 3 / 0

Регистрация: 13.11.2016

Сообщений: 37

23.09.2017, 14:11

 [ТС]

3

Обратился через [], теперь подчеркивается arr[] и пишет «Multiple markers at this line
— Syntax error, insert «. class» to complete
Expression
— The left-hand side of an assignment must be a
variable»
И про сканеры я не понял что не так?

0

no_way

Заблокирован

23.09.2017, 14:15

4

Цитата
Сообщение от gwiden
Посмотреть сообщение

Обратился через []

А индекс?

Добавлено через 24 секунды

Цитата
Сообщение от gwiden
Посмотреть сообщение

И про сканеры я не понял что не так?

Вроде все понятно написано: зачем их два? Почему не закрываешь?

0

Понравилась статья? Поделить с друзьями:
  • Error incompatible types string cannot be converted to int
  • Error incompatible types possible lossy conversion from double to int
  • Error incompatible types possible lossy conversion from double to float
  • Error incompatible types object cannot be converted to
  • Error incompatible types nonexistentclass cannot be converted to annotation