Why do I get error on if else statements - java

why do my last two if statements have illegal start of expression and else without if errors? also I cannot post my code here because it wants formatting and I do not know how to do it properly. how do I post an actual code view?
I have changed it and this is the edited code. thank you for all of your help.
//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 ");}
}
}

In the third else statement, you have some parentheses missing. The entire boolean condition must be enclosed in parentheses. Also, you should use == instead of =, because == checks for equality, and = is the assignment operator. Also, the third else if statement has a semicolon instead of an opening curly brace at its end, and the statement directly following it needs a quotation mark, a parenthesis, and a semicolon added at the end.

You need == in the last else if not =
= is an assignment operator, whereas == checks for equality (with primitives).

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 );{
Should be this, without the semicolons after the else if statments. You are saying your statement is done when you leave them in there and the compiler is confused by the next else statements.
EDIT: Also as the other answers talk about, wrap your ifs in parthesis, and you should use == when doing a comparison.
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 )){

Too may bracketing errors to keep track of them all. And you need to fix the = to == as mentioned my another ansewer. Here's the refactor. You can compare it with your current code.
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 ");
}
}
}

Related

How to repeat an array together with a counter

What I’m trying to do with the following code is to print numbers and to replace the number with a word for the number that are divisible for 3, for 5 and for both 3 and 5.
So, when the user starts the code, it has to choose how many players are going to play.
The problem is that my code print all the numbers from 1 to 100 four times, one time for every player.
Can someone kindly explain me where is the mistake? Thanks!
Here are two solutions to that problem.
Option 1
In your case, there is no player object needed. So you could make use of a counter. That one will start by 1 and be incremented until it equals the selected number of players. Then you have to reset it to 1 again.
int player = 1;
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("player " + player + " says: divisible for 3 and 5");
} else if (i % 3 == 0) {
System.out.println("player " + player + " says: divisible for 3");
} else if (i % 5 == 0) {
System.out.println("player " + player + " says: divisible for 5");
} else {
System.out.println("player " + player + " says: " + i);
}
if (player < playersNumber) {
player++;
} else {
player = 1;
}
}
Option 2
If you really need a player object, I will advise you to make use of a queue. Also therefore you do not need an extra for-loop.
final Queue<Integer> allPlayers = new LinkedList<>();
for (int i = 1; i <= playersNumber; i++) {
allPlayers.add(i);
}
for (int i = 1; i <= 100; i++) {
final int player = allPlayers.poll();
allPlayers.add(player);
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("player " + player + " says: divisible for 3 and 5");
} else if (i % 3 == 0) {
System.out.println("player " + player + " says: divisible for 3");
} else if (i % 5 == 0) {
System.out.println("player " + player + " says: divisible for 5");
} else {
System.out.println("player " + player + " says: " + i);
}
}
Both solutions are not perfect, but there are working ones.
If something is unclear with these solutions do not hesitate to ask me.
I can post here a working example, but that will have no learning effect for you. So please answer my question.
What was your intention to use this:
for(int p = 0; p <= 100; p++){
for(int i = 1; i <= 100; i++){
}
}
Why do you think, you need two for-loop with each 100 iterations?
Keep it simple and don't overcomplicate things without a need. You alredy seem to be familiar with the modulo operator. Just use that to get the current player:
public static void main(String args[]) {
int playersNumber;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the number of players (min 2, max 6)");
playersNumber = scanner.nextInt();
//add so many players as user interd number
ArrayList<String> players = new ArrayList<>();
for (int i = 1; i <= playersNumber; i++) {
players.add("Player " + i);
}
// use modulo operator to get the current player.
// Note: list indexes are zero based, but your player number start with one,
// so you need to substract one from i
for(int i = 1; i <= 100; i++){
if(i % 3 == 0 && i % 5 == 0){
System.out.println(players.get((i-1) % playersNumber) + " says: divisible for 3 and 5");
} else if (i % 3 == 0) {
System.out.println(players.get((i-1) % playersNumber) + " says: divisible for 3");
} else if (i % 5 == 0) {
System.out.println(players.get((i-1) % playersNumber) + " says: divisible for 5");
} else {
System.out.println(players.get((i-1) % playersNumber) + " says: " + i);
}
}
}

Trying to figure out why my math will not add

