Illegal cast ошибка

Не понимаю почему не запускает код и выдает ошибку illegal start of expression

package InputandOtput;
import java.io.*;

public class ReadBytes {
    public static void main(String[] args){
        throws IOException {
            byte[] data = new byte[10];
            System.out.println("Enter Symbol");
            System.in.read(data);
            System.out.println("You enter: ");
            for (int i = 0; i < data.length; i++) {
                System.out.print(data[i]);
            }
        }
    }
}

I’m getting the error, illegal cast: from 'int' to 'FIELDS' while initializing the structure variables here:-

SOCKET_LOG_DATA socket_log_data() : fields(0), socket_number(0) {}

How should I resolve it?

typedef PACKED struct PACKED_SUFFIX
{
      UINT16 loss_reason : 1;
      UINT16 unused : 15;
} LOSS_REASON;

typedef union PACKED_SUFFIX
{
      LOSS_REASON loss;
      UINT16 all_fields;
} FIELDS;

typedef PACKED struct PACKED_SUFFIX SOCKET_LOG_DATA
{
      FIELDS fields;
      UINT16 socket_number;

      // As per @Dietrich's & @crashmstrcomments:-
      SOCKET_LOG_DATA() : fields{{0, 0}}, socket_number(0) {}
} SOCKET_LOG_DATA;

Gave a lot many errors:-

".filename.h", line 183: error (dplus:1207): syntax error near }
".filename.h", line 183: error (dplus:1463): type expected in arg-declaration-clause
".filename.h", line 183: error (dplus:1263): identifier socket_number already declared
".filename.h", line 183: error (dplus:1376): function int socket_number(void) is not a member of class $incomplete SOCKET_LOG_DATA
".filename.h", line 183: error (dplus:1247): syntax error after fields, expecting (
".filename.h", line 183: error (dplus:1404): mem initializers only allowed for constructors
".filename.h", line 183: error (dplus:1247): syntax error after 0, expecting ;

Then I retained socket_log_data() constructor by changing the line to

SOCKET_LOG_DATA socket_log_data() : fields{{0, 0}}, socket_number(0) {}

, and received following errors:-

".filename.h", line 183: error (dplus:1272): member $incomplete SOCKET_LOG_DATA::fields used outside non-static member function
".filename.h", line 183: error (dplus:1125): int constant expected
".filename.h", line 183: error (dplus:1536): bitfields must be integral type
".filename.h", line 183: error (dplus:1247): syntax error after fields, expecting ;
".filename.h", line 183: error (dplus:1436): syntax error - declarator expected after }
".filename.h", line 183: error (dplus:1461): type expected for socket_number
".filename.h", line 183: error (dplus:1247): syntax error after ), expecting ;
".filename.h", line 186: error (dplus:1461): type expected for SOCKET_LOG_DATA

Describe the bug
After successful connection, the following call throws an error:

result = conn.call("RFC_READ_TABLE", QUERY_TABLE='REPOSRC', DELIMITER='|', FIELDS = ['PROGNAME'], OPTIONS=[{'TEXT':"PROGNAME = 'ZZ_TEST'"}], ROWCOUNT = 1000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "src/pyrfc/_pyrfc.pyx", line 500, in pyrfc.pyrfc.Connection.call
  File "src/pyrfc/_pyrfc.pyx", line 332, in pyrfc.pyrfc.Connection._error
pyrfc._exception.ABAPRuntimeError: RFC_ABAP_RUNTIME_FAILURE (rc=3): key=ASSIGN_CASTING_ILLEGAL_CAST, message=Error with ASSIGN ... CASTING in program SAPLSDTX                                . [MSG: class=, type=, number=, v1-4:=;;;]

To Reproduce

from pyrfc import Connection
conn = Connection(ashost='XXX', sysnr='00', client='100', user='XXX', passwd='XXX')
result = conn.call("RFC_READ_TABLE", QUERY_TABLE='REPOSRC', DELIMITER='|', FIELDS = ['PROGNAME'], OPTIONS=[{'TEXT':"PROGNAME = 'ZBC_ACTT_EXTRACT'"}], ROWCOUNT = 1000)

I have tested this by calling several other tables and noticed that the issue only occurs if the table has a field with data type rawstring (RSTR) / xstring.

Environment

  • OS: x86_64 GNU/Linux
  • Running in docker? Yes, but get the same result outside of docker
  • PyRFC version = 2.4.1 using NWRFC SDK 7.5 PL 8

//————————————————-
файл SPMainWin.h

#include «SPSettings.h»

void InitSettings();

//————————————————-
файл SPMainWin.cpp

#include «SPMainWin.h»

void InitSettings()
{
MainSettings.SCREEN_WIDTH = 640;
MainSettings.SCREEN_HEIGHT = 480;
MainSettings.TITLE = «SP»;
}

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
InitSettings();
}

