Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am supposed to build a slot machine that has 3 display windows, each window has 6 options that could display.
I am confused what "test expression" to use after the term switch? and then how to get the program to compare the 6 cases or options (cherry, orange, plum, bell, melon, bar) to see if they match and offer a return of what they won.
import java.util.Random;
import java.util.Scanner;
public class SlotMachine
{
//This is the main method
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Random random = new Random();
String cont = "y" or "Y";
char answer;
int money = 0;
int totalEntered = 0;
int a;
int n;
int amountWon = 0;
int dbl = money * 2;
int trpl = money * 3;
while (cont.equals("y"))OR (cont.equals("Y"))
{
a = random.nextInt(6);
n = random.nextInt(991) +10;
totalEntered += money;
System.out.println("How much money would you like to bet? ");
money = keyboard.nextInt();
switch (TestExpression????)
{
case 0:
System.out.println("Cherry");
break;
case 1:
System.out.println("Orange");
break;
case 2:
System.out.println("Plum");
break;
case 3:
System.out.println("Bell");
break;
case 4:
System.out.println("Melon");
break;
default:
System.out.println("Bar");
}
if ()
{
System.out.println("You have won $0");
}
else if ()
{
System.out.println("Congratulations, you have won $" + dbl);
amountWon += dbl;
}
else if ()
{
System.out.println("Congratulations, you have won $" + trpl);
amountWon += trpl;
}
System.out.println("Continue? Enter y = yes");
cont = keyboard.nextLine();
}
}
}
Put a there. Whatever a is it jumps to that case in the switch statement. Ex: if a is 2 it jumps to case 2 so would print "Plum"
Could I also recommend using an Enum in this case?
enum SlotOptions {
CHERRY,
ORANGE,
PLUM,
BELL,
MELON,
BAR;
}
It looks like the swithc expression is the "actual" slow machine, so you want to put a random int there. Something along the lines of switch(a).
Why? Think about how a slot machine works and then look at your code. The slot machine randomly picks a symbol for each spot (ie 1 fruit). In your code you have a case for each fruit. What is happening is you are representing each case with a number. So to determine which case, you need to pick a number. What number do you pick? Since its a slot machine you pick a random number. That is why you have a=random.nextInt();.
You don't put a test expression in a switch-statement. You put an integer value. In this case, it seems like you want a there.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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 13 hours ago.
Improve this question
I am trying to create a 5 questions quiz, after question 4 it automatically prints question 5 and not ask first, and then proceeds on printing the results. here is my code
import java.util.Scanner;
public class quiz {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name, section;
int score, numQuestions = 5;
System.out.println("Welcome to the Basic Electronics Quiz!");
boolean repeat;
do {
// Get name and section
System.out.print("Enter your name: ");
name = scanner.nextLine().trim();
System.out.print("Enter your section: ");
section = scanner.nextLine().trim();
// Initialize score
score = 0;
// Question 1
System.out.println("\nQuestion 1: What is Ohm's Law?");
System.out.println("A. Voltage = Current x Resistance");
System.out.println("B. Current = Voltage x Resistance");
System.out.println("C. Resistance = Voltage / Current");
System.out.print("Answer: ");
String answer1 = scanner.nextLine().trim().toLowerCase();
if (answer1.equals("a")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "A" + ".");
}
System.out.println();
// Question 2
System.out.println("\nQuestion 2: What is the unit of resistance?");
System.out.println("A. Ampere");
System.out.println("B. Volt");
System.out.println("C. Ohm");
System.out.print("Answer: ");
String answer2 = scanner.nextLine().trim().toLowerCase();
if (answer2.equals("c")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "C" + ".");
}
System.out.println();
// Question 3
System.out.println("\nQuestion 3: An LED is a type of resistor. (True/False)");
System.out.print("Answer: ");
String answer3 = scanner.nextLine().trim().toLowerCase();
if (answer3.equals("true")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "True" + ".");
}
System.out.println();
// Question 4
System.out.println("Question 4: What is the total resistance of two 10-ohm resistors in parallel?");
System.out.print("Your answer: ");
try {
double answer4 = scanner.nextDouble();
double expectedAnswer4 = 5.0;
if (Math.abs(answer4 - expectedAnswer4) < 0.0001) {
System.out.println("Correct!");
score++;
} else {
System.out.println("Wrong. The correct answer is " + expectedAnswer4 + ".");
}
System.out.println();
} catch (Exception e) {
// If there's an error parsing the input, don't add to score
}
// Question 5
System.out.println("\nQuestion 5: What is the term for a circuit that can generate an output signal with a fixed frequency?");
System.out.print("Your answer: ");
String answer5 = scanner.nextLine().trim().toLowerCase();
if (answer5.contains("Occilator") && answer5.contains("occilator")) {
score++;
}
else {
//System.out.println("Wrong. The correct answer is " + "Oscillator" + ".");
}
System.out.println();
// Display results
System.out.printf("\n%s, section %s, your score is %d/%d.\n", name, section, score, numQuestions);
// Ask to repeat
System.out.print("\nDo you want to take the quiz again? (yes/no): ");
String repeatStr = scanner.nextLine().trim().toLowerCase();
repeat = repeatStr.equals("yes") || repeatStr.equals("y");
} while (repeat);
System.out.println("\nThank you for taking the quiz!");
}
}
I tried copying only the question 5 to another file and it works but when i paste it again in the main file it will only proceeds on printing the results instead of asking for question 5
The problem is in using scanner.nextDouble();. You can read here more about why the problem occurs on this line.
You can solve your problem if you use Double.parseDouble(scanner.nextLine()); instead of scanner.nextDouble();.
Also, as Gilbert Le Blanc
has stated in the comments, you need to update the condition in your 5th question from answer5.contains("Occilator") && answer5.contains("occilator") to answer5.contains("Occilator") || answer5.contains("occilator"), otherwise you will never be able to answer the 5th question correctly. Here you also meant to write oscillator and not ocillator.
Here is an example output after implementing the solution:
Welcome to the Basic Electronics Quiz!
Enter your name: Aleksa
Enter your section: 1
Question 1: What is Ohm's Law?
A. Voltage = Current x Resistance
B. Current = Voltage x Resistance
C. Resistance = Voltage / Current
Answer: a
Correct!
Question 2: What is the unit of resistance?
A. Ampere
B. Volt
C. Ohm
Answer: c
Correct!
Question 3: An LED is a type of resistor. (True/False)
Answer: true
Correct!
Question 4: What is the total resistance of two 10-ohm resistors in parallel?
Your answer: 5
Correct!
Question 5: What is the term for a circuit that can generate an output signal with a fixed frequency?
Your answer: occilator
Aleksa, section 1, your score is 5/5.
Do you want to take the quiz again? (yes/no):
I had a prompt to write a program in java that asks users for the base and height of a triangle. Then the program is supposed to find the area. I started the program asking the user if they are willing to help me. If they say "Yes" then the program continues. If they say anything other than "Yes" I want the program to stop. I don't know how to get it to reply to the user, then stop running. My code is below. If you have time to review the full thing that would be awesome! I'm brand new at this.
public static void main(String[] args) {
System.out.println("Hey can you help me practice finding the area of a triangle?");
String answerFirstQuestion = "Yes";
//if (answerFirstQuestion = Yes){
//}else{
// System.exit(0);
//}
//^^This part isn't apart of the prompt. I wanted to ask the user a question, then have them answer "Yes". If they entered anything other than that, I wanted the program to print "Oh ok, that's fine. Thanks anyways." then stop. Could I get some feedback on how to accomplish this.
switch (answerFirstQuestion) {
case "Yes":
System.out.println("Thanks kid!\nJust give me a random base and height for our imaginary triangle.\nI'll then use the equation b*h/2 to see if my program can find the area.");
break;
default:
System.out.println("Oh ok, that's fine.\nThanks anyways.");
}
int base;
base = 6;
int height;
height = 12;
int area = base*height/2;
area = base*height/2;
System.out.println("The base of the triangle is? " + base);
System.out.println("The height of the triangle is? " + height);
System.out.println("Area of Triangle is: " + area);
System.out.println("Cool I guess it works, thanks again!");
}
}
The java.lang.System.exit() method exits the current program by terminating running Java virtual machine.
The following example shows the usage of java.lang.System.exit() method.
// A Java program to demonstrate working of exit()
import java.util.*;
import java.lang.*;
class GfG
{
public static void main(String[] args)
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
for (int i = 0; i < arr.length; i++)
{
if (arr[i] >= 5)
{
System.out.println("exit...");
// Terminate JVM
System.exit(0);
}
else
System.out.println("arr["+i+"] = " +
arr[i]);
}
System.out.println("End of Program");
}
}
I hope that this helps you :).
Just return.
System.out.println("Hey can you help me practice finding the area of a triangle?");
String answerFirstQuestion = "Yes";
switch (answerFirstQuestion) {
case "Yes":
System.out.println("Thanks kid!\nJust give me a random base and height for our imaginary triangle.\nI'll then use the equation b*h/2 to see if my program can find the area.");
break;
default:
System.out.println("Oh ok, that's fine.\nThanks anyways.");
return;
// Return from the main function. The code below this will NOT be executed
}
Working on a coding assignment and we have to incorporate methods and returning it. However, that is the beside the point. I am struggling on the price calculation portion. Okay, here's the gist of what I am stuck with. When the program asks, is your car and import. If the answer is yes, you will be charge with a 7% import tax, if no, the charge is negated. Now, the program asks for four services, depending on yes or no, the charge will be added based on their answer.
So, if the user wants an Oil Change and Tune Up and if their car is an import the services price will be added along with the import tax or if the car is not an import but want all services then the charges will be displayed without the import tax added, etc... The final outcome would display "Before taxes, it would be $# and after taxes, your total is..." An if statement is required but I do not know where to start because I am mainly struggling with the yes or no... Any help? My professor advised me to use an accumulator so I added one.. No avail, I am lost, any help would be greatly appreciated.
import java.util.Scanner;
public class CarMaintenance
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String car;
//capture car
System.out.println("What is the make of your car");
car = keyboard.nextLine();
String answer;
boolean yn;
System.out.println("Is your car an import?");
while (true)
{
answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("yes"))
{
yn = true;
break;
}
else if (answer.equalsIgnoreCase("no"))
{
yn = false;
break;
}
else
{
System.out.println("Sorry, I didn't catch that. Please answer yes or no");
}
}
String[] services = {"Oil Change", "Coolant Flush", "Brake Job", "Tune Up"};
for(int i=0; i<services.length; i++)
{
System.out.println("Do you want a " +services[i]);
answer = keyboard.next();
}
double amount = 0;
double[] price = {39.99, 59.99, 119.99, 109.99};
for(int i =0; i<price.length; i++)
{
amount = (price[i] + price [i]);
}
// double total = 0;
double c = 0;
c = car(amount);
// c = car(total);
System.out.println("The price for your services for your" + " " + car + " " + "is" + " "+ c + ".");
}
public static double car(double amount)
{
return (double) ((amount-32)* 5/9);
}
}
Before I talk about your code, I recommend you read this article.
Rubber Duck Debugging.
It is a bit flippant, but there is a deep truth to it. And it maps neatly with a debugging technique that I was taught .... umm ... 40 years ago.
First I draw your attention to this:
System.out.println("Is your car an import?");
while (true)
{
answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("yes"))
{
yn = true;
break;
}
else if (answer.equalsIgnoreCase("no"))
{
yn = false;
break;
}
else
{
System.out.println("Sorry, I didn't catch that. Please answer yes or no");
}
}
That code does a pretty good job of asking a "yes or no" question and getting the answer. It includes code to retry if the user responds with something that isn't recognizable as "yes" or "no".
So I'm guessing that someone wrote that code for you ... or you found it somewhere. You need to read that code carefully, and make sure you understand exactly how it works.
Next, I draw your attention to this:
for(int i=0; i<services.length; i++)
{
System.out.println("Do you want a " +services[i]);
answer = keyboard.next();
}
This code does not make sense. (Explain it to your rubber duck!)
Your earlier code is a good example of how to ask a yes / no question. But this is nothing like that:
You are not testing for "yes" or "no".
You are not repeating if the user gives an unrecognizable answer
You are not even storing the answer .... for each distinct service.
Then this:
double amount = 0;
double[] price = {39.99, 59.99, 119.99, 109.99};
for(int i =0; i<price.length; i++)
{
amount = (price[i] + price [i]);
}
It looks like this is trying to add the price of service items to the overall amount. But:
You are doing it for every service item, not just the items that the customer asked for.
You are actually doing the calculation incorrectly anyway. (Talk to your Rubber Duck about it!)
How to fix this?
Some things should be obvious from what I said above.
The problem of remembering the answers from the first for loop and using them in the second for loop ... is actually a problem you can / should avoid. Instead, combine the two loops into one. Here's some pseudo code:
for each service:
ask the user if he wants this service
if the user wants this service:
add the service cost to the total.
Understand the logic of that, and translate it into Java code. (Yes I could write it for you, but that defeats the purpose!)
If you would want the charges to be added to the value of answer you should do it in only one for loop and because the index of services and prices line up just use and if statement to check if the response is yes
String[] services = {"Oil Change", "Coolant Flush", "Brake Job", "Tune Up"};
for(int i=0; i<services.length; i++)
{
System.out.println("Do you want a " +services[i]);
answer = keyboard.next();
if(answer.equalsIgnoresCase()){
answer += prices[i]
}
}
double amount = 0;
double[] price = {39.99, 59.99, 119.99, 109.99};
for(int i =0; i<price.length; i++)
{
amount = (price[i] + price [i]);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Given this requirement
Create a code which creates random number and ask user to make 2 guess and then print out the actual number and also state which one of your guess was closest
I am stuck at the last part. Please help.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package selectionexercises;
/**
*
*
* #author jhonpaul
*/
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("I have picked a number between 1 to 100 try to guess it.");
int randomNumber = (int) (Math.random() * 100 + 1);
System.out.println("Enter Your First Guess.");
int guess1;
guess1 = sc.nextInt();
System.out.println("Enter Your Second Guess.");
int guess2;
guess2 = sc.nextInt();
System.out.println("The number was " + randomNumber);
int range;
range = randomNumber;
}
}
Use Math.min(Math.abs(randomNumber-guess1), Math.abs(randomNumber-guess2))
Do something like this:
//Calculate difference and use absolute value (turn negative values into positive if necessary)
int difference1 = Math.abs(randomNumber - guess1)
int difference2 = Math.abs(randomBumber - guess2)
//Compare result
if(difference1<difference2) {
System.out.println("Guess1 was closer");
} else if (difference1>difference2) {
System.out.println("Guess2 was closer");
} else {
System.out.println("Both were equally close!");
}
There are shorter ways than this but scince you are a starter I think this is an understandable and easy to use way.
I have created a single-class Java game in which we need to buy and sell stocks, I have just started Java and am a newbie so need help + this code is not very good.
import java.io.*;
import java.util.Random;
public class stock_holding_game
{
static Random randomn = new Random();
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args)throws IOException
{
double cash = 30.0;
double stocks[] = {0,10,20,40,80,160,320,640};//cost of stocks (there are 7 stocks each with different price)
int mystocks[] = {0,0,0,0,0,0,0,0};
pass("Enter your name");
String name = br.readLine();
pass("Hi "+name);
commandlist();
boolean booleancheck = true;
while(booleancheck)
{
pass("Please enter your command");
String command = br.readLine();
command =" "+command+" ";
char c = command.charAt(2);
switch(c)
{
case'h':
pass("enter the stock ID number");
int s1 = Integer.parseInt(br.readLine());
if(s1>0&&s1<=8)
{
pass("Starting price: "+stocks[s1]);
double t = randomn.nextDouble() *(stocks[s1]/10.0);
int add = randomn.nextInt(2);
if(add==0)stocks[s1]=stocks[s1]+t;
else
stocks[s1]=stocks[s1]-t;
pass("Current price: "+stocks[s1]);
}
else
{
pass("Wrong Number");
pass("Enter a number from 1 to 8");
pass("Do whole task again xD");
}
break;
case 'n':
pass("Enter the stock ID number");
int s2 = Integer.parseInt(br.readLine());
if(s2>0&&s2<=8)
{
double t = randomn.nextDouble() *(stocks[s2]/10.0);
int add = randomn.nextInt(2);
if(add==0)stocks[s2]=stocks[s2]+t;
else
stocks[s2]=stocks[s2]-t;
pass("Current price: "+stocks[s2]);
pass("You currently have: "+mystocks[s2]+ " of these stocks");
pass("You have " +cash+" cash");
pass("Enter the number of stocks you wish to buy");
int nsbuy = Integer.parseInt(br.readLine());
if(nsbuy<0)pass("Idiot ! , add atleast 1 if you wish to buy");
else if(nsbuy==0);
else
{
double checkprice = nsbuy*stocks[s2];
if(checkprice > cash)
{
pass("You don't have enough cash in hand !");
}
else
{
cash = cash - checkprice;
mystocks[s2] = mystocks[s2] + nsbuy;
pass("Now you have "+mystocks[s2]+ " of stock ID " +s2);
pass("You are left with "+cash);
}
}
}
else
{
pass("Invalid Input!");
pass("Enter a number from 1 to 8");
}
break;
case 'a':
pass("You have currentln " +cash+" cash");
break;
case 'x':
booleancheck = false ;
pass("You leave with "+cash+" cash");
pass("Bye, Hope to see you again .");
break;
case 'o':
commandlist();
break;
case 'y':
for(int xyz = 1; xyz<mystocks.length - 1;xyz++)
{
pass("You have "+mystocks[xyz]+ " of stock ID "+xyz);
}
break;
case 'e':
pass("Enter the stock ID number");
int s3 = Integer.parseInt(br.readLine());
if(s3>0&&s3<=8)
{
double t = randomn.nextDouble() *(stocks[s3]/10.0);
int add = randomn.nextInt(2);
if(add==0)stocks[s3]=stocks[s3]+t;
else
stocks[s3]=stocks[s3]-t;
pass("Current price: "+stocks[s3]);
pass("You currently have: "+mystocks[s3]+ " of these stocks");
pass("You have " +cash+" cash");
pass("Enter the number of stocks you wish to sell");
int nssell = Integer.parseInt(br.readLine());
if(nssell<0)pass("Enter atleast 1 if you wish to sell(in case you have)");
else if(nssell==0);
else
{
double nscheckprice = stocks[s3]*nssell;
if(nssell>mystocks[s3])pass("You don't jave that many stocks !");
else
mystocks[s3] = mystocks[s3] - nssell;
cash = cash + nscheckprice;
pass("You have successfully sold your " +nssell+" stocks for "+nscheckprice);
pass("Now , you have , "+ mystocks[s3]+ " of stock ID "+s3);
pass("You are left with " +cash + " cash");
}
}
else
{
pass("Invalid Input!");
pass("Enter a number from 1 to 8");
}
break;
default:
pass("Invalid Input!");
break;
}
}
}
private static void commandlist()
{
pas("Your command list : ");
pas("checkstock - check the current and earlier value of a stock");
pas("invest - buy shares ");
pas("sell - sell ur share ");
pas("exit - leave the game");
pas("my - show ur all current stock");
pas("cash - show ur current cash in hand");
pas("There are 7 stock with id 1 , 2 , 3 , and so on till 7")
pas("Remember ! It is case sensitive");
}
private static void pass(String source)
{
System.out.println(source);
}
private static void pas(String source)
{
System.err.println(source);
}
}
I wish to have an applet for this code but I don't know much about applets. I wish to use some buttons instead of typing. I know codes to add buttons but don't know how to use them. Need help on it, all replies would be appreciated.
And yes , also tell how is this game (rate this game), but rate as if a newbie as made it.
Now, instead of going on full ask on how to convert it into an applet I wish to ask it in small blocks. First of all how shall I use a button and tell my PC how to proceed?
This is my code:
import java.awt.*;
public class Buttonsuse extends java.applet.Applet
{
Button invest , sell , check ;
public void init()
{
setBackground (Color.white);
setLayout(new FlowLayout (FlowLayout.CENTER,10,10));
invest = new Button("Invest");
sell = new Button("Sell");
check = new Button("Check");
add(invest);
add(sell);
add(check);
}
}
Now, how shall I know and tell the computer that a button is pressed, like if user presses invest button, it prints "you wish to invest".
How shall I do that?
Your current program is little more than a large static main method with a few small supporting static methods. Since this code is very linear, as most console programs are, and since it has no OOP-compliant classes, there is no way to directly convert or re-use any of this code to use in an event-driven GUI. I suggest:
Extract out the logic or brains behind your program into true OOP classes with instance fields, constructors and non-static methods.
Only after doing this should you consider creating a GUI to display the logic.
Read a decent book on OOP and Java such as "Thinking in Java" as this will help you think and code in an OOP way.
Non-GUI Classes to consider:
Stock classes with String name, double (or BigDecimal) value, String abbreviated name
Player that holds a String for name, a HashMap<Stock, Integer> for Stocks held and number of shares.
Market where a player can buy and sell Stocks.
The bottom line is that there is no one single simple way to "convert" this code to a GUI, and instead you should focus on learning Java fundamentals, and experiment with your code while learning (for that's how you learn).