Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Hello to all and best wishes for 2014.
My question is ... In the following program is it possible to replace the ht = Clavier.lireDouble () to simplify the package because every time I implement this command I have to create a class "Clavier.java "this increased the source code ?
Thank you for your answers
best regards
NOTE FROM EDITOR
Clavier is the French translation of keyboard. The Clavier class seems
to be used for educational purpose. The question asked here could be
"How can my java program read a value from the keyboard input?"
Billing program for lectuire a price exclusive of tax and VAT calculation and VAT and price discounts based on cost
r0%
1000 <= r1%
2000 <= r3%
r5%> = $ 5000 */
/Program (In french)/
public class Tva
{
public static void main (String[]args)
{
double ht;
double ttc, net, tauxr, remise;
double taux_tva = 21.6;
System.out.print ("donnez le prix hors taxe :");
ht = Clavier.lireDouble(); /*Replace this command*/
ttc = ht * (1. + taux_tva/100);
if (ttc < 1000.) tauxr = 0;
else if (ttc < 2000) tauxr = 1.;
else if (ttc < 5000) tauxr = 3.;
else tauxr = 5.;
remise = ttc * tauxr / 1000;
net = ttc - remise;
System.out.println ("Prix Ttc : "+ ttc);
System.out.println ("Remise : "+ remise);
System.out.println ("Net à payer : "+ net);
}
}
You can use the Scanner class for that purpose.
You code to replace can become
Scanner scan = new Scanner(System.in);
ht = scan.nextDouble();
One remark : my mother tongue is also French but IMHO I think it is better to code in English because it is always possible that you will have to share/submit... your code to people who don't understand your mother tongue so it will make things more difficult.
Ah I was about to forget it : because Clavier is a French word, you can be sure it never existed in Java or standard JDK.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 days ago.
Improve this question
This is what I want:
For example on some way to store 30 questions, code pick random one, show it to user, give him a three option for answer that he get, if he pick right one program continue.
Basically, I have in my mind how to make this, but I think so far its not on good way, because If I want to store many question there will be a lot of code that will repeat, and I'm sure there is a better way to do this.
I created Class like this:
public class QuestionsLevelEasy {
String question;
int answer;
public QuestionsLevelEasy(String question, int answer) {
this.question = question;
this.answer = answer;
}
// getter - setters
Method to return random question and let user choose answer:
public static void randomQuestionAndUserGuess() {
QuestionsLevelEasy q1 = new QuestionsLevelEasy("Who is best NBA player?", 1);
QuestionsLevelEasy q2 = new QuestionsLevelEasy("Who is best Football player?", 2);
QuestionsLevelEasy q3 = new QuestionsLevelEasy("Who is best Hokey player?", 3);
QuestionsLevelEasy q4 = new QuestionsLevelEasy("Who is best Tennis player?", 4);
List<QuestionsLevelEasy> givenList = List.of(q1, q2, q3, q4);
Random rand = new Random();
QuestionsLevelEasy randomElement = givenList.get(rand.nextInt(givenList.size()));
System.out.println("Here is your question, guess it right and continue: ");
System.out.println(randomElement.getQuestion());
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
for (QuestionsLevelEasy questionsLevelEasy : givenList) {
if (questionsLevelEasy.getAnswer() == choice) {
System.out.println("Correct!");
break;
} else {
System.out.println("Not Correct!");
break;
}
}
}
So, its easy to understand so far. Things that I' missing right now is to provide a user option menu to choose answer. So for example user get Who is best NBA player? show him 3 answers related on that question.
I tried to find some examples on how to achieve this but nothing useful so far, plus when I try to google How to create a list of questions and answers in Java google return me PDF of questions and answer from Java :D
The Answer by Eritrean is good in that it suggests defining a custom class to contain your question and answers.
I would take it a step further by (a) defining your custom class as a record since you have no need for setters (immutable object), (b) representing the correct answer as the ordinal number within the list of the offered answers, and (c) using List.of methods for simplicity.
Define the class in one brief line.
public record Question( String ask , List < String > answers , int solutionOrdinal ) { }
Use List.of to build some data.
package work.basil.example.quiz;
import java.util.List;
public class QuestionsRepository
{
// For now we hard-code some data.
// Later we could re-implement by reading CSV text files or hitting a database.
List < Question > fetchQuestions ( )
{
return
List.of(
new Question(
"Best programming language" ,
List.of(
"C" ,
"C++" ,
"Java"
) ,
3
) ,
new Question(
"Best beer" ,
List.of(
"Pilsner" ,
"Porter" ,
"IPA"
) ,
2
) ,
new Question(
"Non-existent color" ,
List.of(
"Magenta" ,
"Red" ,
"Blue"
) ,
1
) ,
new Question(
"Best programming font" ,
List.of(
"Pragmata by Fabrizio Schiavi" ,
"Menlo by Jim Lyles" ,
"Comic Sans by Vincent Connare"
) ,
1
)
);
}
}
Declare a Quiz class to present the questions and answers to the user.
Notice how we pass the content, the list of questions, to the constructor. This addresses the design principle of separation of concerns. The Quiz class is dedicated to presenting a quiz, not generating its content. The QuestionsRepository class is dedicated to retrieving a set of questions, not presenting to the user.
Also notice how we use Collections.shuffle to randomize the order of elements in our list of questions. This approach is simpler than picking questions randomly while tracking remaining questions.
package work.basil.example.quiz;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Quiz
{
private final List < Question > questions;
// Constructor
public Quiz ( final List < Question > questions )
{
List < Question > q = new ArrayList <>( questions ); // Make a modifiable list from a possibly unmodifiable list.
Collections.shuffle( q ); // Randomize the order of elements in this list.
this.questions = List.copyOf( q ); // Generate a new unmodifiable list.
}
public void present ( )
{
System.out.println( "Here is your quiz, with " + this.questions.size() + " questions." );
Scanner scanner = new Scanner( System.in );
for ( Question question : questions )
{
System.out.println( "--------| Question |-------------------------------------" );
System.out.println( question.ask() );
System.out.println( "Answers:" );
int ordinal = 0;
for ( String answer : question.answers() )
{
ordinal++;
System.out.println( ordinal + " | " + answer );
}
int choice = scanner.nextInt();
if ( choice == question.solutionOrdinal() )
{
System.out.println( "Correct." );
}
else
{
System.out.println( "Incorrect. Solution is: " + question.solutionOrdinal() );
}
}
}
}
Lastly, we write a class to run our app. This class harnesses our other classes.
package work.basil.example.quiz;
import java.util.List;
public class App
{
public static void main ( String[] args )
{
App app = new App();
app.demo();
}
private void demo ( )
{
QuestionsRepository qRepo = new QuestionsRepository();
List < Question > questions = qRepo.fetchQuestions();
Quiz quiz = new Quiz( questions );
quiz.present();
System.out.println( "Demo done. " );
}
}
When run:
Here is your quiz, with 4 questions.
--------| Question |-------------------------------------
Non-existent color
Answers:
1 | Magenta
2 | Red
3 | Blue
1
Correct.
--------| Question |-------------------------------------
Best programming font
Answers:
1 | Pragmata by Fabrizio Schiavi
2 | Menlo by Jim Lyles
3 | Comic Sans by Vincent Connare
1
Correct.
--------| Question |-------------------------------------
Best programming language
Answers:
1 | C
2 | C++
3 | Java
3
Correct.
--------| Question |-------------------------------------
Best beer
Answers:
1 | Pilsner
2 | Porter
3 | IPA
3
Incorrect. Solution is: 2
Demo done.
Write your questions with possible answers and the correct answer in a file, for example a csv.
Question; Choise1; Choise2; Choise3; Answer
For which NBA Team did Michael Jordan play for 13 years? Chicago Bulls; Washington Wizards; Dallas Mavericks; Chicago Bulls
...
...
Expand your question object with the fields question, choices and correct answer.
public class QuestionsLevelEasy {
String question;
List<String> choices;
String answer;
public QuestionsLevelEasy(String question, List<String> choices, String answer) {
this.question = question;
this.choices = choices;
this.answer = answer;
}
// getter - setters
}
Read the file and create QuestionsLevelEasy objects and show the user the question with the choices and compare the user input with the correct answer.
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 3 years ago.
Improve this question
1: Hi there. I don't know why my Java Cannot run. I think that my code is fine. Can anyone help me out?
This was the error message that was displayed after I run. The error message is displayed below.
It would be nice if someone can help me with this code. Thank you
This is the content of my file
A 1 50 3
B 2 1300 104
C 3 9000 900
D 4 1500
where
A - D Represents the transaction code
1 - 4 represents the Employeenumber
50, 1300,9000,1500 represents the retail price
and the last section represents the commission that I have calculated
This is the Question.
A transaction record on a sales commission file contains the retail price of an item sold, a
transaction code which indicates the sales commission category to which an item can belong,
and the employee number of the person who sold the item. The transaction code can contain
the values A, B or C which indicate that the percentage commission will be 6%, 8% or 10%
respectively. Construct an algorithm that will read a record on the file, calculate the commission
owing for that record and print the retail price, commission and employee number.
Convert this to Java
import java.util.Scanner;
import java.io.*;`
public class Question1
{
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner (new File ("C:\\Users\\leeli\\Desktop\\Assignment2Qns1.txt"));
double retailprice, commission;
String Empnum;
char transcode;
while(input.hasNext())
{
retailprice = input.nextDouble();
commission = input.nextDouble();``
Empnum = input.next();
transcode = input.next().charAt(0);
if (transcode == 'A' || transcode == 'a')
{
commission = retailprice *0.06;
}
else if (transcode == 'B' || transcode == 'b')
{
commission = retailprice *0.08;
}
else if (transcode == 'C' || transcode == 'c')
{
commission = retailprice *0.1;
}
else
{
commission = 0;
System.out.print("Invalid transaction code");
}
System.out.println("Transaction code \t Employee Number \t Retail Price \t Commission");
System.out.println(transcode + "\t" + Empnum +"\t" + retailprice +"\t" + commission);
}
}
}
//run:
//Exception in thread "main" java.util.InputMismatchException
//at java.util.Scanner.throwFor(Scanner.java:909)
//at java.util.Scanner.next(Scanner.java:1530)
//at java.util.Scanner.nextDouble(Scanner.java:2456)
//at Question1.main(Question1.java:18)
//Java Result: 1
//BUILD SUCCESSFUL (total time: 0 seconds)
Your order of reading from file matters a lot, you were getting the error because you were not reading the content in the correct order. You should read content in this order transcode, Empnum, retailprice, commission. This will fix your problem :
transcode = input.next().charAt(0);
Empnum = input.next();
retailprice = input.nextDouble();
commission = input.nextDouble();
Compare the input file and your code:
In the input file, a record consists of a letter followed by two or three numbers.
Your code is trying to read a record as two (floating point) numbers followed by two strings.
So your code is trying to read a letter as if it was a number. That won't work. That is what is causing the InputMismatchException exception.
Solution: Change your code to match the input file's format.
If your sample input file is accurate, changing the order of the nextXXX calls is not sufficient. That doesn't cope with the fact that the "commission" field is optional. Instead, you should read each record using Scanner::nextLine then create a new Scanner to parse the record.
For future reference: you can solve these problems yourself by doing the following:
Read the stacktrace to find the exception that was thrown, where it was thrown, and what your code called to get to the place where the exception was thrown.
Read the javadocs for the exception and (typically) the API method that your code called.
Figure out what the exception means in the context of your program and its input.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My homework is to create a program that tells how many calories you consumed depending on the numbers of cookies you ate. But when I run the program, it doesn't show anything and I need it to work for my homework.
Here's the code for more context:
package cookie.calories;
import java.util.Scanner;
public class CookieCalories {
public static void main(String[] args) {
Scanner ob = new Scanner(System.in);
int TotalNumberOfCookiesPerBag = 40;
int CaloriesPerServing = 300;
int ServingsPerBag = 10;
//The next equation represent the number of cookies per servings
int NumberOfCookiesPerServings = TotalNumberOfCookiesPerBag/ServingsPerBag;
//number of calories per cookies
int CaloriesPerCookies =CaloriesPerServing/NumberOfCookiesPerServings;
Scanner ob2 = new Scanner(System.in);
System.out.println("This programm can determined how many calories you ate depending on the number of cookie you ate.");
//Below this sentence, the amount of calories will be determined
System.out.println("Enter the number of cookies you ate");
int Cookies = ob.nextInt(4);
int TotalCaloriesConsumed = CaloriesPerCookies*Cookies;
System.out.println(TotalCaloriesConsumed + "for the amount of cookies you ate");
}
}
The program shows me that I didn't made any error in the way I wrote my program but when I play it, it doesn't show anything in the output. Why?
When I run your program I get this output
This programm can determined how many calories you ate depending on the number of
cookie you ate.
Enter the number of cookies you ate
when I enter (for example) 4 and press enter I get this error
Exception in thread "main" java.util.InputMismatchException: For input string: "4"
under radix 4
at java.base/java.util.Scanner.nextInt(Scanner.java:2264)
at testasdf.Testasdf.main(Testasdf.java:38)
Not really sure why you have "ob.nextInt(4);" instead of "ob.nextInt();" should change your code to be nextInt();
So I am unsure of why nothing is showing up for you, are you sure you have a output screen set up?
What IDE are you using?
Remove the '4' from the nextInt method params.
int Cookies = ob.nextInt();
Also you don't need another Scanner object, you can use the same one to get input from the user multiple times, so you can remove this from your code.
Scanner ob2 = new Scanner(System.in);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I had tried to do some calculations and something doesn't quite add up. I am trying to achieve the screenshot below
but this is what i'm getting
Please I need some help, this is what I have done so far
public class VelocityFall
{
public static void main (String [] a)
{
Scanner s = new Scanner (System.in);
System.out.print("This program prints a table that shows each \nsecond,"
+
"height from the ground (meters), and the velocity (m/s)\n of a free-falling" +
"object from an initial height (metres).\nPlease input the Initial Height H: ");
// input/get the value of H from the keyboard
double H = s.nextDouble ();
// we need to design/output the table by using println with lines and tabs (\t)
System.out.println ("------------------------------------------");
System.out.println (" t(s)\t\tHeight(m)\t\tVelocity(m/s)");
System.out.println ("------------------------------------------");
//we now require a for loop
for (int t = 0; t<=15; t++)
{
// we are now going to calculate and output the velocity and decreasing
height
double velocity = 9.8*t;
H = H-(0.5*9.8*Math.pow(t,2));
System.out.println(t + "\t\t" + H + "\t\t" + velocity);
}
}
}
Your problem is that you are reassigning the H variable in the line below.
H = H-(0.5*9.8*Math.pow(t,2));
Replace that line with the one below to get the right output.
double H_new = H-(0.5*9.8*Math.pow(t,2));
Don't forget to change the variable in your println call too:
System.out.println(t + "\t\t" + H_new + "\t\t" + velocity);
This way, the H variable stays equal to the user's input and your calculation isn't affected by the results of the previous calculation.
Output:
t(s) Height(m) Velocity(m/s)
------------------------------------------
0 1234.56 0.0
1 1229.6599999999999 9.8
2 1214.96 19.6
3 1190.46 29.400000000000002
4 1156.1599999999999 39.2
5 1112.06 49.0
6 1058.1599999999999 58.800000000000004
7 994.4599999999999 68.60000000000001
8 920.9599999999999 78.4
9 837.6599999999999 88.2
10 744.56 98.0
11 641.6599999999999 107.80000000000001
12 528.9599999999999 117.60000000000001
13 406.4599999999999 127.4
14 274.15999999999985 137.20000000000002
15 132.05999999999995 147.0
As for the issue of repeating digits, try using the DecimalFormat class.
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 6 years ago.
Improve this question
The code doesn't work right the program runs both if statements and the total never comes out right. I can't figure out whats wrong. what changes do i need to make for this to work? the directions are below.
The cost to become a member of a fitness center is as follows: (a) the Senior
citizens discount is 30%; (b) if the membership is bought and paid for 12 or
more months in advance, the discount is 15%; or (c) if more than 5 personal
training sessions are purchased, the discount on each session is 20%.
Write a menu driven program that determines the cost of a new membership.
Your program must contain a method that displays the general information about
the fitness center and its charges, a method to get all the necessary information
to determine the membership cost, and a method to determine the membership
cost. Use appropriate parameters to pass information in and out of a method.
what methods should i use?
double grossdiscount1,grossdiscount2,grossdiscount3;
double grossprice1,grossprice2,grossprice3;
//end result of box calculation
double answerbox1,answerbox2,answerbox3;
double answerbox1b,answerbox2b,answerbox3b;
//Jtext inputs
double box1,box2,box3;
double discount1 = 0.30 ;
double discount2 = 0.20 ;
double discount3 = 0.15 ;
// prices PT=personal training MT=montly price
double pricePT =50.00;
double priceMT =100.00;
box1 = Double.parseDouble(jTextField1.getText());
box2 = Double.parseDouble(jTextField2.getText());
box3 = Double.parseDouble(jTextField3.getText());
// i brought these out of the if statement because the program won't run without
// them being stated
answerbox1b=box1*100;
grossdiscount1=(box1*priceMT)*discount3;// the amount saved
grossprice1=(box1*priceMT);
answerbox1=(grossprice1-grossdiscount1);
answerbox2b=(box2*pricePT);
grossdiscount2=(box2*pricePT)*discount2;// the amount saved
grossprice2=(box2*pricePT);
answerbox2=(grossprice2-grossdiscount2);
double total = answerbox1+answerbox2+answerbox1b+answerbox2b;
grossdiscount3=(total*discount3);// the amount saved
grossprice3=total;
answerbox3=(grossprice3-grossdiscount3);
if(box1<11 )
{
answerbox1b=box1*100;
}
else if(box1>12)
{
grossdiscount1=(box1*priceMT)*discount3;// the amount saved
grossprice1=(box1*priceMT);
answerbox1=(grossprice1-grossdiscount1);
}
if(box2<5 )
{
answerbox2b=(box2*pricePT);
}
else if(box2>=5)
{
grossdiscount2=(box2*pricePT)*discount2;// the amount saved
grossprice2=(box2*pricePT);
answerbox2=(grossprice2-grossdiscount2);
}
if(box3==1 )
{
grossdiscount3=(total*discount3);// the amount saved
grossprice3=total;
answerbox3=(grossprice3-grossdiscount3);
}
else if(box3==0);
{
}
jTextField4.setText(String.valueOf(total));
The else if statements are not written correctly. Remove the ; for a correct flow.
And I also recommend you to check any of the threads related to comparing doubles in Java