//————————————————-

файл SPSettings.h

#pragma once

#include <string>

class SPSettings {

public:
SPSettings(void);
~SPSettings(void);

typedef std::basic_string<char> TITLE;
typedef unsigned int SCREEN_WIDTH;
typedef unsigned int SCREEN_HEIGHT;
};

extern SPSettings MainSettings;
//————————————————-
файл SPSettings.cpp

#include «SPSettings.h»

SPSettings MainSettings;

SPSettings::SPSettings(void)
{
}

SPSettings::~SPSettings(void)
{
}
//————————————————-

Получаю ошибку

SPMainWin.cpp(20): error C2274: ‘function-style cast’ : illegal as right side of ‘.’ operator
SPMainWin.cpp(21): error C2274: ‘function-style cast’ : illegal as right side of ‘.’ operator
SPMainWin.cpp(22): error C2274: ‘function-style cast’ : illegal as right side of ‘.’ operator

Может подскажете — в чем я не прав?

A quick guide and fix to java lang ClassCastException in java with examples.

1. Overview

In this article, we will learn what is java.lang.ClassCastException in java and how to fix it.

We will look at the meaning of ClassCastException and a few examples of it.

java lang ClassCastException

2. What is the meaning of ClassCastException

From API, ClassCastException is thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. 

If you are not clear what is ClassCastException then look at the below example.

For example, the following code generates a ClassCastException:

Object x = new Integer(0);
System.out.println((String)x);

In this example, we are trying to cast an Integer object into a String. That means converting the Integer object into a String. This operation produced the class cast exception.

The reason behind this error is there is no direct relation between the Integer and String classes.

If there is a Has-a or Is-a relationship between the two classes then the casting is possible, if there is no relation between the classes and if we try to cast it to another class or interface then we get the ClassCastException.

3. Java ClassCastException Examples

A few examples to see in which scenarios we get the class cast exception at runtime.

Example 1

package com.javaprogramto.exception;

public class ClassCastExceptionExample {

	public static void main(String[] args) {

		Object s = "hello";
		Integer i = (Integer) s;
	}
}

Output

Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
	at com.javaprogramto.exception.ClassCastExceptionExample.main(ClassCastExceptionExample.java:8)

Example 2

In this example, class B extends class B that means B is a child of A. Child class object can be assinged to the parent class object but the parenet class object can not be assinged to the child class.

So here we have casted class A instance to class B. This code is resulted in classcastexception.

package com.javaprogramto.exception.classcaseexception;

public class ClassCastExceptionExample {

	public static void main(String[] args) {
		A a = new A();
		B b = (B) a;
	}
}

class A {

}

class B extends A {

}

Output

Exception in thread "main" java.lang.ClassCastException: class com.javaprogramto.exception.classcaseexception.A cannot be cast to class com.javaprogramto.exception.classcaseexception.B (com.javaprogramto.exception.classcaseexception.A and com.javaprogramto.exception.classcaseexception.B are in unnamed module of loader 'app')
	at com.javaprogramto.exception.classcaseexception.ClassCastExceptionExample.main(ClassCastExceptionExample.java:7)

Example 3

package com.javaprogramto.exception.classcaseexception;

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

public class ClassCastExceptionExample2 {

	public static void main(String[] args) {

		List list = new ArrayList<>();

		list.add(10);
		list.add(20);
		list.add("String");
		list.add(30);

		for (int i = 0; i < list.size(); i++) {
			Integer value = (Integer) list.get(i);
			System.out.println(value);
		}
	}
}