I am currently working on a project for college which requires you to create a basic shopping menu. I am currently totaling my math by multiplying quantity of items by cost, but the total stays at zero. I created separate integers that store the cost of the item(ex: int hat = 32) and separate integers for quantity.( ex: quanHat = 0). For some reason, the quantity of items stays at zero even though I added a ++. anyone help me with this?
I have tried converting the integer to a string and back, but it does not seem to do anything.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pirate Trading Post v3");
System.out.println("----------------------");
int eight = 8;
int hat = 32;
int patch = 2;
int sword = 20;
int map = 100;
int shirt = 150;
int test = -1;
int quanEight = 0;
int quanHat = 0;
int quanPatch = 0;
int quanSword = 0;
int quanMap = 0;
int quanShirt = 0;
int total = ( quanEight * eight) + ( quanHat * hat) + ( quanPatch * patch) + ( quanSword * sword) + ( quanShirt * shirt) + ( quanMap * map);
while (test != 0){
System.out.println("Enter Item Code, ? or Q: ");
String code = input.next();
char ch = code.charAt(0);
ch = Character.toUpperCase(ch);
if (ch == '?'){
System.out.println("Valid Item codes are: 8 I H M S T.");
System.out.println("Q to quit.");
}
else if (ch == 'Q'){
test++;
System.out.println("Pirate Trading Post");
System.out.println(quanEight + " Genuine Piece Of Eight " + quanHat + " Pirate Hat " + quanPatch + " Eye Patch " + quanSword + " Sword " + quanMap + " Treasure Map " + quanShirt + " T-Shirt ");
System.out.println("Total: " + total + " bits");
}
else if (ch == '8'){
quanEight ++;
}
else if (ch == 'I'){
quanHat++;
}
else if (ch == 'H'){
quanPatch++;
}
else if (ch == 'M'){
quanSword++;
}
else if (ch == 'S'){
quanMap++;
}
else if (ch == 'T'){
quanShirt++;
}
}
The expected output should be cost of item multiplied by quantity, but the quantity will not store the value. I am thinking the value is not stored because it is a string, but I am not sure.
When the code calculated total , quanHat was 0. And so total was assigned the value 0.
During the while loop when quanHat is incremented, its value increments by 1.
But since total is not being updated or recalculated, it still shows 0.
you need to recalculate total in the if block of else if (ch == 'Q')

While loop for change making

I am learning Java and am making code that converts pennies in to change. It is completed however, I am unsure what to enter for the while loop. I would have used while(!change.equals("END")) but this can't be done because change is an integer, so what can I do?
class Main {
public static void main(String args[]) {
System.out.print("#Please enter the amount of change : ");
int change = BIO.getInt();
if (change <= 500 && change >= 1) {
System.out.print("Amount" + "\t" + "Coins" + "\n");
}
while (change =) {
int twopounds, pounds, fifty, twenty, ten, five, two, one;
twopounds = change / 200;
int left = change % 200;
pounds = left / 100;
left = left % 100;
fifty = left / 50;
left = left % 50;
twenty = left / 20;
left = left % 20;
ten = left / 10;
left = left % 10;
five = left / 5;
left = left % 5;
two = left / 2;
left = left % 2;
one = left / 1;
int nbCoins = twopounds + pounds + fifty + twenty + ten + five + two + one;
if (change > 500 || change < 1) {
System.out.print("Invalid amount " + change + "p" + "\n");
}
if (change <= 500 && change >= 1) {
if (nbCoins == 1) {
System.out.print(change + "p " + "\t" + nbCoins + " coin ");
} else {
System.out.print(change + "p " + "\t" + nbCoins + " coins ");
}
if (twopounds > 0) {
System.out.print(twopounds > 1 ? twopounds + "*200p " : "200p ");
}
if (pounds > 0) {
System.out.print(pounds > 1 ? pounds + "*100p " : "100p ");
}
if (fifty > 0) {
System.out.print(fifty > 1 ? fifty + "*50p " : "50p ");
}
if (twenty > 0) {
System.out.print(twenty > 1 ? twenty + "*20p " : "20p ");
}
if (ten > 0) {
System.out.print(ten > 1 ? ten + "*10p " : "10p ");
}
if (five > 0) {
System.out.print(five > 1 ? five + "*5p " : "5p ");
}
if (two > 0) {
System.out.print(two > 1 ? two + "*2p " : "2p ");
}
if (one > 0) {
System.out.print(one > 1 ? one + "*1p " : "1p ");
}
System.out.print("\n");
}
System.out.print("#Please enter the amount of change : ");
change = BIO.getInt();
}
}
}
Thanks :)
It depends on what BIO is. Generally, there are options like .hasNextToken() if it is Enumerable. But, without knowing what that variable is declared as, I can't tell you what your trigger would be.
maybe this will work:
boolean flag = true;
while(flag){
//do things
if(condition_when_you_want_your_loop_to_stop){
flag = false;
}
}

How can I output the hundred and teens numbers in words in my program

