UPDATED
How can you by using this method (Collatz conjecture) to find the number with the highest number of operations between, say 4 and 230.
Any guidance appreciated.
public static void main(String[] args) {
System.out.print("Enter a low integer ");
Scanner input = new Scanner(System.in);
int low = input.nextInt();
System.out.print("Enter a high integer ");
int number = input.nextInt();
maxendurance(number);
}
public static int maxendurance(int number) {
int count = 0;
System.out.print("The number " + number);
// need to loop this i suppose in relative to user input
while (number != 1) {
number = (number & 1) != 0 ? number * 3 + 1 : number >> 1;
count++;
}
System.out.println(" has endurance: " + count);
return number;
}
You will have to loop through all the numbers between low and high. Look into for-loops:
for(int number = low; number <= high; number++)
{
// do something with number
}
Somehow you will need to execute a for every number within the loop (hint: pass it in as a parameter). Then keep track of the number with the highest count.
Oh, and please name your methods more clearly than a and b - nobody will understand what they do without going through the code.
First of all, move the input out of method a:
public static void main(String[] args) {
System.out.print("Enter an integer to be checked: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
a(number);
b();
}
public static int a(int number) {
int count = 0;
System.out.print("The number " + number);
[...]
Then you can use a simple for loop to iterate between low and high:
int bestNumber = -1;
int bestScore = -1;
for (int i = low; i <= high; i++) {
int score = a(i);
if (score < bestScore) {
bestNumber = i;
bestScore = score;
}
}
The result can then be found in bestNumber.
I am going to suggest a more advanced approach, in case relevant and incase anyone comes upon this. If you are concerned about time efficiency, Memoization or Dynamic Programming can help you, especially inverse dragon recursion.
I'll give you a hint. If you need more, just comment.
Take 3 for example. One transformation T has T(3)=10. If prior you had found it takes v transformations to take 10 to 1 and you stored (10,v) in a map, then instantly you know that it takes (v+1) steps to get 3 to 1.
Related
I'm trying to write a code which will show the highest, lowest, the difference of them and the average of inputted 30 numbers.
But its not working and is showing the same result for both min and max numbers. Here is the code.
public class aa {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] daystemp = new int[30];
int i = 0;
int dayHot = 0;
int dayCold = 0;
while(i < daystemp.length){
daystemp[i] = input.nextInt();
i++;
}
int maxTemp = daystemp[0];
while (i < daystemp.length) {
if (daystemp[i] > maxTemp) {
maxTemp = daystemp[i];
dayHot = i + 1;
i++;
}
}
System.out.println(maxTemp);
int minTemp = daystemp[0];
while (i < daystemp.length) {
if (daystemp[i] < minTemp) {
minTemp = daystemp[i];
dayCold = i + 1;
i++;
}
}
System.out.println(minTemp);
int diff = maxTemp - minTemp;
System.out.println("The difference between them is"+diff);
double sum = 0;
while(i < daystemp.length) {
sum += daystemp[i];
i++;
}
double average = sum / daystemp.length;
System.out.println("Average was"+average);
}
}
After the first loop (the input loop), i value is daystemp.length (i.e. 30).
It's never reset to 0. So each while loop condition is false.
Add i=0 before the loops and do i++outside the ifblocks or your code will never end.
example:
i=0;
int maxTemp = daystemp[0];
while (i < daystemp.length) {
if (daystemp[i] > maxTemp) {
maxTemp = daystemp[i];
dayHot = i + 1;
}
i++;
}
A few notes about this solution:
By declaring the cumulative total double, no casting is required.
Because Java knows you want to convert int to double automatically if you assign an int to a declared double. Similary the fact that you want to express a result as double is implied when dividing a double by an int, such as when the average is taken. That avoids a cast also. If you had two ints and you wanted to produce a double you'd need to cast one or more of them, or in cases like a print statement where the compiler can't deduce the optimal type for the parameter, you'd need to explicitly cast to covert an int value to a double.
Not sure what OS you're running this on. The ideal situation would be to make it work on all platforms without requiring people type a magic word to end input (because how tacky). The easiest way to end input is to use the OS-specific end of input (end of file) key combination, and for Linux it's CTRL/D, which is how I explained it in the prompt. On another OS with a different end of input sequence you could just change the prompt. The trickiest would be if it is supposed to be truly portable Java. In that case I'd personally investigate how I could figure out the OS and/or End of File character or key combination on the current OS and modify the prompt to indicate to end input with whatever that is. That would be a bit of and advanced assignment but a very cool result.
Example illustrates use of a named constant to determine the array and is used limit the amount of input (and could be used to limit loop count of for loops accessing the array).
By setting the min and max to very high and low values respectively (notice the LOW value assigned to max and HIGH value assigned to min, those ensure the first legit temp entered will set the min and max and things will go from there).
Temperature Maximum, Minimum, Average and Difference Calculator
import java.util.Scanner;
public class TemperatureStats {
final static int MAX_DAYS = 31;
public static void main(String[] args) {
int[] dayTemps = new int[MAX_DAYS];
double cumulativeTemp = 0.0;
int minTemp = 1000, maxTemp = -1000;
Scanner input = new Scanner(System.in);
System.out.println("Enter temps for up to 1 month of days (end with CTRL/D):");
int entryCount = 0;
while (input.hasNextInt() && entryCount < MAX_DAYS)
dayTemps[entryCount++] = input.nextInt();
/* Find min, max, cumulative total */
for (int i = 0; i < entryCount; i++) {
int temp = dayTemps[i];
if (temp < minTemp)
minTemp = temp;
if (temp > maxTemp)
maxTemp = temp;
cumulativeTemp += temp;
}
System.out.println("High temp. = " + maxTemp);
System.out.println("Low temp. = " + minTemp);
System.out.println("Difference = " + (maxTemp - minTemp));
System.out.println("Avg temp. = " + cumulativeTemp / entryCount);
}
}
I am trying to write a program that accepts an integer from the user, then it should calculate this series S = 1/2! - 1/3! + 1/4! – 1/5! + .... all the way to 1/x! where x is the integer taken from the user, I already wrote this code to calculate the factorial of x :
import java.util.Scanner;
public class Factorial {
public static void main(String args[]){
Scanner x = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = x.nextInt();
int fact = 1;
for (int i = 1; i <= number; i++){
fact = fact*i;
}
System.out.println("The factorial of "+number+" is "+fact);
x.close();
}
}
but still am not sure how to code the series, any tips would be really appreciated.
Also I am sorry if my code is not organized I don't know how to use stackoverflow tools ;( .
Ideally, what you want is to separate your code into multiple functions, and think logically.
Since you said you didn't want tips, I'll just try to put you on the right track.
Tip 1:
Separate your code into multiple functions
eg.
public static int factorial(int n){
int fact = 1;
for (int i = 1; i <= n; i++){
fact = fact*i;
}
return fact;
}
This allows you to split your code up into manageable chunks. Call each chunk at the appropriate time. This makes your code easier to read and more reusable
Tip 2:
One main class and the other class with functions.
Ideally, you want to create two classes, one which takes input from the user and one which contains all the functions you need. The main class taking the input will create an Object of the other class
public class Factorial{
public static void main(String args[]){
Scanner x = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = x.nextInt();
Series s=new Series(number);
s.print();
x.close();
}
And in Series.java
public class Series{
int output;
int input;
Series(int i){
input=i;
//..here you calculate output
}
public int factorial(int n){
//.... the code
}
public void print(){
System.out.println("The calculation of " + input + " is " + output);
}
}
Tip 3:
Make a nice simple function to calculate the output. Sum up all your factorials over time
for (int i = 2; i <= input; i++) {
//if its even
if(i%2==0)
output = output + 1.0 / factorial(i);
else
output = output - 1.0 / factorial(i);
}
Add the following to your constructor and you'll have a well built Java program
Tip 4:: These sums are going to be decimals, not integers so you need to replace all your ints with doubles
First, you have to compute a sum of terms. The standard pattern is like
double sum = 0;
for (int i = first; i <= last; i++) {
sum += term(i);
}
then remark that
the first term is term(2) = +1/2!
the second term is term(3) = -1/3! = -term(2)/3
the third term is +1/4! = -term(3)/4
etc.
So you'll notice that each term can be easily obtained from the previous one.
This leads to
double sum = 0;
double term = (some value);
for (int i = first; i <= last; i++) {
term = (some expression involving i and previous term);
sum += term;
}
Exercise left as, huh, an exercise ?
This code compiles fine, but when I run it, it asks for my two numbers as expected and then just sits there and doesn't do anything at all. I've searched the Internet and worked on this all day. I'm finally caving and asking for help.
Is the issue that it's not looping back up automatically? After 10 hours at this, I've found nothing.
import java.util.Scanner;
public class EA
{
public static void main (String[] args)
{
// get first integer from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
//resolve the issue of zero
while(J<1)
{
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
//do the calculations
while(J>0)
{
int Remainder;
Remainder = I % J;
while(Remainder>0)
{
I = J;
J = Remainder;
return;
}
System.out.println("GCD is" + J);
}
}
}
}
Among other things already mentioned, you are confusing while with if. You have put your algorithm logic inside a while loop that only runs if the first input is bad.
// get first integer from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
//resolve the issue of zero
while(J<1)
{
// You never reach here under ordinary conditions
}
SJuan mention that the return breaks the loop, which is true, but even if it's fixed there are a few other issues:
The inner while never end (infinite loop)
The result will be stored in J - not in I
System.out.println("GCD is " + I); Should be printed outside of the outer while!
The "heart" of your program should do this:
// we get here with valid values stored in I,J
int Remainder = I % J;
//do the calculations
while(Remainder>0)
{
I = J;
J = Remainder;
Remainder = I % J;
}
System.out.println("GCD is " + J);
There are more than 1 error: the return in the while, the algorithm and the brackets of the first while.
1) When you resolve the issue of zero, the brackets of the while must be closed suddenly after you re-assign the value of the variable J.
while (J < 1) {
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
}
2) The algorithm for computing the gcd is the following:
function gcd(a, b)
while b ≠ 0
t := b
b := a mod t
a := t
return a
Here is the correct version of your code:
public static void main(final String[] args) {
// get first integer from user
final Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
// resolve the issue of zero
while (J < 1) {
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
}
// do the calculations
while (J != 0) {
int Remainder;
Remainder = I % J;
I = J;
J = Remainder;
}
System.out.println("GCD is" + I);
}
The return in the middle of the loop will end the execution.
This one
while(Remainder>0)
{
I = J;
J = Remainder;
return; <------- THIS IS THE RETURN THAT BREAKS ALL
}
so it does not get to the System.out.println.
UPDATE: Also, you do input.nextInt() twice for J. Probably from your description, it keeps waiting for you for entering the third integer.
Well Euclid's algorithm has a drawback as both the inputs should be non zero to compute the Greatest common divisor . But if you want to find out the GCD when one of the input is a zero ('0') tweak the logic a bit . When one of the input is zero the GCD is 1, and 'a' should be greater than 'b' to compute GCD. Check the snippet below:
if (a < b) {
int temp = a;
a = b;
b = temp;
}
if (b == 0) {
System.out.println("1");
} else {
while (b != 0) {
r = a % b;
a = b;
b = r;
}
I have been having a lot of trouble with this and it is due soon, and I was wondering if anyone knows how to fix my problem. I have to create a program where:
"Your task is to implement a number guesser that works on the principle of a binary search. In each step, the computer cuts the query interval in half. When the interval contains a single number, it proclaims the answer. The user of the program selects a number between 1 and 100. The computer is then asked to guess the number."
The sample output goes:
Is your number greater than 50? (computer is asking this)
no (user responds with yes or no)
Is your number greater than 25?
no
Is your number greater than 13?
no
Is your number greater than 7?
yes
Is your number greater than 10?
yes
Is your number greater than 12?
yes
Is your number 13?
yes
13 is the answer. (computer declares final answer)
Thank you for playing the guessing game.
My sample output in contrast goes:
Is your number greater than 50?
no
Is your number greater than 25?
no
Is your number greater than 13?
no
Is your number greater than 7?
yes
Is your number greater than 10?
yes
Is your number greater than 11?
yes
Is your number greater than 12?
yes
Is your number 12?
yes
12 is the answer.
Thank you for playing the guessing game.
with some variation based on what edits I make.
The code is as follows:
//import statements
import java.util.Scanner;
import java.util.ArrayList;
public class Numbers
{
//constant to initialize the ArrayList
private final int AT_MOST = 100;
//anArrayList of type ArrayList<Integer> which is to hold the values from 1 - 100
private ArrayList<Integer> anArrayList;
/**
* Constructor of the Numbers() class which initializes all of the instance fields
*/
public Numbers()
{
anArrayList = new ArrayList<Integer>();
int i =0;
//while loop to initialize anArrayList with values from 1-100
while(i < AT_MOST)
{
anArrayList.add(i+1);
i++;
}
}
public void search()
{
int low = 0;
int high = anArrayList.size();
int i = 0;
int j = 0;
while(low <= high)
{
int mid = (low + high)/2;
mid = anArrayList.get(mid - 1);
Scanner in = new Scanner(System.in);
System.out.println("Is your number greater than " + mid + "?");
String answer = in.nextLine();
if(answer.equalsIgnoreCase("yes"))
{
low = mid + 1;
}
else if (answer.equalsIgnoreCase("no"))
{
high = mid - 1;
low++;
}
if(low == high+1)
{
Scanner in2 = new Scanner(System.in);
System.out.println("Is your number " + mid + "?");
String finalAnswer = in2.nextLine();
if(finalAnswer.equalsIgnoreCase("yes"))
{
System.out.println(mid + " is the answer.");
System.out.println("Thank you for playing the guessing game.");
low = high + 1;;
}
else
{
System.out.println("Please play again, something went wrong!");
low = high + 1;
}
}
}
}
}
Of course this also has a tester class which is relatively short:
public class NumbersGuesser
{
public static void main(String[] args)
{
//creates a new numbers object
Numbers newNumber = new Numbers();
//run method is called, game is played.
newNumber.search();
}
}
Since you made an effort to solve the problem, I went ahead and restructured your Numbers class.
The first thing I did was get rid of the ArrayList. You can just as easily do arithmetic on integers as traverse the ArrayList.
I added a couple of integers, distance and direction. After each guess, the distance is cut in half. The computer guesses high or low until the distance is reduced to zero. At that point, the number is somewhere between the low and the high, inclusive.
The direction just tells us whether we need to guess lower (-1) or higher (+1) for the next guess.
I pulled the high low scanner code into its own method. It looks confusing at first, but all it does is tell us whether to guess higher (true) or lower (false). By moving this code into its own method, I could concentrate on the guessing logic.
Finally, I closed the scanner at the end of the processing.
//import statements
import java.util.Scanner;
public class Numbers {
// constants to start the game
private final int AT_LEAST = 0;
private final int AT_MOST = 100;
/**
* Constructor of the Numbers() class
*/
public Numbers() {
}
public void search() {
int low = AT_LEAST;
int high = AT_MOST;
int guess = (low + high) / 2;
int distance = guess / 2;
int direction = 1;
System.out.println("Guess a number between " + low + " and " + high
+ ".");
Scanner in = new Scanner(System.in);
do {
boolean greaterThan = getHighLowResponse(in, direction, guess);
if (greaterThan) {
low = guess;
guess += distance;
direction = 1;
} else {
high = guess;
guess -= distance;
direction = -1;
}
distance /= 2;
} while (distance != 0);
for (int i = low; i <= high; i++) {
System.out.println("Is your number " + i + "?");
String finalAnswer = in.nextLine().toLowerCase();
if (finalAnswer.equalsIgnoreCase("yes")) {
System.out.println(i + " is the answer.");
System.out.println("Thank you for playing the guessing game.");
break;
}
}
in.close();
}
private boolean getHighLowResponse(Scanner in, int direction, int guess) {
do {
System.out.println("Is your number " + getDirection(direction)
+ " than " + guess + "?");
String answer = in.nextLine().toLowerCase();
if (direction < 0) {
if (answer.equals("yes"))
return false;
if (answer.equals("no"))
return true;
} else {
if (answer.equals("yes"))
return true;
if (answer.equals("no"))
return false;
}
} while (true);
}
private String getDirection(int direction) {
if (direction < 0) {
return "less";
} else {
return "greater";
}
}
}
I don't have any idea how to display the largest and smallest number after the user enter -1.
Note: I also have to display the sum of all of this number and the average of this sum.
Here's my code so far:
public static void main(String[] args) {
// store
int cnt = 0;
int acumulator = 0;
int larger = 0;
int smaller = 0;
int number;
// inputs
System.out.println("enter the number all the number");
Scanner kb = new Scanner(System.in);
number = kb.nextInt();
// loop
while (number != -1) {
acumulator += number;
number = kb.nextInt();
cnt++;//
}
double average = (acumulator / cnt);
System.out.println(" The total of your number is=" + acumulator);
System.out.println(" The average of your number is=" + average);
}
Seems like schoolwork, but what you could do is making a var and checking in your while if the input number is higher or lower then the saved var.
if(input > max)
max = input;
And
if(input < min)
min = input;
I would make the following changes:
use a for loop instead of a while loop (you need intialization, condition and iteration)
use the JDK's API more - Math.min() and Math.max()
spell "accumulator" correctly
remove all variables you are not using (cnt)
Try this:
public static void main(String[] args) {
int accumulator = 0;
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
int count = 0;
// inputs
System.out.println("enter a number (-1 to end)");
Scanner kb = new Scanner(System.in);
for(int number = kb.nextInt(); number != -1; number = kb.nextInt()) {
count++;
accumulator += number;
largest = number > largest ? number : largest;
smallest = number < smallest ? number : smallest;
}
double average = (accumulator / count);
System.out.println(" The total of your numbers is=" + accumulator);
System.out.println(" The average of your numbers is=" + average);
System.out.println(" The largest of your numbers is=" + largest);
System.out.println(" The smallest of your numbers is=" + smallest);
}
FYI: Math.min/max could be used instead of the ternary statements, but the above is the simplest java that will achieve the result.
Basically you need to check each all numbers with each other.Lets say we have numbers 1,2 and 3
here is the code:
public static void main(String[] args){
int one=1;
int two=2;
int three=3;
if(three>one){
if(three>two){
System.out.println("three is biggest");
}
}
if(two>one){
if(two>three){
}
}
etc etc.
I think you got idea
You need to use an "if" statement.