Ouptut

10
20
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
	at com.javaprogramto.exception.classcaseexception.ClassCastExceptionExample2.main(ClassCastExceptionExample2.java:18)

This example is resulted in error becaues of list has string in it and we casted each value of list into Integer. Once it found the string then it is not able to cast into the integer. So, ended up in exception.

4. How to fix ClassCastException

ClassCastException is a unchecked exception that is thrown by the JVM at runtime when you do the invalid or illegal casting is done. 

Finding the ClassCastException at the compile time can not be done as similar to the checked exceptions. 

So, we must be careful when we do the explicit casting to the different types.

To fix ClassCastException, we need to follow the strict generics when working with the collections API.

In the above section example 3, a list is created without generic type which did not show any error at the compile time but it produces the casting exception at the runtime.

Look at the below code how ClassCastException is eliminated at the compile time.

Example 4

package com.javaprogramto.exception.classcaseexception;

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

public class ClassCastExceptionExample2 {

	public static void main(String[] args) {

		List<Integer> list = new ArrayList<>();

		list.add(10);
		list.add(20);
		list.add("String");
		list.add(30);

		for (int i = 0; i < list.size(); i++) {
			Integer value = (Integer) list.get(i);
			System.out.println(value);
		}
	}
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The method add(Integer) in the type List<Integer> is not applicable for the arguments (String)

	at com.javaprogramto.exception.classcaseexception.ClassCastExceptionExample2.main(ClassCastExceptionExample2.java:14)

In the above example, the class cast exception is suppressed and caught at the compile time. So we can take out the string from the list.

Another way is to fix class cast exception is with instanceof oeprator.

Example 5

package com.javaprogramto.exception.classcaseexception;

public class ClassCastExceptionExample3 {