I need help to display my hundred and teens number in words. For example if I enter 116. My program will output One hundred and Six, instead of One hundred and sixteen. All the other numbers that I input work except for the teens numbers.
I would change 4 things in your code:
First:
Use int instead of double for your input
int numInput = Integer.parseInt(br.readLine());//user inputs number
Second:
In order to get the appropriate digit placements in int use:
int hundredsDigit = (numInput % 1000) / 100;
int tensDigit = (numInput % 100) / 10;
int onesDigit = numInput % 10;
instead of:
double hundredsDigit=Math.floor((numInput%1000)/100);
double tensDigit = Math.floor((numInput % 100) / 10);
double onesDigit = numInput % 10;
Third:
The else condition for the 110-119 range must be before the 100-999 (which technically should be 120-999)
Fourth:
Your teens method is taking the original numInput as parameter.
What you need to take is the onesDigit to determine which "teen" it is
So it should be a call like:
teens(onesDigit);
This call must be changed in the [10-19] condition and the [110-119] condition
And your teens new method should look like:
public static void teens(int onesDigit) {
if (onesDigit == 0) {
System.out.print("Ten ");
}
if (onesDigit == 1) {
System.out.print("Eleven ");
}
if (onesDigit == 2) {
System.out.print("Twelve ");
}
if (onesDigit == 3) {
System.out.print("Thirteen ");
}
if (onesDigit == 4) {
System.out.print("Fourteen ");
}
if (onesDigit == 5) {
System.out.print("Fifteen ");
}
if (onesDigit == 6) {
System.out.print("Sixteen ");
}
if (onesDigit == 7) {
System.out.print("Seventeen ");
}
if (onesDigit == 8) {
System.out.print("Eighteen ");
}
if (onesDigit == 9) {
System.out.print("Nineteen ");
}
}//closes teens method
That happens because you check if the number is in the range [100, 999] before checking that it is in the range [100, 119], change the order of the ifs and it will work just fine.
Start from smallest number to highest when comparing.
First condition:
if((numInput>=10)&&(numInput<=19)){
Second:
else if((numInput>=20)&&(numInput<=99)){
Third:
else if((numInput>100)&&(numInput<=119)){
Fourth:
else if((numInput>=100)&&(numInput<=999)){
You should put the
else if((numInput>100)&&(numInput<=119))
clause before the more inclusive
else if((numInput>=100)&&(numInput<=999))
What's happening here is that the larger range is searched first, and your tens function doesn't output anything for 1.
Your else if
else if((numInput>100)&&(numInput<=119)){
hundreds(hundredsDigit);
System.out.print(" ");
teens(numInput);
}
must be placed one level higher... Since the
else if((numInput>=100)&&(numInput<=999)){
hundreds(hundredsDigit);
System.out.print(" ");
tens(tensDigit);
System.out.print(" ");
ones(onesDigit);
}
will also fulfill the condition, the "116" you entered will never get there...
Just in case you wan't this, I did not write this:
public static String intToText(int n) {
if (n < 0)
return "Minus " + intToText(-n);
else if (n == 0)
return "Zero";
else if (n <= 19)
return oneToNineteen[n - 1] + " ";
else if (n <= 99)
return twentyToNinety[n / 10 - 2] + " " + intToText(n % 10);
else if (n <= 199)
return "One Hundred " + intToText(n % 100);
else if (n <= 999)
return intToText(n / 100) + "Hundred " + intToText(n % 100);
else if (n <= 1999)
return "One Thousand " + intToText(n % 1000);
else if (n <= 999999)
return intToText(n / 1000) + "Thousand " + intToText(n % 1000);
else if (n <= 1999999)
return "One Million " + intToText(n % 1000000);
else if (n <= 999999999)
return intToText(n / 1000000) + "Million " + intToText(n % 1000000);
else if (n <= 1999999999)
return "One Billion " + intToText(n % 1000000000);
else
return intToText(n / 1000000000) + "Billion " + intToText(n % 1000000000);
}
This was fun. It has the following issues:
-Only deals with integers. No longs, doubles etc.
-Doesn't deal with the single case of zero.
-Fails at Integer.MIN_VALUE because of the number = number * -1
Otherwise, it seems to work. The motivation was that I can't stand huge blocks of "if-else" code.
public class NumbersToWords {
private static final Map<Integer,String> NUM_TO_WORD = new HashMap<Integer, String>();
private static final List<Integer> KEYS = new ArrayList<Integer>(30);
static {
NUM_TO_WORD.put(0,"zero");
NUM_TO_WORD.put(1,"one");
NUM_TO_WORD.put(2,"two");
NUM_TO_WORD.put(3,"three");
NUM_TO_WORD.put(4,"four");
NUM_TO_WORD.put(5,"five");
NUM_TO_WORD.put(6,"six");
NUM_TO_WORD.put(7,"seven");
NUM_TO_WORD.put(8,"eight");
NUM_TO_WORD.put(9,"nine");
NUM_TO_WORD.put(10,"ten");
NUM_TO_WORD.put(11,"eleven");
NUM_TO_WORD.put(12,"twelve");
NUM_TO_WORD.put(13,"thirteen");
NUM_TO_WORD.put(14,"fourteen");
NUM_TO_WORD.put(15,"fifteen");
NUM_TO_WORD.put(16,"sixteen");
NUM_TO_WORD.put(17,"seventeen");
NUM_TO_WORD.put(18,"eighteen");
NUM_TO_WORD.put(19,"nineteen");
NUM_TO_WORD.put(20,"twenty");
NUM_TO_WORD.put(30,"thirty");
NUM_TO_WORD.put(40,"forty");
NUM_TO_WORD.put(50,"fifty");
NUM_TO_WORD.put(60,"sixty");
NUM_TO_WORD.put(70,"seventy");
NUM_TO_WORD.put(80,"eighty");
NUM_TO_WORD.put(90,"ninety");
NUM_TO_WORD.put(100,"hundred");
NUM_TO_WORD.put(1000,"thousand");
NUM_TO_WORD.put(1000000,"million");
NUM_TO_WORD.put(1000000000,"billion");
KEYS.addAll(NUM_TO_WORD.keySet());
Collections.sort(KEYS);
}
public static void main(String[] args){
int[] testValues = {24,4,543755,12,10000,123000,123,Integer.MAX_VALUE, -456};
NumbersToWords ntw = new NumbersToWords();
for(int i : testValues){
System.out.println(i + " -> " + ntw.getWords(i));
}
}
/* called recursively */
public String getWords(int number){
boolean isNegative = number < 0;
if(isNegative){
number = number * -1;
}
if(number < 100){
return getWordLessThanHundred(number);
}
StringBuilder words = new StringBuilder(50);
int key = getKey(number);
if(isNegative){
words.append("negative ");
}
words.append(getWords(number/key))
.append(" ").append(NUM_TO_WORD.get(key)) // get the largest placeholder word
.append(" ").append(getWords(number % key)); // get the rest
return words.toString();
}
private String getWordLessThanHundred(int number){
if(number == 0){
return "";
}
if(number < 21){
return NUM_TO_WORD.get(number);
}
int key = getKey(number);
return NUM_TO_WORD.get(key) + " " + NUM_TO_WORD.get(number - key);
}
private int getKey(int number){
for(int i = 0; i<KEYS.size();i++){
int value = KEYS.get(i);
if(i > 0 && number < value){
return KEYS.get(i - 1);
}else if(number == value){
return value;
}
}
return KEYS.get(KEYS.size() - 1);
}
}

Craps game: How do i get the while loop in this code from going into an infinite loop?

this are comments that explain the game so you can test it, but the main problem is when you are suppose to run the while loop if you a point value then it becomes an infinite loop. How do I get it to not be an infinite loop?
import java.util.Random;
public class Craps {
private int roll1;
private int roll2;
private Random randGen;
private int sum;
private int thePoint = sum;
private int bet;
private int newSum;
// instance classes
public Craps() {
randGen = new Random(); // this is the random generator
}
// when you win you double your money
// when you lose you lose everything
public void roll(int bet) { // you can bet as much money as you want
roll1 = (randGen.nextInt(6) + 1);
roll2 = (randGen.nextInt(6) + 1);
sum = roll1 + roll2; // you must add the two rolls and that is your sum
if (sum == 2 || sum == 3 || sum == 12) { // if the sum is 2 you lose
System.out.println("The sum is 2. You Lose!");
System.out.println("Your credit:" + " " + bet * 0);
} else if (sum == 7 || sum == 11) { // if it 7 you win
System.out.println("The sum is 7. You Win!");
System.out.println("Your credit:" + " " + bet * 2);
} else {
System.out.println("You rolled a" + " " + sum + ". " + "That is your point. Roll again.");
sum = thePoint;
}
}
public void rollAgain() {
while (sum != 7 || sum != thePoint) { // whatever the the sum is that is not one of the numbers above becomes your point.
roll1 = (randGen.nextInt(6) + 1);// you must role the die again until you get your point again the you win or until you get a 7 and then you lose.
roll2 = (randGen.nextInt(6) + 1);
sum = roll1 + roll2;
if (thePoint == sum) { // if the point equals the sum you win
System.out.println("You're on point. You Win!");
System.out.println("Your credit:" + " " + bet * 2);
} else if (sum == 7) { // if it equals 7 you lose.
System.out.println("You got a 7. You lose!");
System.out.println("Your credit:" + " " + bet * 0);
}
}
}
}
You need to change your loop condition.
while (sum != 7 || sum != thePoint) what happens here is that as soon as the first condition is met (sum is not seven), the loop starts executing.
if you change it to while (sum != 7 && sum != thePoint) then both these conditions need to be met - the loop only starts executing again if sum is not seven or the value of thePoint.

Categories