i have rewritten this in a do while loop but how can i make the division part retun/accept just three decimal place for example is if i get 1/4 i should be able to enter 0.25 and also if i get 1/7 i should be able to get 0.14.
import java.util.*;
public class HelloWorld
{
public static void main (String[] args)
{
Scanner keyboard=new Scanner(System.in);
Random quest=new Random();
int module,range,number,count,quest1,quest2,answer,score;
double result;
System.out.print("Enter module(1 for addition, 2 for subtraction, 3 for multiplication, 4 for division, -1 for exit)?");
module=keyboard.nextInt();
do{
System.out.print("Enter range of numbers(1-100)");
range=keyboard.nextInt();
System.out.print("How many questions do you want to practice(minimum 3)?");
number=keyboard.nextInt();
count=1;
score=0;
result=0;
while (count<= number)
{
quest1=quest.nextInt(range)+1;
quest2=quest.nextInt(range)+1;
if (module==1)
{
result=quest1+quest2;
System.out.print(quest1+"+" +quest2+"=");
}
else
{
if (module==2)
{
result=quest1-quest2;
System.out.print(quest1+"-" +quest2+"=");
}
else
{
if (module==3)
{
result=quest1*quest2;
System.out.print(quest1+"*" +quest2+"=");
}
else
{
if (module==4)
{
result=(double)quest1/quest2;
System.out.print(quest1+"/" +quest2+"=");
}
}
}
}
answer=keyboard.nextInt();
if(answer==result)
{
score=score+1;
System.out.println("you are correct!");
}
else {
System.out.println("You are wrong, the correct answer is " +result);
}
count=count+1;
if(count>number)
{
System.out.println("you scored "+score+" out of "+number+".");
count=1;
score=0;
break;
}
}
System.out.print("Enter module(1 for addition, 2 for subtraction, 3 for multiplication, 4 for division, -1 for exit)?");
module=keyboard.nextInt();
}while((module>0) && (module<5));
System.out.println("The program is terminating......");
}
}
Simple put whatever you have in the while loop, into a do - while loop like so:
do{
// Execute whatever
} while(conditionIsTrue);
Note that the difference between a while loop and a do while is that the do while loop executes 1 time always and then loops, where the while loop may not execute not even once because of the condition.
Personally I prefer tu use the while loop.
Related
what I am looking to do is create a program that will randomly pick an integer between 1 and 100. Then, ask the user to guess it. Loop until they do, and after each incorrect guess tell them if they are too high or too low. I want to use two different methods to validate their input. One to test whether it is a valid int, the other to test the range (1-100). This second will require another parameter for the high range value.
The problems I am having:
1. I do not understand why I have to enter a number multiple times before my while (guess != a) { is triggered.
Example from console :
I am thinking of a number from 1 to 100 ... guess what it is ?6
I am thinking of a number from 1 to 100 ... guess what it is ?6
I am thinking of a number from 1 to 100 ... guess what it is ?6
6
higher!
2. how could I use my check methods and have them pertain to my while guess loop?
Example from console again:
`I am thinking of a number from 1 to 100 ... guess what it is? 10001
I am thinking of a number from 1 to 100 ... guess what it is? 10001
Error! Must be less than 100
I am thinking of a number from 1 to 100 ... guess what it is? 10001
100
lower!
10001
lower!`
{What I have full written currently}
package labbs;
import java.util.Scanner;
public class Lab12 {
public static double getDoubleGreaterThan(double low, Scanner input, String prompt) {
double num;
num = getDouble(input,prompt);
if(num <= low)
System.out.println("Error! Must be greater than 1");
num = getDouble(input,prompt);
if (num > 100)
System.out.println("Error! Must be less than 100");
num = getDouble(input,prompt);
return num;
}
public static double getDouble(Scanner input, String prompt) {
boolean OK;
double val=0;
do {
System.out.print(prompt);
OK = true;
try {
val = input.nextDouble();
}
catch(Exception e) {
OK = false;
System.out.println("Error! Invalid input. Must be a double value");
input.next();
}
}while(! OK);
return val;
}
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
double output, letscheck;
int count=0, guess=0;
int a=1 + (int) (Math.random() * 99);
letscheck = getDoubleGreaterThan(-0.9, keyboard,"I am thinking of a number from 1 to 100"
+ " ... guess what it is ?");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess > a) {
System.out.println("lower!");
} else if (guess < a) {
System.out.println("higher!");
}
}
System.out.println("Congratulations. You guessed the number with "
+ count + " tries!");
}
}
1. Query: You have just missed bracket in getDoubleGreaterThan()method as after if statement block always working not on the basis of input so change your code like below:
public static double getDoubleGreaterThan(double low, Scanner input, String prompt) {
double num;
num = getDouble(input,prompt);
if(num <= low){
System.out.println("Error! Must be greater than 1");
num = getDouble(input,prompt);
}
if (num > 100){
System.out.println("Error! Must be less than 100");
num = getDouble(input,prompt);
}
return num;
}
I am required to write a recursive method. I have written the code to perform the task without recursion. I am getting the error Exception in thread "main" java.lang.StackOverflowError at Exercise13r.recursion(Exercise13r.java:29). Code is... to enter a number then if result is even, divide by 2, if result is odd, multiply by 3 and subtract 1. Obviously I am looping but not sure why. Any assistance would be appreciated.
import java.util.Scanner;
public class Exercise13r
{
public static void main(String[] args)
{
// Initialize variables
long number = 0;
Scanner in = new Scanner(System.in);
System.out.println ("Enter a starting number: ");
number = in.nextInt ();
System.out.println ("Your starting number is: " + number);
if (number != 1)
{
recursion(number);
}
}
public static void recursion(long n)
{
if (n % 2 == 0)
{
recursion(n/2);
}
else
{
recursion(n*3-1);
}
System.out.println ("number: " + n);
return;
}
}
Your base case if (number != 1) needs to be inside the definition of the function so that it actually knows when to stop. Right now your program eventually reduces to calling recursion(1) and your function will still call itself recursively (what else can it do?) so it ends up calling recursion(2) which leads to recursion(1) again and so on.
Note that this becomes apparent if you move System.out.println ("number: " + n); before the recursive calls. Since you have infinite recursion it never gets around to printing anything preventing you from seeing the problem.
Here is a minimal working example:
class Exercise13r {
public static void main(String[] args) {
recursion(12);
}
public static void recursion(long n) {
System.out.println ("number: " + n);
if (n != 1) {
if (n % 2 == 0) {
recursion(n/2);
} else {
recursion(n*3-1);
}
}
}
}
Output:
number: 12
number: 6
number: 3
number: 8
number: 4
number: 2
number: 1
My code is supposed to simulate something similar to a vending machine. But there is a problem when I enter a price that is not one of my options, e.g. 0.82 the program still runs. How do I get it to only accept one of my options?
import java.util.Scanner;
public class VendingMachine
{
public static void main (String[] args)
{
double price;
Scanner keyboard = new Scanner(System.in);
System.out.println("Choose your price. Your options are: ");
double i;
for (i=0.25; i<=1.25; i+=0.25)
System.out.printf("$%.2f\n", i );
System.out.println("Enter your selection now: ");
price=keyboard.nextDouble();
System.out.printf("You chose the $%.2f option. ",price);
double deposit;
if (price<=1.00) {
System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
deposit=1;
} else {
System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
deposit=2;
}
System.out.println("Please press 'Enter' to simulate inserting money. ");
new Scanner(System.in).nextLine();
double change;
change = deposit-price;
System.out.printf("Your change is $%.2f\n",change);
}
}
I tried something like this but it doesn't work. What is the best way to do this.
if (price==i)
System.out.println("You entered " + price);
else {
System.out.println("Invalide choice. Please try again.")
System.exit(0);
}
Here is an image if you find it easier to read.
You can use some sort of loop (while, do-while, for), which will continue to excecute the code until a condition is (or isn't) met.
Here is an example:
do {
code line 1;
code line 2;
code line 3;
...
} while(yourCondition);
If yourCondition is satisfied (yourCondition == true), the code will go back to code line 1 (will perform the code block between do and while) and it'll stop once the condition isn't satisfied(yourCondition == false). yourCondition could be any expression that returns a true/false result (boolean), such as 2+2==4.
If you want to keep looping for as long as yourCondition isn't met, you can add a ! before your expression, which will evaluate the opposite of your boolean like this (!yourCondition).
Now, if you understood how that works, you can easily apply it to your code.
If you want the user to enter only your displayed prices, I suggest the following, you shall edit to your exact desires.
//given you an open scanner
boolean isCorrectPrice = false;
System.out.println("enter price");
price = in.nextDouble();
while(!isCorrectPrice)
{
if(price%0.25==0 && price<=1.25 && price>0)
{
System.out.println("you entered "+price);
IsCorrectPrice = true;
continue;
}
System.out.println("incorrect price, re-enter ");
price = in.nextDouble();
}
//your code after user enters correct price
That will do the check. If your prices change, all you have to do is change the maximum price provided its still dividable with 0.25 or the condition price check.
Use BigDecimal (instead of double) to work with money. Its exact -- double isn't.
http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html
I would write a function to get the user input. It would not return until the
user had entered an allowed value.
Although my real answer is the one on the comments, you can use something like this. To check recursively if the correct value was given.
import java.util.Scanner;
public class VendingMachine {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Choose your price. Your options are: ");
for (double i = 0.25; i <= 1.25; i += 0.25) {
System.out.printf("$%.2f\n", i);
}
double price = checkMultipleValues(0.25,1.25, 0.25);
System.out.printf("You chose the $%.2f option. ", price);
double deposit;
if (price <= 1.00) {
System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
deposit = 1;
} else {
System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
deposit = 2;
}
System.out.println("Please press 'Enter' to simulate inserting money. ");
new Scanner(System.in).nextLine();
double change;
change = deposit - price;
System.out.printf("Your change is $%.2f\n", change);
}
private static double checkMultipleValues(double initial,double last,double step) {
System.out.println("Enter your selection now: ");
double price = keyboard.nextDouble();
for (double i = initial; i <= last; i += step) {
if (price == i) {
return price;
}
}
return checkMultipleValues( initial, last, step);
}
}
ADDENDUM
Since you like #Sello answer why don't you combine it with #MrD and have something like
do {
System.out.println("enter price");
price = in.nextDouble();
// System.out.println("you entered " + price);
} while (!(price % 0.25 == 0 && price <= 1.25 && price > 0));
I am trying to code a number guessing class and client.
The issue/problems I am having with this class/client is that my number guess either ends up too high or too low and in top of that it loops the number twice when it should once.
Number generated from 0 to 100. Wanna take a guess(enter 0 to give up)
Let's take a guess:
50
40
Your guess is too low
What possible change can I make to improve the overall loop or change.
Here is my code for anyone that wants to look at it.
import java.util.Random;
public class NumberGuess
{
private Random generator;
private int Number;
int intGuess= (1 + (int)(Math.random()*100));
int numGuess=0;
boolean isGuessCorrect=false;
public NumberGuess(){
}
int numguess;
public int guess(int guessIn){
int numguess=guessIn;
if(numguess>intGuess){
return 1;
}else if(isGuessCorrect){
return 0;
}else{
return -1;
}
}
public int getNumberofGuesses(){
return numGuess;
}
public boolean gameIsComplete(){
if(isGuessCorrect){
return true;
}else{
return false;
}
}
public void reset(){
intGuess=(1 + (int)(Math.random()*100));
numGuess=0;
isGuessCorrect=false;
}
}
Client class
import java.util.Scanner;
public class NumberGuessclient{
public static void main(String[] args){
NumberGuess game1=new NumberGuess();
Scanner scan = new Scanner(System.in);
int quit=1;
while(quit != 0) {
System.out.println("Number generated from 0 to 100. Wanna take a guess(enter 0 to give up)");
System.out.println("Let's take a guess: ");
int guess1= scan.nextInt();
while((guess1 != 0)||(!game1.gameIsComplete())) {
guess1 = scan.nextInt();
if (game1.guess(guess1)==1){
System.out.println("Your guess is too high");
}
else if(game1.guess(guess1)==-1) {
System.out.println("Your guess is too low");
}
else { System.out.println("guessed in " + game1.getNumberofGuesses() + " tries");
}
}
System.out.println("Enter 1 for new game, 0 to quit: ");
quit = scan.nextInt();
if(quit==1){
game1.reset();
}
}
}
}
source code for more ELABORATION if not clarified above.
NumberGuess Class:
The NumberGuess class will facilitate a number guessing game. The constructor should generate a random number, saving the number in a private class field. The class should also define a method which accepts a "guess", compares the "guess" to the randomly generated number, and returns one of the following:
• -1 the guess was less than the secret number
• 0 the guess matched the secret number
• 1 the guess was higher than the secret number
Determine whether other methods, constructors or otherwise, would be useful for this class.
The Java API defines a Random class for generating random numbers. The class can be reviewed in the API or in your textbook beginning on page 250. Consider limiting the range of the random number. For instance, a number between 0 and 100.
Client Application:
The client application allows the end-user to play the number guessing game. Below is a sample run. Your application does not need to match.
I'm thinking of a number between 0 and 100. Can you guess it?
Take a guess: 50
Your guess is too high
Another guess? (Y or N): y
Take a guess: 25
Your guess is too high
Another guess? (Y or N): y
Take a guess: 10
Your guess is too low
Another guess? (Y or N): y
Take a guess: 15
Your guess is too low
Another guess? (Y or N): y
Take a guess: 18
Your guess is too low
Another guess? (Y or N): y
Take a guess: 20
Congratulations! You correctly guessed the secret number in 6 tries.
There are quite a bit of things that you can change, for instance:
There's no need to call game1.guess(guess1) more than once every loop.
The completion method is quite long...
You should call scan.nextInt() before entering the while loop...
I'm assumming the last output was manually generated, because you never increment numguess
The guess(int) method doesn't work...
I'm not usually one to do homework... but (I'm having a good day...!):
import java.util.Random;
import java.util.Scanner;
public class NumberGuessclient {
private static final String[] ANS = {
"Your guess is too low\n",
"guessed in %d tries\n",
"Your guess is too high\n"
};
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
NumberGuess game = new NumberGuess();
System.out.println("Number generated from 0 to 100. Wanna take a guess(enter 0 to give up)");
System.out.println("Let's take a guess: ");
while (!game.isGameComplete()) {
System.out.format(ANS[game.guess(scan.nextInt())+1], game.getNumberofGuesses());
}
System.out.println("Enter 1 for new game, 0 to quit: ");
if (scan.nextInt() != 1) {
System.out.println("Bye!");
System.exit(0);
}
}
}
}
class NumberGuess {
private static final Random RAND_GENERATOR = new Random(System.nanoTime());
int intGuess = RAND_GENERATOR.nextInt(101);
int numGuess = 0;
boolean isGuessCorrect = false;
public int guess(int guessIn) {
numGuess++;
if (guessIn > intGuess) {
return 1;
} else if (guessIn == intGuess) {
isGuessCorrect = true;
return 0;
} else {
return -1;
}
}
public int getNumberofGuesses() {
return numGuess;
}
public boolean isGameComplete() {
return isGuessCorrect;
}
}
Now one comment: as I recall the "fun" of this game was that you should always "guess" the number in at the very most 10 tries, you could implement that...
I have used Euclid's method to find the L.C.M for two numbers.
l.c.m=a*b/(gcd(a,b))
How can I do this without using this algorithm?
I have an idea of first getting all factors of these two numbers and storing them in array. Then take 1 element from array 1 and search for it in array2, if it present there then remove it from there and make the result multiply by that num.
Is this OK?
Almost. What's the LCM of 4 and 8? Obviously 8 (23), but in your method you'd find 2. You need to keep track not just of all factors, but also how often they appear.
I believe the algorithm you suggest is a method using a table, check to see if it works for you.
LCM(Least Common Multiple) is always greater than or equal to the larger of the two numbers. So we will first check that the larger number itself a LCM of two numbers by checking that the larger number is divisible by the smaller one , if yes we found the LCM & If no then we will increment the larger number by 1 and check again.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the first Number : ");
int number1 = scan.nextInt();
System.out.print("Enter the second number : ");
int number2 =scan.nextInt();
int multiple;
if(number1 >= number2) {
multiple = number1;
} else {
multiple = number2;
}
Boolean loopContinue = true;
while(loopContinue) {
if(multiple % number1 == 0 && multiple % number2 == 0) {
System.out.println("LCM of Two Numbers is " + multiple);
loopContinue = false;
}
multiple++;
}
}
}
You can get LCM of two number by getting GCD at first.
Here is the solution for the above.
package com.practice.competitive.maths;
import java.util.Scanner;
public class LCMandGCD {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int testCases = scanner.nextInt();
while (testCases-- > 0) {
long number1 = scanner.nextInt();
long number2 = scanner.nextInt();
long gcd = computeGCD(number1, number2);
long lcm = computeLCM(number1, number2, gcd);
System.out.println(lcm + " " + gcd);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static long computeGCD(long number1, long number2) {
while (number1 != number2) {
if (number1 > number2)
number1 -= number2;
else
number2 -= number1;
}
return number2;
}
private static long computeLCM(long number1, long number2, long gcd) {
return (number1*number2)/gcd;
}
}