	public static void main(String[] args) {
		C c = new C();

		if (c instanceof D) {
			D d = (D) c;
		} else {
			System.out.println("c is not instance of d. skipping..");
		}
	}
}

class C {

}

class D extends C {

}

Output

c is not instance of d. skipping..

If you know any other ways, please post in the comments we will update the post.

5. Conclusion

In this tutorial, We’ve seen understood the meaning of Java ClassCastException which is present in the java.lang package.

how to fix java.lang.classcaseexception in java.


CAST.pyc проблемы часто являются результатом отсутствия, удаления или случайного перемещения файла из исходного места установки FreeBSD for amd64. Обычно, установка новой версии файла PYC позволяет устранить проблему, из-за которой возникает ошибка. Кроме того, регулярная очистка и оптимизация реестра Windows предотвратит создание неправильных ссылок на пути к файлам PYC, поэтому мы настоятельно рекомендуем регулярно выполнять сканирование реестра.

В таблице ниже представлен список доступных для загрузки файлов CAST.pyc, подходящих для большинства версий Windows (включая %%os%%). К сожалению, в настоящее время в нашей базе могут отсутствовать некоторые версии файлов CAST.pyc, но их можно запросить, нажав на кнопку Request (Запрос). Если ниже отсутствует необходимая вам версия, мы рекомендуем обратиться непосредственно к The FreeBSD Project.

Как правило, при размещении файла CAST.pyc в надлежащем каталоге, проблемы, связанные с данным файлом, больше не возникают, однако следует выполнить проверку, чтобы убедиться в том, что проблему удалось устранить. Повторно запустите FreeBSD for amd64, чтобы убедиться, что проблема успешно решена.

CAST.pyc Описание файла
Тип: PYC
Группа: Operating System
App: FreeBSD for amd64
Версия: 11.0
Программист: The FreeBSD Project
 
Имя файла: CAST.pyc  
Размер (в байтах): 3811
SHA-1: 822200e6afc8955ff7cfa5034392b5ceab759223
MD5: fbcfe57182a3c723e5701028a4090209
CRC32: cb6274b0

Продукт Solvusoft

Загрузка
WinThruster 2023 — Сканировать ваш компьютер на наличие ошибок реестра в CAST.pyc

Windows
11/10/8/7/Vista/XP

Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление

PYC
CAST.pyc

Идентификатор статьи:   555044

CAST.pyc

Filename Контрольная сумма MD5 Размер Загрузить
+ CAST.pyc fbcfe57182a3c723e5701028a4090209 3.72 KB
Софт FreeBSD for amd64 11.0
Программист The FreeBSD Project
Версия FreeBSD
Тип 64-разрядная (x64)
KB 3811
Контрольная сумма MD5 fbcfe57182a3c723e5701028a4090209
ША1 822200e6afc8955ff7cfa5034392b5ceab759223
CRC32: cb6274b0
+ CAST.pyc d41d8cd98f00b204e9800998ecf8427e 0.00 B
Софт Fedora 23 Server 64-bit 2015
Программист Red Hat, Inc.
Версия Linux x64
Тип 64-разрядная (x64)
KB 0
Контрольная сумма MD5 d41d8cd98f00b204e9800998ecf8427e
ША1 da39a3ee5e6b4b0d3255bfef95601890afd80709
CRC32: 00000000
+ CAST.pyc ef4ab57662303ac76fa6a0decfc03b9e 3.61 KB
Софт NOOBS 2.4.4
Программист Raspberry Inc
Версия Raspbian
Тип 64-разрядная (x64)
KB 3695
Контрольная сумма MD5 ef4ab57662303ac76fa6a0decfc03b9e
ША1 c4f05d9b2b8b838f49416b05e87f42511782d595
CRC32: 6ff3423f
+ CAST.pyc 0f99c216acd1f25fd7e85cf287141762 3.71 KB
Софт SUSE OpenStack Cloud x86_64 — 1 of 3 7
Программист SuSE Inc.
Версия Linux x86
Тип 64-разрядная (x64)
KB 3795
Контрольная сумма MD5 0f99c216acd1f25fd7e85cf287141762
ША1 65ce8de7b279fe9ff6ab3a849a7299f70ac2f071
CRC32: 1246284b
+ CAST.pyc 0f99c216acd1f25fd7e85cf287141762 3.71 KB
Софт SUSE OpenStack Cloud x86_64 — 1 of 3 7
Программист SuSE Inc.
Версия Linux x64
Тип 64-разрядная (x64)
KB 3795
Контрольная сумма MD5 0f99c216acd1f25fd7e85cf287141762
ША1 65ce8de7b279fe9ff6ab3a849a7299f70ac2f071
CRC32: 1246284b
+ CAST.pyc 0f99c216acd1f25fd7e85cf287141762 3.71 KB
Софт SUSE OpenStack Cloud x86_64 — 1 of 3 7
Программист SuSE Inc.
Версия SuSE Linux
Тип 64-разрядная (x64)
KB 3795
Контрольная сумма MD5 0f99c216acd1f25fd7e85cf287141762
ША1 65ce8de7b279fe9ff6ab3a849a7299f70ac2f071
CRC32: 1246284b
+ CAST.pyc 0f99c216acd1f25fd7e85cf287141762 3.71 KB
Софт SUSE OpenStack Cloud x86_64 — 1 of 3 7
Программист SuSE Inc.
Версия Linux
Тип 64-разрядная (x64)
KB 3795
Контрольная сумма MD5 0f99c216acd1f25fd7e85cf287141762
ША1 65ce8de7b279fe9ff6ab3a849a7299f70ac2f071
CRC32: 1246284b

Типичные ошибки CAST.pyc

Распространенные проблемы, связанные с FreeBSD for amd64s, возникающие с CAST.pyc:

  • «Ошибка в файле CAST.pyc.»
  • «CAST.pyc отсутствует или перемещен. «
  • «Отсутствует файл: CAST.pyc»
  • «Не удалось загрузить модуль для CAST.pyc. «
  • «Ошибка регистрации: CAST.pyc. «
  • «Ошибка CAST.pyc во время выполнения. «
  • «Ошибка загрузки: CAST.pyc. «

Ошибка CAST.pyc возникает во время ошибочной установки программы, во время запуска приложений, выпущенных CAST.pyc, во время установки Windows, запуска или завершения работы ПК. Документирование проблем CAST.pyc в FreeBSD for amd64 является ключевым для определения причины проблем с электронной Operating System и сообщения о них в The FreeBSD Project.

Причины ошибок в файле CAST.pyc

Проблемы CAST.pyc вызваны поврежденным или отсутствующим CAST.pyc, недопустимыми ключами реестра, связанными с FreeBSD for amd64, или вредоносным ПО.

Более конкретно, данные ошибки CAST.pyc могут быть вызваны следующими причинами:

