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')
Related
I need to make this java code repeat based on the user input, and I cannot make it repeat using the code that I do have so far. I am not supposed to use any other imports besides the scanner and use class main. This is because we are using the https://repl.it/languages/java10 as our compiler because we are an elementary class. When I run the code, it is supposed to ask ten random addition and subtraction and should ask if the user wants to continue or not. When entering 1 for continue, it should ask another ten questions. however, upon running this code, it stops after the first question.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Answer the following questions.");
Scanner in = new Scanner(System.in);
int A = 0;
int N = 10;
int n = 0;
int H = 0;
boolean p = true;
while (p){
int R1 = (int)(Math.random() * 50 + 1);
int R2 = (int)(Math.random() * 999 + 1);
int R3 = (int)(Math.random() * 999 + 1);
if(R1>25){
System.out.println( "" + R2 + " + " + R3);
A = in.nextInt();
if (A == (R2 + R3))
System.out.println("Correct");
else
System.out.println("Incorrect");
}
if(R1<25){
System.out.println( "" + R2 + " - " + R3);
A = in.nextInt();
if (A == (R2 - R3))
System.out.println("Correct");
else
System.out.println("Incorrect");}
N--;
if (N==0)
p = false;
continue;
}System.out.println("Do you want ot continue? Put 1 for yes, 2 for no.");
H = in.nextInt();
if (H==1)
p=true;
else
p=false;
while (N>0);
}
}
That's why you put the question System.out.println("Do you want ot continue? Put 1 for yes, 2 for no."); out of the while.
I recommend use do while instead of while. So you just need to put the question inside of loop do while.
System.out.println("Answer the following questions.");
Scanner in = new Scanner(System.in);
int A = 0;
int N = 10;
int H = 0;
boolean p = true;
do{
int R1 = (int) (Math.random() * 50 + 1);
int R2 = (int) (Math.random() * 999 + 1);
int R3 = (int) (Math.random() * 999 + 1);
if (R1 > 25) {
System.out.println("" + R2 + " + " + R3);
A = in.nextInt();
if (A == (R2 + R3)) {
System.out.println("Correct");
} else {
System.out.println("Incorrect");
}
}
if (R1 < 25) {
System.out.println("" + R2 + " - " + R3);
A = in.nextInt();
if (A == (R2 - R3)) {
System.out.println("Correct");
} else {
System.out.println("Incorrect");
}
}
N--;
System.out.println("Do you want ot continue? Put 1 for yes, 2 for no.");
H = in.nextInt();
if (H == 1) {
p = true;
} else {
p = false;
}
if (N == 0) {
p = false;
System.out.println("You have reached your max attempts.")
}
}while (N > 0 && p);
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 ");
}
}
}
I'm working on a coin flip assignment and I have the majority of it functioning properly (albeit in a less elegant fashion compared to the code I see on here).
I'm trying to find a way to tell the user which number appears most in their flips, and if heads are assigned to even #s, and tails to odd #s, which one came up the most. I'm looking for suggestions to implement these features.
Here is the code thus far:
import java.io.*;
import java.util.*;
public class coinFlip {
public static void main(String[] args) throws IOException {
// declare in as a BufferedReader; used to gain input from the user
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int flips;
int anArray[];
int x;
int r;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
int counter7 = 0;
int counter8 = 0;
int counter9 = 0;
int counter10 = 0;
System.out.println("How many times would you like to flip your coin?");
flips = Integer.parseInt(in.readLine());
if (flips > 1000) {
System.out.println("Invalid input, restart program!");
}
if(flips <= 1000) {
System.out.println("You want to flip " + flips + " times");
anArray = new int[flips];
for(x = 0; x < flips; x++) {
r = (int) Math.round(Math.random()*9)+1;
anArray[x] = r;
System.out.println(anArray[x]);
if (anArray[x] == 1) {
counter1 += 1;
}
else if (anArray[x] == 2) {
counter2 += 1;
}
else if (anArray[x] == 3) {
counter3 += 1;
}
else if (anArray[x] == 4) {
counter4 += 1;
}
else if (anArray[x] == 5) {
counter5 += 1;
}
else if (anArray[x] == 6) {
counter6 += 1;
}
else if (anArray[x] == 7) {
counter7 += 1;
}
else if (anArray[x] == 8) {
counter8 += 1;
}
else if (anArray[x] == 9) {
counter9 += 1;
}
else if (anArray[x] == 10) {
counter10 += 1;
}
}
System.out.println("\n You rolled 1 " + counter1 + " times.");
System.out.println("You rolled 2 " + counter2 + " times.");
System.out.println("You rolled 3 " + counter3 + " times.");
System.out.println("You rolled 4 " + counter4 + " times.");
System.out.println("You rolled 5 " + counter5 + " times.");
System.out.println("You rolled 6 " + counter6 + " times.");
System.out.println("You rolled 7 " + counter7 + " times.");
System.out.println("You rolled 8 " + counter8 + " times.");
System.out.println("You rolled 9 " + counter9 + " times.");
System.out.println("You rolled 10 " + counter10 + " times.");
}
}
}
import java.io.*;
import java.util.Random;
public class CoinFlip {
public static void main(final String[] args) throws IOException {
// declare in as a BufferedReader; used to gain input from the user
final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//declare variables
System.out.println("How many times would you like to flip your coin?");
final int flips = Integer.parseInt(in.readLine());;
if (flips > 1000) {
System.out.println("Invalid input, restart program!");
return;
}
System.out.println("You want to flip " + flips + " times");
final int[] counters = new int[10],
side = new int[2];
int r=0,x,max=0;
final Random rand = new Random();
for(x = 0; x < flips; ++x) {
r = rand.nextInt(10);
System.out.println(r+1);
counters[r]++;
}
for ( x = 0; x < counters.length; ++x )
{
System.out.println("You rolled " + (x+1) + " " + counters[x] + " times.");
if ( counters[x] > max )
{
max = counters[x];
r = x+1;
}
side[x%2] += counters[x];
}
System.out.println(r + " was rolled most.");
System.out.println("You rolled " + side[0] + " heads and " + side[1] + " tails." );
}
}
Using loops, as shown in another answer, will make life much easier.
There is a more critical logic error in your code:
You round the output of Math.random(), which gives a float between 0 and 1, and round that to get an integer. The following table shows what output you'll get from your code in respect to the RNG:
| Math.random() output | Resulting Integer |
| 0 ~ 0.04999 | 0 |
| 0.05 ~ 0.14999 | 1 |
| ...... | ..... |
| 0.95 ~ 0.99999 | 10 |
See the problem? 0 and 10 appear only half as much as the other numbers.
You should either floor() the output, or use Random.nextInt() to generate a uniform distribution of ints.
This would make your life much easier:
int counter[10];
...
for(x = 0; x < flips; x++) {
r = (int) Math.round(Math.random()*9)+1;
anArray[x] = r;
System.out.println(anArray[x]);
counter[r-1]++;
}
for(i=1; i <= counter.length; i++)
System.out.println("You rolled " + i + " " + counter[i-1] + " times.");
For your other two problems, there's nothing to really "suggest". Just iterate over counter, remember the largest value, and add up the even and odd indices separately.
I'm working on a simple java code that outputs all factors of a user-inputted number. How do I count and then display the number of factors outputted?
System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();
System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
System.out.println(w);
}
}
In the code above, it's the number of integers outputted in 'w' For instance, if the number inputted is 8 and its factors are 1,2,4,8, how do I write a code that says '8 has 4 factors' ?
Thanks
You simply need a variable to count factors:
System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();
int nFactors = 0;
System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
System.out.println(w);
++nFactors;
}
}
System.out.println(d + " has " + nFactors + " factors");
You need a counter variable. Here is the code:
int counter =0;
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
counter++;
System.out.println(w);
}
System.out.println(d + " has " + counter + "factors ");
Try with this code:
import java.util.Scanner;
public class EmbalzadoFactorial {
public static Scanner sc;
public static void main(String[] args) {
int Number, i;
sc = new Scanner(System.in);
System.out.print("Please Enter any number to Find Factors: ");
Number = sc.nextInt();
System.out.println("The factors are: ");
for(i = 1; i <= Number; i++) {
if(Number%i == 0) {
System.out.format(" %d ", i);
System.out.print ("and");
System.out.format("%s %n ", i);
}
}
}
}
I'm trying to create a game that rolls 2 set of dice, three times in a row. It has the user guess a number between 2-12 just once. If that one guess matches any of the three rolls he/she wins, otherwise he/she loses. I have another class to display results and I have a counter for how many loops it's been through. It comes out 0 if the user correctly guessed it, otherwise it comes out as 1. I'm guessing the loop just loops once so if anyone can point out what I'm doing wrong to make it so it loops three times(and stopping if the user gets the answer right).
import javax.swing.JOptionPane;
/**
* #author Marcus
*
*/
public class Dice {
int randomDieNum1;//random number generator for dice
int randomDieNum2;//random number generator for dice
private final int MINVALUE1 = 1, //minimum die value
MAXVALUE1 = 6;//maximum die value
private final int MINVALUE2 = 1, //minimum die value
MAXVALUE2 = 6;//maximum die value
int userNum = Integer.parseInt(JOptionPane.showInputDialog(null, "Guess a number between 1-12", "Guess a Number",
JOptionPane.INFORMATION_MESSAGE));//gets user input
String result ; //results
int start = 0 ; //counter to see how many turns were taken
public Dice()
{
for (int i = 1 ; i <= 3; i++)
randomDieNum1 = ((int)(Math.random()* 100) % MAXVALUE1 + MINVALUE1);
randomDieNum2 = ((int)(Math.random()* 100) % MAXVALUE2 + MINVALUE2);
int total = randomDieNum1 + randomDieNum2;
if (randomDieNum1 + randomDieNum2 != userNum)
{
result = "You did not guess the \n number correctly";
++ start;
}
else if (randomDieNum1 + randomDieNum2 == userNum)
{
result = randomDieNum1 + "+" + randomDieNum2 + "=" + total + "\n" +
"You guessed the number correctly";
}
else
{
result = "You Did not guess the number correctly";
}
}
public String get() //used in another class to display count
{
String temp;
temp = "" + start;
return temp;
}
}
EDIT
Thanks guys. I added both suggestions and added a break to stop the loop after the user gets the answer right.
This is what it looks like:
public Dice()
{
for (int i = 1 ; i <= 3; i++)
{randomDieNum1 = ((int)(Math.random()* 100) % MAXVALUE1 + MINVALUE1);
randomDieNum2 = ((int)(Math.random()* 100) % MAXVALUE2 + MINVALUE2);
int total = randomDieNum1 + randomDieNum2;
if (randomDieNum1 + randomDieNum2 == userNum)
{result = randomDieNum1 + "+" + randomDieNum2 + "=" + total + "\n" +
"You guessed the number correctly";
++ turns; //
break; //stops the loop if condition is meet
}
else if(randomDieNum1 + randomDieNum2 != userNum)
{
result = "You did not guess the \n number correctly\n\n";
++ turns;
}
}
}
Apart from the missing { in for (int i = 1 ; i <= 3; i++) {
You might have to reconsider the logic used in the if condition
if(x+y != c)
{// do operation A}
else if (x+y == c)
{// do operation B}
the else condition after the else-if will never get executed.
This isn't encapsulating everything in the loop
for (int i = 1 ; i <= 3; i++)
You're missing the brackets for encapsulating
for (int i = 1 ; i <= 3; i++) {
}