2014-02-01 4 views
-1

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

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

//Import Java scanner 
import java.util.Scanner; 

//This class ask a user for their item count and informs the user of the best packing method. 
public class PackingOrganizer{ 
public static void main(String[] args){ 
//declare constants and variables 
int CARTONS = 4, BOXES = 5; 
double containerAmount; 
double containerAmount2; 
//Get users item count 
Scanner input = new Scanner(System.in); 
System.out.print("Enter number of items : (All partial items are to be rounded up. ex. 6.5 items is rounded to 7 items)"); 
double itemCount = input.nextDouble(); 

//Check to see if input is an integer value 
if (itemCount != (int) itemCount) 
System.out.println("Invalid input round all partial numbers up"); 
//processing phase 
    else if (itemCount % CARTONS == 0){ 
     containerAmount =(itemCount /CARTONS); 
     System.out.println("Cartons can be used. The " + itemCount + " items will require " + containerAmount + " cartons ");} 
    else if (itemCount % BOXES ==0){ 
     containerAmount = (itemCount/BOXES); 
     System.out.println("Boxes can be used. The " + itemCount + " items will require " + containerAmount + " Boxes ");} 
    else if ((itemCount % BOXES != 0) && (itemCount % CARTONS != 0)) 
     System.out.println("Neither boxes nor cartons can be used for your: " + itemCount + " items."); 
    else if ((itemCount % BOXES == 0) && (itemCount % CARTONS == 0));{ 
     containerAmount = (itemCount/BOXES); 
     containerAmount2 = (itemCount/CARTONS); 
     System.out.println("Cartons can be used. The " + itemCount + " items will require " + containerAmount2 +"." + " Boxes can be used. The " + itemCount + " items will require" + containerAmount +" boxes ");} 
} 
} 
+3

Скопируйте свой код, выделите его и нажмите кнопку '{}'. –

+0

Просто положил backticks вокруг вашего кода и опубликовал его – s3nzoM

+0

Это очень понравилось. –

ответ

0

== Вам нужно в последнем else if не =

= является оператор присваивания, в то время как == проверки на равенство (с примитивов).

+2

это может быть правдой, но есть WAY больше, чем эта проблема – MightyPork

+0

+1, хотя «это определенно верно», но есть больше, чем эта проблема: P – ataulm

1

В третьем заявлении else у вас есть некоторые круглые скобки. Все логическое условие должно быть заключено в круглые скобки. Кроме того, вы должны использовать == вместо =, потому что == проверяет равенство, а = - оператор присваивания. Кроме того, оператор else else if имеет точку с запятой вместо открывающей фигурной скобки на своем конце, а непосредственно следующему за ней нужно отметить котировку, скобки и точку с запятой, добавленную в конце.

0
else if (itemCount % BOXES != 0) && (itemCount % CARTONS != 0); 
     System.out.println("Neither boxes nor cartons can be used for your: " + itemCount + " items. 
    else if (itemCount % BOXES = 0) && (itemCount % CARTONS = 0);{ 

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

EDIT: Также, как говорят другие ответы, оберните ваш ifs в parthesis, и вы должны использовать == при сравнении.

else if ((itemCount % BOXES != 0) && (itemCount % CARTONS != 0)) 
     System.out.println("Neither boxes nor cartons can be used for your: " + itemCount + " items. 
    else if ((itemCount % BOXES == 0) && (itemCount % CARTONS = 0)){ 
0

Слишком много ошибок брекетинга, чтобы отслеживать их все. И вам нужно исправить = до ==, как упоминалось в моем другом анкете. Вот рефактор. Вы можете сравнить его с вашим текущим кодом.

import java.util.Scanner; 

//This class ask a user for their item count and informs the user of the best packing method. 
public class PackingOrganizer { 

    public static void main(String[] args) { 
//declare constants and variables 
     int CARTONS = 4, BOXES = 5; 
     double containerAmount; 
     double containerAmount2; 
//Get users item count 
     Scanner input = new Scanner(System.in); 
     System.out.print("Enter number of items : (All partial items are to be rounded up. ex. 6.5 items is rounded to 7 items)"); 
     double itemCount = input.nextDouble(); 

//Check to see if input is an integer value 
     if (itemCount != (int) itemCount) { 
      System.out.println("Invalid input round all partial numbers up"); 
     } //processing phase 
     else if (itemCount % CARTONS == 0) { 
      containerAmount = (itemCount/CARTONS); 
      System.out.println("Cartons can be used. The " + itemCount + " items will require " + containerAmount + " cartons "); 
     } else if (itemCount % BOXES == 0) { 
      containerAmount = (itemCount/BOXES); 
      System.out.println("Boxes can be used. The " + itemCount + " items will require " + containerAmount + " Boxes "); 
     } else if ((itemCount % BOXES != 0) 
       && (itemCount % CARTONS != 0)) { 
      System.out.println("Neither boxes nor cartons can be used for your: " + itemCount + " items"); 
     } else if ((itemCount % BOXES == 0) 
       && (itemCount % CARTONS == 0)) { 

      containerAmount = (itemCount/BOXES); 
      containerAmount2 = (itemCount/CARTONS); 
      System.out.println("Cartons can be used. The " + itemCount + " items will require " + containerAmount2 + "." + " Boxes can be used. The " + itemCount + " items will require" + containerAmount + " boxes "); 
     } 
    } 
} 
Смежные вопросы