  • Поврежденные ключи реестра Windows, связанные с CAST.pyc / FreeBSD for amd64.
  • Файл CAST.pyc поврежден от заражения вредоносными программами.
  • CAST.pyc злонамеренно или ошибочно удален другим программным обеспечением (кроме FreeBSD for amd64).
  • CAST.pyc конфликтует с другой программой (общим файлом).
  • Загрузите повреждение или неполную установку программы, связанной с CAST.pyc.

I’m getting the error, illegal cast: from 'int' to 'FIELDS' while initializing the structure variables here:-

SOCKET_LOG_DATA socket_log_data() : fields(0), socket_number(0) {}

How should I resolve it?

typedef PACKED struct PACKED_SUFFIX
{
      UINT16 loss_reason : 1;
      UINT16 unused : 15;
} LOSS_REASON;

typedef union PACKED_SUFFIX
{
      LOSS_REASON loss;
      UINT16 all_fields;
} FIELDS;

typedef PACKED struct PACKED_SUFFIX SOCKET_LOG_DATA
{
      FIELDS fields;
      UINT16 socket_number;

      // As per @Dietrich's & @crashmstrcomments:-
      SOCKET_LOG_DATA() : fields{{0, 0}}, socket_number(0) {}
} SOCKET_LOG_DATA;

Gave a lot many errors:-

".filename.h", line 183: error (dplus:1207): syntax error near }
".filename.h", line 183: error (dplus:1463): type expected in arg-declaration-clause
".filename.h", line 183: error (dplus:1263): identifier socket_number already declared
".filename.h", line 183: error (dplus:1376): function int socket_number(void) is not a member of class $incomplete SOCKET_LOG_DATA
".filename.h", line 183: error (dplus:1247): syntax error after fields, expecting (
".filename.h", line 183: error (dplus:1404): mem initializers only allowed for constructors
".filename.h", line 183: error (dplus:1247): syntax error after 0, expecting ;

Then I retained socket_log_data() constructor by changing the line to

SOCKET_LOG_DATA socket_log_data() : fields{{0, 0}}, socket_number(0) {}

, and received following errors:-

".filename.h", line 183: error (dplus:1272): member $incomplete SOCKET_LOG_DATA::fields used outside non-static member function
".filename.h", line 183: error (dplus:1125): int constant expected
".filename.h", line 183: error (dplus:1536): bitfields must be integral type
".filename.h", line 183: error (dplus:1247): syntax error after fields, expecting ;
".filename.h", line 183: error (dplus:1436): syntax error - declarator expected after }
".filename.h", line 183: error (dplus:1461): type expected for socket_number
".filename.h", line 183: error (dplus:1247): syntax error after ), expecting ;
".filename.h", line 186: error (dplus:1461): type expected for SOCKET_LOG_DATA

The problem is:

((PWORD)pbyTmp)++

You may hope that this increments pbyTmp to point at the next WORD. Instead, the increment would be applied to a temporary object resulting from the conversion, leaving pbyTmp unchanged. However, to prevent subtle bugs from mistakes like this, the language doesn’t allow temporaries to be used where lvalues are required, hence the error.

Presumably, your older compiler didn’t diagnose the error correctly, and gave some kind of undefined behaviour instead.

You should instead put the converted pointer into a variable of the correct type:

PWORD * pword = reinterpret_cast<PWORD>(pbyTmp);
*pword++ = whatever;
pbyTmp = reinterpret_cast<WHATEVER_pbyTMP_IS>(pword);

or, if you really hate whoever will have to maintain your code, cast to a (lvalue) reference:

*((PWORD&)pbyTmp)++ = whatever;

or, better still, change the type of pbyTmp to the correct type for what it points to.

Автор оригинала: Kai Yuan.

1. Обзор

“Незаконное начало выражения”-это распространенная ошибка, с которой мы можем столкнуться во время компиляции.

