Меню

Ошибка string cannot be converted to string

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



0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка stream read error
  • Ошибка stream not found