Syntax error insert to complete methodbody

I've spent a couple hours just trying to solve this syntax error but it's defeating me in every way. I tried putting closing brackets at the end, in between various blocks but nothing would work. T...

I’ve spent a couple hours just trying to solve this syntax error but it’s defeating me in every way. I tried putting closing brackets at the end, in between various blocks but nothing would work. This is for a class assignment, it’s pretty much finished but this error is keeping me from actually submitting it.

public class Coffee {

    public static void main(String[] args) {
        // Default Constructor 
        public Coffee() {
            this.sugar = 0.0;
            this.milk = 0;
            this.currentlyHot = false;

        }  

        //Instance Variables        
        private double sugar;
        private int milk;
        private boolean currentlyHot; // hot
        private int size;

        // Constructor        
        public Coffee (double id, int dairy, boolean temp) {
            this.sugar = id;
            this.milk = dairy;
            this.currentlyHot = temp;        
        }

        // (setter)
        public void setSugar(double id) {
            sugar = id;
        }
        public void setMilk(int dairy) {
            milk = dairy;
        }       
        public void setSize(boolean temp) {
            currentlyHot = temp;
        }

        public void setHeat(boolean isHot) {
            this.currentlyHot = isHot;
        }

        //(getter)  
        public double getSugar() {
            return this.sugar;
        }

        public int getMilk() {
            return this.milk;
        }

        public boolean checkcurrentlyHot() {
            return this.currentlyHot;
        }

        public int getSize() {
            return this.size;
        }

        // Method to display data
        public void display() {
            System.out.println("You have " + sugar + " sugar in your cup");
            System.out.println("You have " + getMilk() + " in your coffee");
            System.out.println("That's a " + getSize() + " ounce cup");
            System.out.println("Is the cup hot? " + checkcurrentlyHot());            


        }

    }

asked Jul 24, 2017 at 2:55

Charles1932's user avatar

5

You can not have your constructor and other code in your main menthod

public static void main(String[] args) {
    // Default Constructor 
    public Coffee() {   // move this code
    ....
    }
    ....
}

Your probably want to have your main as

public static void main(String[] args) {

      Coffee c = new Coffee ();  // or use the other constructor
      c.display ();
}

answered Jul 24, 2017 at 2:58

Scary Wombat's user avatar

Scary WombatScary Wombat

44.5k5 gold badges34 silver badges64 bronze badges

You have put everything in the main method. The constructor, the property declaration, the method declaration. Also there is a missing end brace at the end. Move the constructor, variable and method declaration out of the main method.

answered Jul 24, 2017 at 3:00

yaswanth's user avatar

yaswanthyaswanth

2,2291 gold badge20 silver badges30 bronze badges

Instance methods and variables are declared in main(), it’s not possible in Java. Take it out of main, It will work.

class Coffee {

      public Coffee() {
          this.sugar = 0.0;
          this.milk = 0;
          this.currentlyHot = false;

      }  

      //Instance Variables        
      private double sugar;
      private int milk;
      private boolean currentlyHot; // hot
      private int size;

      // Constructor        
      public Coffee (double id, int dairy, boolean temp) {
          this.sugar = id;
          this.milk = dairy;
          this.currentlyHot = temp;        
      }

      // (setter)
      public void setSugar(double id) {
          sugar = id;
      }
      public void setMilk(int dairy) {
          milk = dairy;
      }       
      public void setSize(boolean temp) {
          currentlyHot = temp;
      }

      public void setHeat(boolean isHot) {
          this.currentlyHot = isHot;
      }

      //(getter)  
      public double getSugar() {
          return this.sugar;
      }

      public int getMilk() {
          return this.milk;
      }

      public boolean checkcurrentlyHot() {
          return this.currentlyHot;
      }

      public int getSize() {
          return this.size;
      }

      // Method to display data
      public void display() {
          System.out.println("You have " + sugar + " sugar in your cup");
          System.out.println("You have " + getMilk() + " in your coffee");
          System.out.println("That's a " + getSize() + " ounce cup");
          System.out.println("Is the cup hot? " + checkcurrentlyHot());            


      }

    public static void main(String[] args) {
        // Default Constructor 


    }
} 

answered Jul 24, 2017 at 2:59

Dark Knight's user avatar

Dark KnightDark Knight

8,1104 gold badges35 silver badges58 bronze badges

2

Содержание

  1. Issues in Integrating Authorize.net API’s
  2. syntax error: insert > to complete ClassBody
  3. 11 Answers 11
  4. Syntax error, insert «>» to complete ClassBody? [closed]
  5. 4 Answers 4
  6. Android проверьте подключение к Интернету [дубликат]
  7. 20 ответы
  8. Java Hungry
  9. 3 ways to fix «illegal start of expression» error in java
  10. 1. Missing curly braces
  11. 2. Method inside Method
  12. 3. Public, private or protected access modifier inside method

I’m integrating the Authorized.net Gateway to my Android application. To test the feature:

1) I downloaded the SDK anet_android_sdk-1.3.0.