В этом уроке мы рассмотрим примеры, иллюстрирующие основные причины этой ошибки и способы ее устранения.

2. Отсутствующие Фигурные Скобки

Отсутствие фигурных скобок может привести к ошибке “незаконное начало выражения”. Давайте сначала рассмотрим пример:

package com.baeldung;

public class MissingCurlyBraces {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
        
    public int calcSum(int x, int y) {
        return x + y;
    }
}

Если мы скомпилируем вышеуказанный класс:

$ javac MissingCurlyBraces.java
MissingCurlyBraces.java:7: error: illegal start of expression
        public int calcSum(int x, int y) {
        ^
MissingCurlyBraces.java:7: error: ';' expected
        public int calcSum(int x, int y) {
   .....

Отсутствие закрывающей фигурной скобки print Sum() является основной причиной проблемы.

Решение проблемы простое — добавление закрывающей фигурной скобки в метод printSum() :

package com.baeldung;

public class MissingCurlyBraces {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
    }
    public int calcSum(int x, int y) {
        return x + y;
    }
}

Прежде чем перейти к следующему разделу, давайте рассмотрим ошибку компилятора.

Компилятор сообщает, что 7-я строка вызывает ошибку “незаконное начало выражения”. На самом деле, мы знаем, что первопричина проблемы находится в 6-й строке. Из этого примера мы узнаем, что иногда ошибки компилятора не указывают на строку с основной причиной , и нам нужно будет исправить синтаксис в предыдущей строке.

3. Модификатор Доступа Внутри Метода

В Java мы можем объявлять локальные переменные только внутри метода или конструктора . Мы не можем использовать модификатор доступа для локальных переменных внутри метода, поскольку их доступность определяется областью действия метода.

Если мы нарушим правило и у нас будут модификаторы доступа внутри метода, возникнет ошибка “незаконное начало выражения”.

Давайте посмотрим на это в действии:

package com.baeldung;

public class AccessModifierInMethod {
    public void printSum(int x, int y) {
        private int sum = x + y; 
        System.out.println("Calculation Result:" + sum);
    }
}

Если мы попытаемся скомпилировать приведенный выше код, мы увидим ошибку компиляции:

$ javac AccessModifierInMethod.java 
AccessModifierInMethod.java:5: error: illegal start of expression
        private int sum = x + y;
        ^
1 error

Удаление модификатора private access легко решает проблему:

package com.baeldung;

public class AccessModifierInMethod {
    public void printSum(int x, int y) {
        int sum = x + y;
        System.out.println("Calculation Result:" + sum);
    }
}

4. Вложенные методы

Некоторые языки программирования, такие как Python, поддерживают вложенные методы. Но, Java не поддерживает метод внутри другого метода.

Мы столкнемся с ошибкой компилятора “незаконное начало выражения”, если создадим вложенные методы:

package com.baeldung;

public class NestedMethod {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
        public int calcSum ( int x, int y) {
            return x + y;
        }
    }
}

Давайте скомпилируем приведенный выше исходный файл и посмотрим, что сообщает компилятор Java:

