I'm trying to make a simple guessing game where computer should guess the number I chose between 0 and 100. Try to run it, press 1 if the number is too low and press 2 if the number is too high.
1.if I choose 50 and computer guesses 41, I press 1 because the number is too low
2.then computer guesses between 41 and 100, say 70, I press 2 because it's too high
3.now the problem is that next the computer should be guessing between 70 and 41 (previously guessed number), but it guesses between 71 and 0, so it's jumping up and down all the time between extremes
4.I don't know how to make it remember the range ie. previously guessed number
System.out.print("Enter a number: ");
Scanner input = new Scanner(System.in);
int num=input.nextInt();
int ans=0;
Random rand = new Random();
int guess=rand.nextInt(100);
while(guess!=num) {
System.out.print("Is it " + guess + " ? ");
ans=input.nextInt();
if (ans==1) {
guess=rand.nextInt(100-guess+1)+guess;
}
else if (ans==2) {
guess=rand.nextInt(100-guess+1)+0;
}
}
System.out.print("Computer guessed: " + guess);
The output looks like this:
Enter a number: 50
Is it 55 ? 2
Is it 26 ? 1
Is it 35 ? 1
Is it 44 ? 1
Is it 54 ? 2
Is it 31 ? 1
Is it 39 ? 1
Is it 87 ? 2
Is it 0 ? 1
Is it 11 ? 1
Is it 97 ? 2
You should use 2 variables: One for upper limit, one for lower limit.
while(guess!=num) {
System.out.print("Is it " + guess + " ? ");
ans=input.nextInt();
if (ans==1) {
lowerLimit = guess; // Your new lower limit .
guess=lowerLimit+ (upperLimit- lowerLimit) * r.nextInt();
}
else if (ans==2) {
upperLimit = guess; // Your new upper limit.
guess=lowerLimit+ (upperLimit- lowerLimit) * r.nextInt();
}
}
This is what you need :
System.out.print("Enter a number: ");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int ans = 0;
Random rand = new Random();
int min = 0;
int max = 100;
int guess = rand.nextInt(max);
while (guess != num) {
System.out.print("Is it " + guess + " ? ");
ans = input.nextInt();
if (ans == 1) {
min = guess + 1;
} else if (ans == 2) {
max = guess;
}
guess = rand.nextInt(max - min) + min;
}
System.out.print("Computer guessed: " + guess);
sample output:
Enter a number: 50
Is it 62 ? 2
Is it 39 ? 1
Is it 41 ? 1
Is it 56 ? 2
Is it 54 ? 2
Is it 49 ? 1
Is it 52 ? 2
Computer guessed: 50
You need two variables. One for the lower limit and one for the upper limit.
Related
Im trying to implement a program in Java that a user inputs a number greater than 10 & another number (whatever number) then it will list whatever first number the user inputs for example if it was 11 then it'd print 1-11 with corresponding numbers in which it increases by 50 in the first half (1-6) and decreases 25 for the rest (7-11). I have the following code but im having trouble trying to figure out the logic/how to go about the values being increased/decreased.
again the output would be something like this:
1 550
2 600
3 650
4 700
5 750
6 800
7 775
8 750
9 725
10 700
11 675
import java.util.Scanner;
public class Periods2
{
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("enter the number of days in a given period:");
int numbers = 1;
int number = Integer.parseInt(reader.nextLine());
if(number < 10){
System.out.print("the number of days doesnt meet the required criteria enter it again:");
number = reader.nextInt();
}
System.out.print("enter the number of sharepoints:");
int sharepoints = Integer.parseInt(reader.nextLine());
while (numbers <= number && sharepoints > number){
System.out.println(numbers + " " + sharepoints);
numbers++;
}
}
}
Find the half of your input, and in your loop you can add 50 to sharepoints until the value of numbers reaches half, and then decrease by 25 after that:
int half = (int) Math.ceil(number/2.0);
while (numbers <= number && sharepoints > number){
System.out.println(numbers + " " + sharepoints);
if(numbers < half) {
sharepoints += 50;
}
else {
sharepoints -= 25;
}
numbers++;
}
My code is as follows:
import java.util.Scanner;
public class QuestionOne {
public static void main(String[] args) {
int numberofDays;
int sharePoints;
Scanner keyboard = new Scanner(System.in);
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
System.out.print("Share points on the first day: ");
sharePoints = keyboard.nextInt();
while (numberofDays < 10 || numberofDays > 20) {
System.out.println("The number of days doesn’t meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
numberofDays = keyboard.nextInt();
}
System.out.println("Day " + " Share Points");
for (int i = 1; i <= numberofDays; i++) {
if (numberofDays % 2 == 0)
if (i <= numberofDays / 2) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
}
else {
if (i <= numberofDays / 2 + 1) {
sharePoints = sharePoints + 50;
System.out.println(i + " " + sharePoints);
} else {
sharePoints = sharePoints - 25;
System.out.println(i + " " + sharePoints);
}
}
}
}
}
This code should output to something like (as an example if the user were to enter the values 11 for the day and 550 for share price):
Day Share Points
1 550
2 600
3 650
4 700
5 750
6 800
7 775
8 750
9 725
10 700
11 675
however when I enter 11 for the day, and 550 for the share price, my code looks like:
Day Share Points
1 600
2 650
3 700
4 750
5 800
6 850
7 825
8 800
9 775
10 750
11 725
From what I can tell according to my code, I have coded it so that it adds 50 every time until the number six- whereas I want it to display the first number as the user enters it in, then to start adding and subtracting accordingly (note that everything is as I want it in my output except for the first number, and the proceeding numbers, as a result, being different). My wording may not be very accurate, but I hope the example outputs are enough to explain what I want as my output.
Sometimes it can be useful to process a base case before a for loop.
In your case that would look like printing the appropriate line for day 1 and then starting your loop at i=2 instead of i=1.
Here is a quick look at the program that I made to give a better example of my question.
Loop code
public void scheme1(int d) {
// first modification
if (mark<=20){
System.out.print("\nBecause mark under 20 mark stays as its original value. mark="+mark);
return;
}
int total = mark;
int finalMark=20;
System.out.print("Scheme 1"+"\n");
// Loop
for(int loopParameter = START_CONDITION;
loopParameter <= d;loopParameter++){
System.out.print("(" + loopParameter + ") " + total + " ");
total = total + constantDiffSch1;
// second modification
if (total < 40){
System.out.print("\nThis work can be up to " + loopParameter);
return;
}
// third modification
if (total<=20){
System.out.print("\nBecause mark drops below 20, mark stays as 20. final mark="+ finalMark);
return;
}
} // End
System.out.print("\n\n");
}
This is what my program outputs
Please input mark: 64
Please input number of days to display: 10
Scheme 1
(0) 64 (1) 59 (2) 54 (3) 49 (4) 44
This work can be up to 4 days late before failing.
This is what the output is supposed to be
Please input mark: 64
Please input number of days to display: 10
Scheme 1
(0) 64 (1) 59 (2) 54 (3) 49 (4) 44 (5) 39 (6) 34 (7) 29 (8) 24
This work can be up to 4 days late before failing.
I have to display how many days late the assignment is and calculate the late penaltie (mark -5) I also have to display the number of days needed needed to fail the assigment ( number of days until failure might be larger than the number (d) of days that the user input ) . the failing mark is less than 40.
2nd example (output)
Please input mark: 64
Please input number of days to display: 2
Scheme 1
(0) 64 (1) 59 (2) 54
This work can be up to 4 days late before failing.
I have almost complete my code but this problem is slowing me down.
P.S. I am new at java
here is my full program
LatePenalties calss
public class LatePenalties {
// attributes
private int mark;
private static final int constantDiffSch1 = -5;
private static final double constantDiffSch2 = 0.9;
private static final int START_CONDITION = 0;
// constructors
public LatePenalties(int m) {
mark = m;
}
// methods
public void scheme1(int d) {
// first modification
if (mark<=20){
System.out.print("\nBecause mark under 20 mark stays as its original value. mark="+mark);
return;
}
int total = mark;
int finalMark=20;
System.out.print("Scheme 1"+"\n");
// Loop
for(int loopParameter = START_CONDITION;
loopParameter <= d;loopParameter++){
System.out.print("(" + loopParameter + ") " + total + " ");
total = total + constantDiffSch1;
// second modification
if (total < 40){
System.out.print("\nThis work can be up to " + loopParameter);
return;
}
// third modification
if (total<=20){
System.out.print("\nBecause mark drops below 20, mark stays as 20. final mark="+ finalMark);
return;
}
} // End
System.out.print("\n\n");
}
public void scheme2(int d) {
double total = mark;
System.out.print("\n\nScheme 2"+"\n");
// Loop
for(int loopParameter = START_CONDITION;
loopParameter <= d;loopParameter++){
System.out.print( "(" + loopParameter + ") " );
System.out.printf("%.02f",total);
System.out.print(" ");
total = total * constantDiffSch2;
} // End
System.out.print("\n");
}
}
Main class
import java.util.Scanner;
public class LatePenaltiesUser {
public static void main(String [] args) {
// local variables
Scanner input = new Scanner(System.in);
LatePenalties latePen;
int mark;
int days;
// input
do{
System.out.print("Please input mark (between 0 and 100) --> ");
mark = input.nextInt();
if (( mark < 0 ) | (mark > 100 )){System.out.print("\n" + "Input value outside the range!!!" + "\n");}
}while(( mark < 0 ) | (mark > 100 ));
do{
System.out.print("Please input number of days to display (between 0 and 20) --> ");
days = input.nextInt();
System.out.print("\n");
if (( days < 0 ) | (days > 20 )){System.out.print("Input value outside the range!!!"+ "\n");}
}while(( days < 0 ) | (days > 20 ));
// computation
latePen = new LatePenalties(mark);
latePen.scheme1(days);
latePen.scheme2(days);
}
}
I have to show when the faling mark occurs(at less than 40), but I have to stop the loop at 20 or when the number of days is reached, as I show in the example on what it is expected.
You can use break to come out of the loop as soon as total is less than 40. You can update your scheme1 method as below
public void scheme1(int d) {
int total = mark;
System.out.print("Scheme 1" + "\n");
int days = 0;
// Loop
for (int loopParameter = START_CONDITION; loopParameter <= d; loopParameter++) {
System.out.print("(" + loopParameter + ") " + total + " ");
total = total + constantDiffSch1;
if(total < 40)
break;
days++;
} // End
if (total <= 40) {
System.out.print("\nThis work can be up to " + days +" days late before failing.");
}
System.out.print("\n\n");
}
Please input mark (between 0 and 100) --> 82
Please input number of days to display (between 0 and 20) --> 10
Scheme 1 (0) 82 (1) 77 (2) 72 (3) 67 (4) 62 (5) 57 (6) 52
(7) 47 (8) 42
This work can be up to 8 days late before failing.
You don't need to know your loopParameter to calculate the number of days. You can calculate it like so:
int days = (d - 40) / -constantDiffSch1;
You can use break when you want to quit loop. So:
if (total < 20) break;
And off topic. Don't call loopParameter like that. It is good practice to call it in one symbol (or short word) like i or day. It makes code easier to read and understand.
My program is meant to add up all the even integers between 2 and an input number which is between 20 and 60. The logic for that is correct and will work, but it's supposed to be able to run again if the user wishes, and when it runs again, the input only changes if you input a new integer higher than the previous iteration. If you enter one lower, it just uses the same integer input as before. Here is the code:
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
int input;
int i = 2;
int sum = 0;
int restart;
do
{
System.out.print ("\nEnter a value between 20 and 60: ");
input = scan.nextInt();
if (input >= 20 && input <= 60) // checks validity of input
{
while (i <= input)
{
sum = sum + i;
i = i + 2;
}
System.out.println ("\nSum of even numbers between 2 and " +
input + " is: " + sum);
}
else
{
System.out.println ("\nInput is not between 20 and 60. ");
}
System.out.print ("\nEnter a new value? (1 for yes, any other number
for no): ");
restart = scan.nextInt();
} while (restart == 1);
}
}
So for example, if I enter 20 as the input, the program outputs:
Sum of even numbers between 2 and 20 is: 110
Enter a new value? (1 for yes, any other number for no):
and then I enter 30 (same run of the program):
Sum of even numbers between 2 and 30 is: 240
Enter a new value? (1 for yes, any other number for no):
and then I try to enter 20 again:
Sum of even numbers between 2 and 20 is: 240
Enter a new value? (1 for yes, any other number for no):
(Should clearly be 110, not 240)
My initial thought was that it wasn't actually scanning for a new input on the second iteration, but because it will work if I keep giving it inputs of greater value I know that is not true.
Use this code inside main()
Scanner scan = new Scanner (System.in);
int input;
int i = 2;
int sum = 0;
int restart;
do
{
System.out.print ("\nEnter a value between 20 and 60: ");
input = scan.nextInt();
if (input >= 20 && input <= 60) // checks validity of input
{
i = 2;
sum = 0;
while (i <= input)
{
sum = sum + i;
i = i + 2;
}
System.out.println ("\nSum of even numbers between 2 and " +
input + " is: " + sum);
}
else
{
System.out.println ("\nInput is not between 20 and 60. ");
}
System.out.print ("\nEnter a new value? (1 for yes, any other number for no): ");
restart = scan.nextInt();
} while (restart == 1);
Beginner here. So I want to write a program that prints out all the prime numbers up to the number the user entered. E.g., user enters 5, program prints out 2 and 3. That part I understand, however what I am struggling with, is what if I want the program to print out whether the number the user entered is a prime or not (simple yes or no) IF the entered number is bigger than, let's say, 50. Here is code for first part:
public class Primes {
public static void main(String args[]) {
System.out.println("All primes up to: ");
int num = new Scanner(System.in).nextInt();
System.out.println("Prime numbers from 1 to " + num + " are: ");
for(int number = 2; number<=num; number++){
if(isPrime(number)){
System.out.println(number);
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
I honestly can't wrap my around as to what I should be doing next. My first program ever ("Hello world" does not count ;P).
Edit :
Your current code seems to work fine.
As per your doubt as mentioned in one of the comments : Yes, but where do I add if statement that does the following: if the number entered is below 50, then the program prints out all the prime numbers up to the entered number. If the number the user entered is bigger than 50, it tells only whether the entered number is prime or not ( simply "It's a prime" or "No, it's not a prime"). Hope that made things clearer
The check you need to put is after you take the input :
int num = new Scanner(System.in).nextInt();
if( number > 50 )
{
if(isPrime(number))
{
// print out is prime
}
// print out it is not prime
}
else
{
System.out.println("Prime numbers from 1 to " + num + " are: ");
for(int number = 2; number<=num; number++){
if(isPrime(number)){
System.out.println(number);
}
}
}
SUGESTIONS :
However, just to touch upon the algorithmic part, I would recommend using Sieve of Eratosthenes for picking out all the prime numbers within a given range, as you need in your case.
Example :
To find all the prime numbers less than or equal to 30, proceed as follows:
First generate a list of integers from 2 to 30:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Strike (sift out) the multiples of 2 resulting in:
2 3 5 7 9 11 13 15 17 19 21 23 25 27 29
The first number in the list after 2 is 3; strike the multiples of 3 from the list to get:
2 3 5 7 11 13 17 19 23 25 29
The first number in the list after 3 is 5; strike the remaining multiples of 5 from the list:
2 3 5 7 11 13 17 19 23 29
The first number in the list after 5 is 7, but 7 squared is 49 which is greater than 30 so the process is finished. The final list consists of all the prime numbers less than or equal to 30.
Here's the code attached for reference ( Disclaimer : I'm picking up this code here from this site. Just pasted it here for more immediate visibility).
Code :
public class PrimeSieve {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= N; i++) {
if (isPrime[i]) primes++;
}
System.out.println("The number of primes <= " + N + " is " + primes);
}
}
Try this..
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
this is more efficient way tough:-
public boolean isPrime(int n) {
// fast even test.
if(n > 2 && (n & 1) == 0)
return false;
// only odd factors need to be tested up to n^0.5
for(int i = 3; i * i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
however what I am struggling with, is what if I want the program to print out whether the number the user entered is a prime or not (simple yes or no).
Your current isPrime function seems to work, so just ask for a number and test it.
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
if (isPrime(num)) {
System.out.printf("%d yes%n", num);
} else {
System.out.printf("%d no%n", num);
}
}
Or with a ternary,
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
System.out.printf("%d %s%n", num, isPrime(num) ? "yes" : "no");
}
Edit Based on your comment, move your print up sequence to a method
public static void primesUpTo(int num) {
System.out.println("Prime numbers from 1 to " + num + " are: ");
for (int number = 2; number <= num; number++) {
if (isPrime(number)) {
System.out.println(number);
}
}
}
Then
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
if (num > 50) {
System.out.printf("%d %s%n", num, isPrime(num) ? "yes" : "no");
} else {
primesUpTo(num); // <-- call the method above.
}
}
If i understand the question right:
If user enteres number lesser than or equal to 50, then print all primes that are lesser than that number.
Otherwise, just write if inputted number is a prime.
With already existing isPrime() method:
int num = new Scanner(System.in).nextInt();
if (num <= 50) {
System.out.println("Prime numbers from 1 to " + num + " are: ");
for (int number = 2; number <= num; number++) {
if (isPrime(number)) {
System.out.println(number);
}
}
} else { //num > 50
if(isPrime(num)) {
System.out.println(num + " is prime.");
} else {
System.out.println(num + " isn't prime.");
}
}