2) Compiled the anet_android_sdk-1.3.0, it complained about the missing jar file anet-java-sdk-android-2.0.4. I modified the project to include anet-java-sdk-android-2.0.5 jar file. With that the compilation went successfully.

3) anet_android_sdk. Executable jar file was created successfully in the Bin Directlry.

4) I proceeded for the example program

On compiling the Sample code there was alot of WEIRD error thrown by the compiler which are really adsurb.

Syntax error on token «(«, ; expected ExampleActiviy.java /Authorize Android Example/src/net/authorize line 116 Java Problem

Syntax error on token(s), misplaced construct(s) ExampleActiviy.java /Authorize Android Example/src/net/authorize line 116 Java Problem

Syntax error on tokens, delete these tokens ExampleActiviy.java /Authorize Android Example/src/net/authorize line 120 Java Problem

Syntax error, insert «;» to complete BlockStatements ExampleActiviy.java /Authorize Android Example/src/net/authorize line 120 Java Problem

Syntax error, insert «;» to complete Statement ExampleActiviy.java /Authorize Android Example/src/net/authorize line 48 Java Problem

Syntax error, insert «>» to complete Block ExampleActiviy.java /Authorize Android Example/src/net/authorize line 120 Java Problem

Syntax error, insert «>» to complete ClassBody ExampleActiviy.java /Authorize Android Example/src/net/authorize line 120 Java Problem

Syntax error, insert «>» to complete MethodBody ExampleActiviy.java /Authorize Android Example/src/net/authorize line 120 Java Problem

Syntax error, insert «else Statement» to complete IfStatement ExampleActiviy.java /Authorize Android Example/src/net/authorize line 120 Java Problem

Assuming that there is some error, I downloaded the SampleProgram code from your url and after quite hardship was able to compile.

But unfortunately when I ran the app «Sdk Test Harness» it just threw the exception and closed.

Источник

syntax error: insert > to complete ClassBody

I created a method and keep getting an error that I need to include a > at the end of my method. I put the > in and the error is still there! If I then delete that > the same error will pop up on a prior method; and that error wasn’t there before. in other words, if i type the > on my most recent method then the error stays there and only there. if i delete it, it duplicates that error on my prior method.

11 Answers 11

You really want to go to the top of your file and do proper and consistent indention all the way to the bottom.

Odds are, somewhere along the line, you are missing a >. Your description isn’t super clear, but if the code you posted is how you actually have it formatted in your file then odds are you just missed something somewhere. and poor indentation makes it very hard to spot.

The fact that the message is changing is confusing, but it is the sort of thing you see in these cases.

the error might be misleading. In my case i had incorrect/incomplete comment statements such as below which is broken lead to this error:

Fixing the comments fixed the error. Hope this helps. Thanks.

I think this can be caused by a number of different problems. 🙁

In my case it was that I have forgotten to specify the type of two parameters in one of my methods declareations. To fix I had to change this: onUpgrade(SQLiteDatabase pDb, pOldVersion, pNewVersion) <

> to this: onUpgrade(SQLiteDatabase pDb, int pOldVersion, int pNewVersion)

It might be due to invisible Chars when copying code from PDF ebook. Be careful of the little red dot ‘.’

Choose ‘Select First Character’ -> then delete it.

Also, the same error might occur if you accidentally write an if-statement outside of a method. I kept overlooking it since I was looking at the bracket-matching only.

I just simply add another»>»,makes as «>>»,then problem solved

I didnt have to put anther «>» for my other java code exercise.

Im a java beginner,I’ve come across same problem so I searched online found this thread.Hope this help

Had the same problem. Turned out to be a very fundamental oversight. I was having the properties of a class declared like this:

The mistake was i had been instantiating the foo and bar variables outside the functions of the class. When I put the

into their proper functions (like below), the error went away.

I got this error due to a missing .

Here are the steps.

  1. Just copy paste your code in notepad
  2. Remove copy from Java file
  3. Again copy notepad and paste into Java file.
  4. An error will be gone.

This question have already accepted answer but still there are some other problems where it occurs (like even though all statements are there correctly sometimes we will get this issue) and there are solutions too.

Recently I came across like this situation in eclipse workspace.

The solution is

  1. Take the back up of that java file.
  2. Remove the java file from that location and do the build/compile
  3. Paste the file in the same location and do the build/compile
  4. If the above step 3 does not work create new file and paste the content/code from backup file and do the build/compile
  5. If the above step 3&4 both are not working then type the code of that file manually end-to-end and do the build/compile

Источник

Syntax error, insert «>» to complete ClassBody? [closed]

This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.

Closed last year .

For some reason I get a syntax error that says, «Syntax error, insert «>» to complete ClassBody.» I checked every method, every statement to make sure I have complete opening and closing brackets, so I don’t know why this is happening. Can anybody tell me why I might be getting this issue?

Copying the code into another file doesn’t fix the problem, nor does going to Project > Clean.

4 Answers 4

Try removing (or commenting out) one method and see if the problem persists. If it does, remove or comment out an additional method, and so on, until the error disappears. Then restore everything but the last method.

If the error doesn’t reappear, the problem is probably in that last method.

If it does reappear, the problem is more subtle; perhaps a control character embedded in the code. Try copying and pasting the code into a text-only editor (so any control characters will be ignored, save it, and recompiling.

I too had this error. There are NO errors in the code above (when I used the code above as as a sub class). I corrected my error by cleaning up my IDE’s workspace and making sure the caller was working properly.

  • Project settings
  • Run settings
  • Made sure that main was listed properly
  • public static void main(String[] args)

I have faced the similar problem, solved it by deleting the class file and then recreated the file again and pasted the same code. It worked.

Источник

Android проверьте подключение к Интернету [дубликат]

Я хочу создать приложение, использующее Интернет, и я пытаюсь создать функцию, которая проверяет, доступно ли соединение, а если нет, перейдите к действию с кнопкой повтора и объяснением.

Приложен мой код, но я получаю сообщение об ошибке Syntax error, insert «>» to complete MethodBody.

Теперь я помещал их, пытаясь заставить его работать, но пока не повезло . Любая помощь будет оценена.

задан 05 марта ’12, 16:03

Лучший ответ находится здесь stackoverflow.com/a/27312494/1708390 . Просто пингуйте и посмотрите, действительно ли устройство подключено к Интернету — Bugs Happen

Если кто-то хочет проверить официальный документ ConnectivityManager, можно посетить: developer.android.com/training/monitoring-device-state/… — Kalu Khan Luhar

20 ответы

Этот метод проверяет, подключен ли мобильный телефон к Интернету, и возвращает true, если он подключен:

Редактировать: Этот метод фактически проверяет, подключено ли устройство к Интернету (возможно, оно подключено к сети, но не к Интернету).

ответ дан 23 авг.

Это неверный ответ. Если вы подключены к сети, которая не ведет к Интернету, этот метод неверно вернет true. Обратите внимание, что javadoc getActiveNetworkInfo говорит, что вам следует проверить NetworkInfo.isConnected (), но этого также недостаточно для проверки того, что вы в Интернете. Я изучаю это дальше, но вам, возможно, придется пинговать сервер в Интернете, чтобы убедиться, что вы действительно в Интернете. — Мигель

Проверяет ли он 3G, EDGE, GPRS, . тоже? — Доктор Джеки

будьте осторожны с isInternetAvailable (), поскольку он может дать сбой в исключениях «сеть в основном потоке» и, таким образом, вернуть false, даже если у вас есть соединение. — Орен

isInternetAvailable () всегда возвращает false для меня. Даже при обходе улова. Я в сети 3G. — Истер

Первая часть работает в основном потоке, вторая часть (редактирование) работает, только если не в основном потоке. — Dale

Убедитесь, что он «подключен» к сети:

Убедитесь, что он «подключен» к Интернету:

ответ дан 18 авг.

Как найти подключенные к Wi-Fi, но не активные данные по Wi-Fi. — Ганеш Катикар

Сообщает только, если вы подключены к сети, а не к Интернету. Если вам нужны сбои (для безопасного кода в Интернете), используйте это. — Оливер Диксон

Чем это отличается от принятого ответа? — Сешу Винай

@SeshuVinay Прочтите дату. Я разместил это более 4 лет назад. — Джаред Берроуз

Мое тестовое устройство, похоже, кеширует IP-адрес сервера Google, поэтому isInternetAvailable всегда возвращает true. Можно использовать другой сервер, но это не очень надежно. Могу я что-нибудь сделать с кешированием? — Мартин Браун

Вы можете просто проверить связь с интернет-сайтом, например google:

Хороший, но не лучший. Вся логика зависит от google.com, давайте предположим, что если Google не работает в течение нескольких минут, ваше приложение не будет работать в течение нескольких минут — Зишан Шабир

так что вы предлагаете? — Ошибки случаются

Что ж, @ZeeshanShabbir прав, солнечная вспышка в той части страны, где работает Google, вынудит ваше приложение прямо из парка мячей, в таком сценарии вы могли бы, вероятно, пинговать несколько адресов, чтобы проверить то же самое. Кроме того, я думаю, что Google не выйдет из строя, если один из центров выйдет из строя, большинство из них должны быть отключены, чтобы это работало, также при условии, что ваш сетевой оператор переживет всемирное отключение: D — Аниматрикс

Если ваше приложение полагается на удаленный сервер (для аутентификации, получения данных, связи с базой данных и т. Д.), Вы можете использовать этот адрес сервера вместо Google, таким образом вы можете одновременно проверить подключение к Интернету и доступность сервера. время. Если ваш сервер не работает, но подключение к Интернету все еще есть, приложение все равно не будет работать должным образом. В этом случае вы также можете установить интервал тайм-аута для команды ping, используя -i такой вариант ping -i 5 -c 1 www.myserver.com . — малина

Будет ли этот метод ложно возвращать истину в сценариях, где есть страница входа в Wi-Fi? — Роймунсон

Вышеупомянутые методы работают, когда вы подключены к источнику Wi-Fi или через пакеты данных сотового телефона. Но в случае подключения к Wi-Fi бывают случаи, когда вас дополнительно просят войти в систему, как в кафе. Так что в этом случае ваше приложение выйдет из строя, поскольку вы подключены к источнику Wi-Fi, но не подключены к Интернету.

Этот метод работает нормально.

Пожалуйста, используйте это в отдельном потоке от основного потока, поскольку он выполняет сетевой вызов и генерирует исключение NetwrokOnMainThreadException, если не выполняется.

А также не помещайте этот метод внутрь onCreate или любого другого метода. Поместите его в класс и получите к нему доступ.

ответ дан 15 окт ’14, 13:10

Это хороший подход к проблеме. Но наверное пинга хватит — дазито

Трудности, связанные с потоковой передачей, когда вам просто нужно просто проверить ответ в Интернете, не стоят усилий. Ping выполняет свою работу без всяких усилий. — МбайМбуру

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

Это будет полезно в обоих случаях, чтобы вы могли проверить, какие Тип СЕТЕВОГО подключения доступно, так что вы можете выполнять свой процесс таким образом.

Вам просто нужно скопировать следующий класс и вставить прямо в свой пакет.

Теперь вы можете использовать как:

НЕ ЗАБЫВАЙТЕ РАЗРЕШЕНИЕ 🙂 🙂

Вы можете изменить в соответствии с вашими требованиями.

Источник

Java Hungry

Java developers tutorials and coding.

3 ways to fix «illegal start of expression» error in java

«illegal start of expression» error is one of the most common errors, java beginners face. This error arises during compile time i.e running javac command. Usually , java compiler compiles from top to bottom and left to right in a source code file. There are 3 ways in which we can get «illegal start of expression» error.

1. Missing curly braces
2. Method inside method
3. public, protected or private access modifier inside method

Let’s check them out one by one.

1. Missing curly braces

«illegal start of expression» arises if you forgot to add curly braces. In the below example, I do not add the closing curly brace > of the main method.

If you are using eclipse ide then you will get below error for the above code :

If you add closing curly brace to the main method , then the above code will work fine .

2. Method inside Method

In java , one method can not be inside the another method. If you try to put it, then you will get illegal start of expression error as shown below:

3. Public, private or protected access modifier inside method

Variable inside the method is called local variable. In case of local variable you can not use any access modifier.
An access modifier is not allowed inside the method because its accessibility is defined by its method scope.

One solution is to move the declaration of local variable outside the method.

If you run the above code in the eclipse ide, you will get the following error as shown in the image:

Eclipse ide is providing better information about the error then the java compiler.

That’s all for the day. Today I discussed various ways to get Illegal start of expression error and how to fix it. Please post the code in the comments if you are facing the same error.

Источник

Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

The «illegal start of expression» error is a compile-time error when the compiler finds an inappropriate statement in the code. The java compiler, javac, compile your source code from top to bottom, left to right and when it sees something inappropriate at the start of an expression, it throws an «illegal start of expression» error. The most common reason for this is a missing semi-colon. You might know that every statement in Java ends with a semicolon, but if you forget one, you won’t get an error that there is a missing semi-colon at the end of the statement because the compiler doesn’t know the end.

When the compiler checks the next statement it sees an illegal start because an earlier statement was not terminated. The bad part is that you can get tens of «illegal start of expression» errors by just omitting a single semi-colon or missing braces, as shown in the following example.

public class Main {

  public static void main(String[] args) {
    count();
  

  public static int count() {
    return 0;
  }

}

If you compile this program you will be greeted with several «illegal start of expression» error as shown below:

$ javac Main.java

Main.java:7: error: illegal start of expression

  public static int count() {
  ^

Main.java:7: error: illegal start of expression

  public static int count() {
         ^
Main.java:7: error: ‘;’ expected
  public static int count() {
               ^
Main.java:7: error: ‘;’ expected
  public static int count() {
                           ^
Main.java:11: error: reached end of file while parsing
}
 ^
5 errors

And the only problem is missing curly braces in the main method, as soon as you add that missing closing curly brace in the main method the code will work fine and all these errors will go away, as shown below:

How to fix "illegal start of expression" error in Java

The error message is very interesting, if you look at the first one, you will find that error is in line 7 and the compiler complaining about a public keyword but the actual problem was in line 5 where a closing brace is missing. 

From the compiler’s view, the public should not come there because it’s an invalid keyword inside a method in Java, remember without closing braces main() is still not closed, so the compiler thinks the public keyword is part of the main() method.

Though, when you compile the same program in Eclipse, you get a different error because its the compiler is slightly different than javac but the error message is more helpful as you can see below:

Exception in thread «main» java.lang.Error: Unresolved compilation problem:
Syntax error, insert «}» to complete MethodBody

at Main.main(Main.java:4)

In short, the «illegal start of expression» error means the compiler find something inappropriate, against the rules of Java programming but the error message is not very helpful. For «illegal start of expression» errors, try looking at the lines preceding the error for a missing ‘)’ or ‘}’ or missing semicolon. 

Also remember, a single syntax error somewhere can cause multiple «illegal start of expression» errors. Once you fix the root cause, all errors will go away. This means always recompile once you fix an error, don’t try to make multiple changes without compilation.

Other Java troubleshooting guides you may like:

  • How to fix «variable might not have been initialized» error in Java? (solution)
  • Could not create the Java virtual machine Invalid maximum heap size: -Xmx (solution)
  • How to fix class, enum, or interface expected error in Java? (solution)
  • How to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory (solution)
  • Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger in Java (solution)
  • Error: could not open ‘C:Javajre8libamd64jvm.cfg’ (solution)
  • java.lang.OutOfMemoryError: Java heap space : Cause and Solution (steps)
  • How to avoid ConcurrentModificationException while looping over List in Java? (solution)

DromHour

0 / 0 / 0

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

Сообщений: 11

1

Ошибка в синтаксисе

06.08.2017, 10:09. Показов 1214. Ответов 7

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


Java
1
Thread adder = new Thread(){/*TEST*/};

Идёт без ошибок, но стоит записать код:

Java
1
Thread adder = new Thread(){output.setText("test");};

Как начинает идти всё и вся:

Multiple markers at this line
— Syntax error on token «}», delete this token
— Syntax error, insert «}» to complete ClassBody
— Syntax error, insert «;» to complete MethodDeclaration
— Syntax error, insert «)» to complete MethodDeclaration
— Syntax error, insert «Identifier (» to complete
MethodHeaderName

Добавлено через 11 минут

Java
1
Thread adder = new Thread(){{output.setText("test");}};

Как оказалось, я просто забыл создать блок.

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



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

06.08.2017, 10:09

Ответы с готовыми решениями:

Ошибка в синтаксисе
//——————————————————————————
#ifndef TButGroupH…

Ошибка в синтаксисе
&lt;?php

if (isset($siteuri)) {$siteuri=&quot;da&quot;;} else {$siteuri=&quot;nu&quot;;}
if (isset($carti))…

Ошибка в синтаксисе
Задача : Вася, Юля и Петя решили организовать праздничную вечеринку. Они пригласили в гости Женю с…

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

7

korvin_

Эксперт Java

4016 / 2618 / 475

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

Сообщений: 8,422

06.08.2017, 15:20

2

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

Java
1
Thread adder = new Thread(){{output.setText("test");}};

Зачем вообще так извращаться?



0



xave

17 / 17 / 3

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

Сообщений: 34

08.08.2017, 01:50

3

Можно намного красивее

Java
1
Thread adder = new Thread(() -> output.setText("test"));



0



Эксперт Java

4016 / 2618 / 475

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

Сообщений: 8,422

08.08.2017, 07:36

4

xave, это совершенно другой код по смыслу. Впрочем, возможно, ТСу нужен именно он, на самом деле.



0



17 / 17 / 3

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

Сообщений: 34

08.08.2017, 12:58

5

korvin_,
Почему же. ТС переопределяет для run() для класса Thread, поскольку он Runnable(), а я фактически инстанцирую Thread экземпляром Runnable, где run() задан лямбдой. Обе вещи просто добавляют реализацию в run().



0



korvin_

Эксперт Java

4016 / 2618 / 475

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

Сообщений: 8,422

08.08.2017, 15:26

6

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

ТС переопределяет для run() для класса Thread

Нет. Он не это делает. Он задаёт блок инициализации объекта.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public final class Syntax {
 
    public static void main(String[] args) throws InterruptedException {
        final Output output = new Output();
        
        final Thread adder0 = new Thread(){{output.setText("adder0 init");}};
        output.println();
 
        final Thread adder1 = new Thread(() -> output.setText("adder1 runnable"));
        output.println();
        
        adder0.start();
        adder0.join();
        output.println();
        
        adder1.start();
        adder1.join();
        output.println();
    }
    
    private static final class Output {
        
        private String text = "";
        
        String getText() {
            return text;
        }
        
        void setText(String text) {
            this.text = text;
        }
        
        void println() {
            System.out.println(text);
        }
    }
}



0



ViktorFX

528 / 263 / 70

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

Сообщений: 1,223

10.08.2017, 12:06

7

korvin_,

Java
1
2
final Thread adder0 = new Thread(){{output.setText("adder0 init");}};
final Thread adder1 = new Thread(() -> output.setText("adder1 runnable"));

Здесь по сути появляется некий анонимный класс, который имплементит(или наследует) класс Thread?
Двойные скобки {{}} понимаю как вы и говорили — блок инициализации внутри анонимного класса.
А вот почему мы можем использовать лямбду? Класс Thread ведь не функционал, вот если бы Runnable тогда понятно.



0



Эксперт Java

4016 / 2618 / 475

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

Сообщений: 8,422

10.08.2017, 12:11

8

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

А вот почему мы можем использовать лямбду? Класс Thread ведь не функционал, вот если бы Runnable тогда понятно.

https://docs.oracle.com/javase… .Runnable-



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

10.08.2017, 12:11

Помогаю со студенческими работами здесь

Ошибка в синтаксисе
Range(&quot;A5:E5&quot; &amp; Cells(Rows.Count, 1).End(xlUp).Row).Sort Key1:=Range(&quot;A5&quot;), _

Ошибка в синтаксисе
Добрый день!
Пытаюсь запустить в MySQL 8.0 следующий код, однако возникает сообщение о…

Ошибка в синтаксисе
Здравствуйте! такой вопрос устанавливаем скрипт на хостинг и парсер выдаёт ошибку

Parse error:…

Ошибка в синтаксисе
Привет! Очень мало работала в матлабе, срочно приходится разбираться, мне нужно решить задачу…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

8

Все официальные методы только говорят, открыто ли устройство для сети или нет,

Если ваше устройство подключено к Wi-Fi, но Wi-Fi не подключен к Интернету, этот метод не сработает (что происходит много раз). Никакой встроенный метод обнаружения сети не скажет об этом сценарии, поэтому был создан класс Async Callback, который вернется в onConnectionSuccess и onConnectionFail

new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() {

    @Override
    public void onConnectionSuccess() {
        Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFail(String msg) {
        Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show();
    }
}).execute();

Сетевой вызов из асинхронной задачи

public class CheckNetworkConnection extends AsyncTask < Void, Void, Boolean > {
    private OnConnectionCallback onConnectionCallback;
    private Context context;

    public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) {
        super();
        this.onConnectionCallback = onConnectionCallback;
        this.context = con;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(Void...params) {
        if (context == null)
            return false;

        boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context);
        return isConnected;
    }

    @Override
    protected void onPostExecute(Boolean b) {
        super.onPostExecute(b);

        if (b) {
            onConnectionCallback.onConnectionSuccess();
        } else {
            String msg = "No Internet Connection";
            if (context == null)
                msg = "Context is null";
            onConnectionCallback.onConnectionFail(msg);
        }

    }

    public interface OnConnectionCallback {
        void onConnectionSuccess();

        void onConnectionFail(String errorMsg);
    }
}