$ javac NestedMethod.java
NestedMethod.java:6: error: illegal start of expression
        public int calcSum ( int x, int y) {
        ^
NestedMethod.java:6: error: ';' expected
        public int calcSum ( int x, int y) {
                          ^
NestedMethod.java:6: error:  expected
        public int calcSum ( int x, int y) {
                                   ^
NestedMethod.java:6: error: not a statement
        public int calcSum ( int x, int y) {
                                        ^
NestedMethod.java:6: error: ';' expected
        public int calcSum ( int x, int y) {
                                         ^
5 errors

Компилятор Java сообщает о пяти ошибках компиляции. В некоторых случаях одна ошибка может привести к нескольким дальнейшим ошибкам во время компиляции.

Выявление первопричины имеет важное значение для того, чтобы мы могли решить эту проблему. В этом примере первопричиной является первая ошибка “незаконное начало выражения”.

Мы можем быстро решить эту проблему, переместив метод calcSum() из метода print Sum() :

package com.baeldung;

public class NestedMethod {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
    }
    public int calcSum ( int x, int y) {
        return x + y;
    }
}

5. символ или строка Без кавычек

Мы знаем, что String литералы должны быть заключены в двойные кавычки, в то время как char значения должны быть заключены в одинарные кавычки.

Если мы забудем заключить их в соответствующие кавычки, компилятор Java будет рассматривать их как имена переменных .

Мы можем увидеть ошибку “не удается найти символ”, если “переменная” не объявлена.

Однако если мы забудем дважды заключить в кавычки Строку , которая не является допустимым именем переменной Java , компилятор Java сообщит об ошибке “незаконное начало выражения” .

Давайте посмотрим на это на примере:

package com.baeldung;

public class ForgetQuoting {
    public int calcSumOnly(int x, int y, String operation) {
        if (operation.equals(+)) {
            return x + y;
        }
        throw new UnsupportedOperationException("operation is not supported:" + operation);
    }
}

Мы забыли процитировать строку |//+ внутри вызова метода equals , и + , очевидно, не является допустимым именем переменной Java.

Теперь давайте попробуем его скомпилировать:

$ javac ForgetQuoting.java 
ForgetQuoting.java:5: error: illegal start of expression
        if (operation.equals(+)) {
                              ^
1 error

Решение проблемы простое — обертывание String литералов в двойные кавычки:

package com.baeldung;

public class ForgetQuoting {
    public int calcSumOnly(int x, int y, String operation) {
        if (operation.equals("+")) {
            return x + y;
        }
        throw new UnsupportedOperationException("operation is not supported:" + operation);
    }
}

6. Заключение

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

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

Тем не менее, мы все еще можем время от времени сталкиваться с этой ошибкой. Поэтому хорошее понимание ошибки поможет нам быстро найти и исправить ошибку.

//————————————————-
файл SPMainWin.h

#include «SPSettings.h»

void InitSettings();

//————————————————-
файл SPMainWin.cpp

#include «SPMainWin.h»

void InitSettings()
{
MainSettings.SCREEN_WIDTH = 640;
MainSettings.SCREEN_HEIGHT = 480;
MainSettings.TITLE = «SP»;
}

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
InitSettings();
}

//————————————————-

файл SPSettings.h

#pragma once

#include <string>

class SPSettings {

public:
SPSettings(void);
~SPSettings(void);

typedef std::basic_string<char> TITLE;
typedef unsigned int SCREEN_WIDTH;
typedef unsigned int SCREEN_HEIGHT;
};

extern SPSettings MainSettings;
//————————————————-
файл SPSettings.cpp

#include «SPSettings.h»

SPSettings MainSettings;

SPSettings::SPSettings(void)
{
}

SPSettings::~SPSettings(void)
{
}
//————————————————-

Получаю ошибку

SPMainWin.cpp(20): error C2274: ‘function-style cast’ : illegal as right side of ‘.’ operator
SPMainWin.cpp(21): error C2274: ‘function-style cast’ : illegal as right side of ‘.’ operator
SPMainWin.cpp(22): error C2274: ‘function-style cast’ : illegal as right side of ‘.’ operator

Может подскажете — в чем я не прав?

Describe the bug
After successful connection, the following call throws an error:

result = conn.call("RFC_READ_TABLE", QUERY_TABLE='REPOSRC', DELIMITER='|', FIELDS = ['PROGNAME'], OPTIONS=[{'TEXT':"PROGNAME = 'ZZ_TEST'"}], ROWCOUNT = 1000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "src/pyrfc/_pyrfc.pyx", line 500, in pyrfc.pyrfc.Connection.call
  File "src/pyrfc/_pyrfc.pyx", line 332, in pyrfc.pyrfc.Connection._error
pyrfc._exception.ABAPRuntimeError: RFC_ABAP_RUNTIME_FAILURE (rc=3): key=ASSIGN_CASTING_ILLEGAL_CAST, message=Error with ASSIGN ... CASTING in program SAPLSDTX                                . [MSG: class=, type=, number=, v1-4:=;;;]

To Reproduce

from pyrfc import Connection
conn = Connection(ashost='XXX', sysnr='00', client='100', user='XXX', passwd='XXX')
result = conn.call("RFC_READ_TABLE", QUERY_TABLE='REPOSRC', DELIMITER='|', FIELDS = ['PROGNAME'], OPTIONS=[{'TEXT':"PROGNAME = 'ZBC_ACTT_EXTRACT'"}], ROWCOUNT = 1000)

I have tested this by calling several other tables and noticed that the issue only occurs if the table has a field with data type rawstring (RSTR) / xstring.

Environment

  • OS: x86_64 GNU/Linux
  • Running in docker? Yes, but get the same result outside of docker
  • PyRFC version = 2.4.1 using NWRFC SDK 7.5 PL 8

Я получаю ошибку, illegal cast: from 'int' to 'FIELDS' при инициализации структурных переменных здесь: —

SOCKET_LOG_DATA socket_log_data() : fields(0), socket_number(0) {}

Как я должен решить это?

typedef PACKED struct PACKED_SUFFIX
{
UINT16 loss_reason : 1;
UINT16 unused : 15;
} LOSS_REASON;

typedef union PACKED_SUFFIX
{
LOSS_REASON loss;
UINT16 all_fields;
} FIELDS;

typedef PACKED struct PACKED_SUFFIX SOCKET_LOG_DATA
{
FIELDS fields;
UINT16 socket_number;

// As per @Dietrich's & @crashmstrcomments:-
SOCKET_LOG_DATA() : fields{{0, 0}}, socket_number(0) {}
} SOCKET_LOG_DATA;

Дал много ошибок: —

".filename.h", line 183: error (dplus:1207): syntax error near }
".filename.h", line 183: error (dplus:1463): type expected in arg-declaration-clause
".filename.h", line 183: error (dplus:1263): identifier socket_number already declared
".filename.h", line 183: error (dplus:1376): function int socket_number(void) is not a member of class $incomplete SOCKET_LOG_DATA
".filename.h", line 183: error (dplus:1247): syntax error after fields, expecting (
".filename.h", line 183: error (dplus:1404): mem initializers only allowed for constructors
".filename.h", line 183: error (dplus:1247): syntax error after 0, expecting ;

Тогда я сохранил socket_log_data() конструктор, изменив строку на

SOCKET_LOG_DATA socket_log_data() : fields{{0, 0}}, socket_number(0) {}

, и получил следующие ошибки: —

".filename.h", line 183: error (dplus:1272): member $incomplete SOCKET_LOG_DATA::fields used outside non-static member function
".filename.h", line 183: error (dplus:1125): int constant expected
".filename.h", line 183: error (dplus:1536): bitfields must be integral type
".filename.h", line 183: error (dplus:1247): syntax error after fields, expecting ;
".filename.h", line 183: error (dplus:1436): syntax error - declarator expected after }
".filename.h", line 183: error (dplus:1461): type expected for socket_number
".filename.h", line 183: error (dplus:1247): syntax error after ), expecting ;
".filename.h", line 186: error (dplus:1461): type expected for SOCKET_LOG_DATA

1

Решение

Вы инициализируете union с одним int:

: fields(0)

Вы можете инициализировать первый член объединения следующим образом:

: fields{{0, 0}}

В конструкторе есть что-то подозрительное:

SOCKET_LOG_DATA socket_log_data() ...

Обычно это было бы просто:

SOCKET_LOG_DATA() ...

5

Другие решения

Связанный запрос

http://stackoverflow.com/questions/35549540/identifier-int-not-a-direct-member-of-struct-socket-log-data/35555783#35555783

Я исправил это с помощью правильной инициализации конструктора и размещения переменных-членов следующим образом:

typedef struct fields
{
UINT16 loss_reason : 1;
UINT16 unused : 15;
} FIELDS;

typedef union fields_union
{
UINT16 all_fields;
FIELDS ref_fields;
fields_union() : all_fields(0), ref_fields() {}
} FIELDS_UNION;

typedef struct socket_log_data
{
FIELDS_UNION ref_fields_union;
UINT16 socket_number;
socket_log_data() : socket_number(0), ref_fields_union() {}
} SOCKET_LOG_DATA;

Спасибо за ваши предложения!

1

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ilife v8s ошибка e41
  • Ilife v80 ошибка e41
  • Ilife v55 робот пылесос ошибка e04
  • Ilife v55 ошибка е06 что делать

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

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