Фактический класс, который будет пинговать сервер

class NetWorkInfoUtility {

    public boolean isWifiEnable() {
        return isWifiEnable;
    }

    public void setIsWifiEnable(boolean isWifiEnable) {
        this.isWifiEnable = isWifiEnable;
    }

    public boolean isMobileNetworkAvailable() {
        return isMobileNetworkAvailable;
    }

    public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
        this.isMobileNetworkAvailable = isMobileNetworkAvailable;
    }

    private boolean isWifiEnable = false;
    private boolean isMobileNetworkAvailable = false;

    public boolean isNetWorkAvailableNow(Context context) {
        boolean isNetworkAvailable = false;

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
        setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());

        if (isWifiEnable() || isMobileNetworkAvailable()) {
            /*Sometime wifi is connected but service provider never connected to internet
            so cross check one more time*/
            if (isOnline())
                isNetworkAvailable = true;
        }

        return isNetworkAvailable;
    }

    public boolean isOnline() {
        /*Just to check Time delay*/
        long t = Calendar.getInstance().getTimeInMillis();

        Runtime runtime = Runtime.getRuntime();
        try {
            /*Pinging to Google server*/
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int exitValue = ipProcess.waitFor();
            return (exitValue == 0);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            long t2 = Calendar.getInstance().getTimeInMillis();
            Log.i("NetWork check Time", (t2 - t) + "");
        }
        return false;
    }
}


этот вопрос уже есть ответ здесь:

  • Как проверить доступ в интернет на Android? InetAddress не раз

    49 ответы

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

прилагается мой код до сих пор, но я получаю ошибку Syntax error, insert "}" to complete MethodBody.

теперь я помещаю их в попытке заставить его работать, но до сих пор не повезло… Любая помощь будет оценена по достоинству.

public class TheEvoStikLeagueActivity extends Activity {
private final int SPLASH_DISPLAY_LENGHT = 3000;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

private boolean checkInternetConnection() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {

return true;

/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
new Handler().postDelayed(new Runnable() {
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(TheEvoStikLeagueActivity.this, IntroActivity.class);
TheEvoStikLeagueActivity.this.startActivity(mainIntent);
TheEvoStikLeagueActivity.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
} else {
return false;

Intent connectionIntent = new Intent(TheEvoStikLeagueActivity.this, HomeActivity.class);
TheEvoStikLeagueActivity.this.startActivity(connectionIntent);
TheEvoStikLeagueActivity.this.finish();
}
}
}


1152  


20  

20 ответов:

этот метод проверяет, подключен ли мобильный телефон к интернету и возвращает true, если он подключен:

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return cm.getActiveNetworkInfo() != null;
}

в манифесте,

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Edit:
Этот метод фактически проверяет, подключено ли устройство к интернету (есть возможность, что оно подключено к сети, но не к интернету).

public boolean isInternetAvailable() {
    try {
        InetAddress ipAddr = InetAddress.getByName("google.com"); 
        //You can replace it with your name
            return !ipAddr.equals("");

        } catch (Exception e) {
            return false;
    }
}

убедитесь, что он «подключен» к сети:

public boolean isNetworkAvailable(Context context) {
    final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
    return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}

убедитесь, что он «подключен» к сети:

public boolean isInternetAvailable() {
    try {
        final InetAddress address = InetAddress.getByName("www.google.com");
        return !address.equals("");
    } catch (UnknownHostException e) {
        // Log error
    }
    return false;
}

разрешения, необходимые:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

https://stackoverflow.com/a/17583324/950427

вы можете просто пинговать онлайн-сайт, как google:

public boolean isConnected() throws InterruptedException, IOException
{
    String command = "ping -c 1 google.com";
    return (Runtime.getRuntime().exec(command).waitFor() == 0);
}

вышеуказанные методы работают, когда вы подключены к источнику Wi-Fi или через пакеты данных сотового телефона. Но в случае подключения Wi-Fi есть случаи, когда вас дополнительно просят войти в систему, как в кафе. Так что в этом случае ваше приложение не удастся, как вы подключены к источнику Wi-Fi, но не с Интернетом.

этот метод работает отлично.

    public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        try {
            URL url = new URL("http://www.google.com/");
            HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
            urlc.setRequestProperty("User-Agent", "test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1000); // mTimeout is in seconds
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            Log.i("warning", "Error checking internet connection", e);
            return false;
        }
    }

    return false;

}

пожалуйста, используйте это в отдельном потоке от основного потока, как это делает сетевой вызов и будет бросать NetwrokOnMainThreadException если не следовать.

а также не помещайте этот метод в onCreate или любой другой метод. Поместите его в класс и получите к нему доступ.

редактирование принятого ответа показывает, как проверить, можно ли что-то в интернете. Мне пришлось слишком долго ждать ответа, когда это было не так (с Wi-Fi, который не имеет подключения к интернету). К Сожалению InetAddress.getByName не имеет параметра timeout, поэтому следующий код работает вокруг этого:

private boolean internetConnectionAvailable(int timeOut) {
    InetAddress inetAddress = null;
    try {
        Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
            @Override
            public InetAddress call() {
                try {
                    return InetAddress.getByName("google.com");
                } catch (UnknownHostException e) {
                    return null;
                }
            }
        });
        inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
        future.cancel(true);
    } catch (InterruptedException e) {
    } catch (ExecutionException e) {
    } catch (TimeoutException e) {
    } 
    return inetAddress!=null && !inetAddress.equals("");
}

вы не можете создать метод внутри другого метода, перемещение private boolean checkInternetConnection() { способ из onCreate

вы можете использовать следующий фрагмент для проверки подключения к интернету.

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

вы просто должны скопировать следующий класс и вставить непосредственно в пакет.

/**
 * 
 * @author Pratik Butani
 * 
 */
public class InternetConnection {

    /** CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT */
    public static boolean checkConnection(Context context) {
        final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();

        if (activeNetworkInfo != null) { // connected to the internet
            Toast.makeText(context, activeNetworkInfo.getTypeName(), Toast.LENGTH_SHORT).show();

            if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                // connected to wifi
                return true;
            } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                // connected to the mobile provider's data plan
                return true;
            }
        }
        return false;
    }
}

Теперь вы можете использовать как:

if (InternetConnection.checkConnection(context)) {
    // Its Available...
} else {
    // Not Available...
}

Не забудьте взять разрешение :) :)

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

вы можете изменить на основе ваших требований.

спасибо.

все официальные методы только говорит, открыто ли устройство для сети или нет,

если ваше устройство подключено к Wi-Fi, но Wifi не подключен к интернету, то этот метод не будет работать (что происходит много раз), никакой встроенный метод обнаружения сети не расскажет об этом сценарии, поэтому созданный асинхронный класс обратного вызова, который вернется в onConnectionSuccess и onConnectionFail

        new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() {

            @Override
            public void onConnectionSuccess() {
   Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show();
            }

            @Override
            public void onConnectionFail(String msg) {
   Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show();
            }
        }).execute();

сетевой вызов из асинхронного режима Задача

public class CheckNetworkConnection extends AsyncTask<Void, Void, Boolean> {
private OnConnectionCallback onConnectionCallback;
private Context context;

public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) {
     super();
     this.onConnectionCallback = onConnectionCallback;
    this.context = con;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected Boolean doInBackground(Void... params) {
    if (context == null)
        return false;

    boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context);
    return isConnected;
}

@Override
protected void onPostExecute(Boolean b) {
    super.onPostExecute(b);

    if (b) {
        onConnectionCallback.onConnectionSuccess();
    } else {
        String msg = "No Internet Connection";
        if (context == null)
            msg = "Context is null";
        onConnectionCallback.onConnectionFail(msg);
    }

}

public interface OnConnectionCallback {
    void onConnectionSuccess();

    void onConnectionFail(String errorMsg);
}
}

фактический класс, который будет пинговать на сервер

class NetWorkInfoUtility {

public boolean isWifiEnable() {
    return isWifiEnable;
}

public void setIsWifiEnable(boolean isWifiEnable) {
    this.isWifiEnable = isWifiEnable;
}

public boolean isMobileNetworkAvailable() {
    return isMobileNetworkAvailable;
}

public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
    this.isMobileNetworkAvailable = isMobileNetworkAvailable;
}

private boolean isWifiEnable = false;
private boolean isMobileNetworkAvailable = false;

public boolean isNetWorkAvailableNow(Context context) {
    boolean isNetworkAvailable = false;

    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
    setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());

    if (isWifiEnable() || isMobileNetworkAvailable()) {
        /*Sometime wifi is connected but service provider never connected to internet
        so cross check one more time*/
        if (isOnline())
            isNetworkAvailable = true;
    }

    return isNetworkAvailable;
}

public boolean isOnline() {
    /*Just to check Time delay*/
    long t = Calendar.getInstance().getTimeInMillis();

    Runtime runtime = Runtime.getRuntime();
    try {
        /*Pinging to Google server*/
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        long t2 = Calendar.getInstance().getTimeInMillis();
        Log.i("NetWork check Time", (t2 - t) + "");
    }
    return false;
 }
}

не нужно быть сложным. Самый простой и рамочный способ-использовать ACCESS_NETWORK_STATE разрешение и просто сделать подключенный метод

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

вы также можете использовать requestRouteToHost Если у вас есть particualr хост и тип подключения (wifi/mobile) в виду.

вы должны:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

в вашем манифесте android.

для более подробной информации иди сюда

использовать этот метод:

public static boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

это разрешение требуется:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

попробуйте следующий код:

public static boolean isNetworkAvailable(Context context) {
        boolean outcome = false;

        if (context != null) {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo[] networkInfos = cm.getAllNetworkInfo();

            for (NetworkInfo tempNetworkInfo : networkInfos) {


                /**
                 * Can also check if the user is in roaming
                 */
                if (tempNetworkInfo.isConnected()) {
                    outcome = true;
                    break;
                }
            }
        }

        return outcome;
    }

в манифесте

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

в коде

public static boolean isOnline(Context ctx) {
    if (ctx == null)
        return false;

    ConnectivityManager cm =
            (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

после оператора «return» вы не можете написать код(исключая блок try-finally).
Переместите новые коды действий перед операторами «return».

public boolean checkInternetConnection(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context
        .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++){
                if (info[i].getState()==NetworkInfo.State.CONNECTED){
                    return true;
                }
            }
        }
    }
    return false;
}

используйте этот код для проверки подключения к интернету

ConnectivityManager connectivityManager = (ConnectivityManager) ctx
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if ((connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
                || (connectivityManager
                        .getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
                        .getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                        .getState() == NetworkInfo.State.CONNECTED)) {
            return true;
        } else {
            return false;
        }

вот функция, которую я использую как часть моего Utils класс:

public static boolean isNetworkConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return (cm.getActiveNetworkInfo() != null) && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

использовать его как: Utils.isNetworkConnected(MainActivity.this);

1-создать новый файл java (щелкните правой кнопкой мыши пакет. новый > класс > имя файла ConnectionDetector.java

2-добавьте следующий код в файл

<pre>package <add you package name> example com.example.example;

import android.content.Context;
import android.net.ConnectivityManager;

public class ConnectionDetector {

    private Context mContext;

    public ConnectionDetector(Context context){
        this.mContext = context;
    }

    public boolean isConnectingToInternet(){

        ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        if(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected() == true)
        {
            return true; 
        }

        return false;

    }
}

3-Откройте MainActivity.java — активность, где вы хотите проверить соединение, и сделать следующее

A-создание и определение функции.

<pre>ConnectionDetector mConnectionDetector;</pre>

B-внутри «OnCreate» добавьте следующее

<pre>mConnectionDetector = new ConnectionDetector(getApplicationContext());</pre>

C — для проверки соединения выполните следующие действия

<pre> if (mConnectionDetector.isConnectingToInternet() == false) {
//no connection- do something
} else {
//there is connection
}</pre>

Это еще один вариант для обработки всех ситуация:

public void isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
    } else {
        Toast.makeText(ctx, "Internet Connection Is Required", Toast.LENGTH_LONG).show();

    }
}

Проверьте сеть, доступную в android со скоростью передачи данных в интернете.

public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) Login_Page.this.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          try
                            {
                                HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
                                urlc.setRequestProperty("User-Agent", "Test");
                                urlc.setRequestProperty("Connection", "close");
                                urlc.setConnectTimeout(500); //choose your own timeframe
                                urlc.setReadTimeout(500); //choose your own timeframe
                                urlc.connect();
                                int networkcode2 = urlc.getResponseCode();
                                return (urlc.getResponseCode() == 200);
                            } catch (IOException e)
                            {
                                return (false);  //connectivity exists, but no internet.
                            }
                      }

          }
          return false;
    }

эта функция возвращает true или false.
Необходимо получить разрешение пользователя

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Понравилась статья? Поделить с друзьями:
  • Syntax error unexpected expecting end of file перевод
  • Syntax error unexpected eof while parsing python
  • Syntax error unexpected eof php
  • Syntax error unexpected eof expecting
  • Syntax error unexpected endforeach