Program calculates square of number incorrectly - java

The following program is supposed to calculate the square of a number (Different program from previous question) I tried doing this because the previous program used bufferedReader with this in attempt to use scanner. For instance when entering 2 as the number it outputs 1.0 as the squared value of that number. Any help would be much appreciated! Btw sorry for the spacing i can't get past the first screen unless I space each line 4 times for some reason.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("enter number");
Scanner in=new Scanner(System.in);
System.out.println("the sqare of that number is "+sqrt(in.nextInt()));
}
static double sqrt(double x){
double result;
double i=0;
if(x<0)
result=-1;
else{
while (true){
if((i*i)>x)
break;
i++;
}
i=i-1;
result= (i * i);
result= (i * i);
}
return result;
}
}

Why are you returning result? The i variable holds the square-root at the end of the while-loop, try returning i. Then, that first if-statement can simply become:
if (x < 0)
return -1;
and you can get rid of result completely.
I do not fully understand what your goal is here. Your while-loop calculates the square-root of x - what's the point of that? Why not just return x*x? In fact, you don't even need the (rather poorly named) sqrt method:
System.out.print("Enter a number: ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println("The sqare of that number is " + (n*n));
in.close();

It looks like what you want in you while loop is if ( i > x) break;. Then the result should be correct because you subtract 1 from i after the while loop - making it equal to x. So, result = i * i is the square of x since i == x.

Related

Writing a WHILE loop in Java to compute the largest value in a sequence that prevents no user input

I'm trying to learn (self-taught) Java by reading Big Java, Late Objects from by Cay Horstmann. I'm using repl.it to write my code (if you may want to look it up, it's public)
A selfcheck question of Chapter 4 Loops is:
How can you overcome the problem of when the user doesn't provide any input in the algorithm of section 4.7.5 (titled Maximum and Minimum) and the WHILE loop just terminates the program for this reason ?
They basically ask to rewrite the code so it solves this problem.
The information of section 4.7.5 you need to solve this problem: To compute the largest value in a sequence, keep a variable that stores the largest element that you have encountered, and update it when you find a larger one.
(This algorithm requires that there is at least one input.)
double largest = in.nextDouble();
while (in.hasNextDouble())
{
double input = in.nextDouble();
if (input > largest)
{
largest = input;
}
}
This is what the book suggests as the answer to this problem (but I disagree):
One solution is to do all input in the loop and introduce a Boolean variable that checks whether the loop is entered for the first time.
double input = 0;
boolean first = true;
while (in.hasNextDouble())
{
double previous = input;
input = in.nextDouble();
if (first) { first = false; }
else if (input == previous) { System.out.println("Duplicate input"); }
}
I don't fully understand the first sentence. And I disagree this as a solution for the problem because (as far as I can tell) it tests whether the input has been entered before, instead of testing if any sort of user input has been provided..
I tried to merge those two sections of code together but I can't seem to make it work. Or more specific: figure out how to build it. What variables / loops do I need? In which order do I write this?
I've made a flowchart in Visio of the first section of code but have no clue how to continue.
This is what I've written so far:
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number: ");
double largest = 0;
while (input.hasNextDouble())
{
double value = input.nextDouble();
if (value > largest)
{
largest = value;
System.out.println("The largest input till now is: " + largest);
}
}
Can someone:
Ask me questions which help me to solve this question? I.e. Tell me what tools I need (WHILE, FOR etc.)
Provide a solution in text which I can hopefully transform in code
Or write the code for me (I haven't learned arrays yet, so please solve it without)
Thanks in advance,
So I worked on this for a bit and I think I have something close to what you're looking for using a do while loop.
This code accepts user input first, then checks it's value in comparison to the last input and return either "Input a higher value", "Duplicate number found", or it sets the last number entered to the current number.
I hope this helps you get your code to where you'd like it to be! I'm still new, so I apologize if this is not entirely optimized.
Also, I have not added a way to exit the loop, so you may want to add a check on each iteration to see if the user would like to continue.
public static void main(String[] args) {
double userInput = 0;
double prevNum = 0;
boolean hasValue = false;
boolean exitCode = false;
do {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
userInput = sc.nextDouble();
do {
if (userInput<prevNum) {
System.out.println("Please enter a number higher than " + prevNum);
hasValue=true;
}
else if (userInput==prevNum) {
System.out.println("Duplicate input detected.");
hasValue=true;
}
else {
prevNum = userInput;
hasValue = true;
}
}
while(hasValue==false);
System.out.println(prevNum);
System.out.println(userInput);
}
while(exitCode==false);
}
If you want compute if the number entered is the largest entered from the beginning but declare it at the largest if it's the first iteration then do this :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean flag = true;
double largest = 0;
System.out.println("Enter the number: ");
while (input.hasNextDouble()){
double value = input.nextDouble();
if (flag) {
flag = false;
largest = value;
}
else if (value > largest) largest = value;
System.out.println("The largest input till now is: " + largest);
System.out.println("Enter a new number: ");
}
}

Adding message when certain condition is met (Java)

Total newbie here, please forgive the silly question. As an exercise I had to make a program (using do and while loops) that calculates the average of the numbers typed in and exits when the user types 0. I figured the first part out :) The second part of the exercise is to change the program to display an error message if users types 0 before typing any other number. Can you kindly explain to me what is the easiest way to accomplish this? If you provide the code is great but I’d also like an explanation so I am actually understanding what I need to do.
Thank you! Here is the code:
import java.util.Scanner;
public class totalave1 {
public static void main(String[] args) {
int number, average, total = 0, counter = 0;
Scanner fromKeyboard = new Scanner(System.in);
do {
System.out.println("Enter number to calculate the average, or 0 to exit");
number = fromKeyboard.nextInt();
total = total + number;
counter = counter + 1;
average = (total) / counter;
} while (number != 0);
System.out.println("The average of all numbers entered is: " + average);
}
}
The second part of the exercise is to change the program to display
an error message if users types 0 before typing any other number.
It is not very clear :
Do you you need to display a error message and the program stops ?
Do you you need to display a error message and to force the input to start again ?
In the first case, just add a condition after this instruction : number=fromKeyboard.nextInt(); :
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
return;
}
...
} while (number!=0);
In the second case you could pass to the next iteration to take a new input.
To allow to go to next iteration, just change the number from zero to any value different from zero in order that the while condition is true.
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
number = 1;
continue;
}
...
} while (number!=0);
The good news is that you probably have done the hardest part. :) However, I don't want to give too much away, so...
Have you learned about control flow? I assume you might have a little bit, as you are using do and while. I would suggest taking a look at the following Java documentation first: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Then, look at your current solution and try to think what conditions you have that would lead you to display the error message, using if statements. How do you know the user typed a 0? How do you know it's the first thing they entered? Are there any variables that you have now that can help you, or do you need to create a new one?
I know this is not a code answer, but you did well in this first part by yourself already. Let us know if you need further hand.
Don't go down code after reading and if you cant then see the code.
First you have to learn about the flow control. Second you have to check whether user entered 0 after few numbers get entered or not, for that you have to some if condition. If current number if 0 and it is entered before anyother number then you have to leave rest of the code inside loop and continue to next iteration.
import java.util.Scanner;
public class totalave1
{
public static void main (String[]args)
{
int number, average, total=0, counter=0;
boolean firstTime = true;
Scanner fromKeyboard=new Scanner (System.in);
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if(firstTime && number==0){
System.out.println("error enter number first");
number = -1;
continue;
}
firstTime = false;
total=total+number;
counter=counter+1;
average=(total)/counter;
} while (number!=0);
System.out.println("The average of all numbers entered is: "+average);
}
}
Here is a simple program that extends on yours but uses nextDouble() instead of nextInt() so that you can enter numbers with decimal points as well. It also prompts the user if they have entered invalid input (something other than a number):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Java_Paws's Average of Numbers Program");
System.out.println("======================================");
System.out.println("Usage: Please enter numbers one per line and enter a 0 to output the average of the numbers:");
double total = 0.0;
int count = 0;
while(scanner.hasNext()) {
if(scanner.hasNextDouble()) {
double inputNum = scanner.nextDouble();
if(inputNum == 0) {
if(count == 0) {
System.out.println("Error: Please enter some numbers first!");
} else {
System.out.println("\nThe average of the entered numbers is: " + (total / count));
break;
}
} else {
total += inputNum;
count++;
}
} else {
System.out.println("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
}
}
Try it here!

How do I make my program repeat according to certain circumstances?

import java.util.Scanner;
public class MyFirstGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter A Number: ");
double s = scanner.nextDouble();
double randomNumber = Math.random();
double realNumber = randomNumber*10;
double realerNumber = Math.round(realNumber);
System.out.println(realerNumber);
if(s==realerNumber) {
System.out.println("You Win!");
} else {
System.out.println("Try Again...");
}
}
}
So what I am trying to do is make a "game" for my Java class. I have generate a random number between 1 and 10 and the user has to input a number and if the input and the random number are the same, they "win." If they lose, they try again...? First, I did all the necessary scanner stuff that I don't even fully understand. I just copied the professor. So the program says to enter a number and the program generates a number between 0.0 and 1.0. I multiply that number by 10 to make it between 1 and 10. Then I round the number to the nearest integer. If the input matches this number, the program says you win. If not, it'll say try again.
The problem is how do I make the program repeat itself without the user having to reboot the program with the cmd? I need to repeat the input, random number generator, and then the result. What do I need to do? Also, how is my program? My second big one...yeah right...big. But seriously, how can I make it less complex or anything to improve it. Thanks.
Use a while loop:
long realerNumber = Math.round(realNumber);
// first guess
long guess = scanner.nextLong();
while (guess != realerNumber) {
System.out.println("Try Again...");
// guess again
guess = scanner.nextInt();
}
System.out.println("You Win!");
There is already a class to generate random numbers, you could use it:
// TODO: move to constant
int MAX = 10;
// nextInt(int n) generates a number in the range [0, n)
int randomNumber = new Random().nextInt(MAX + 1)
just put your code inside the do-while loop
Scanner scanner = new Scanner(System.in);
do
{
System.out.println("Please Enter A Number: ");
double s = scanner.nextDouble();
double realerNumber = Math.round( Math.random() * 10 );
System.out.println(realerNumber);
if(s==realerNumber) {
System.out.println("You Win!");
} else {
System.out.println("Try Again...");
}
}
while(someCondition);
the someCondition can be for example a counter (if you want to play n times just set counter to n and decrease it every loop iteration then check if it is 0 in while) or some function checking if a key is pressed (like escape)
int n = 5;
do
{
n--;
...
}
while(n > 0);
This will run forever, but it's the idea mentioned in the first comment
...
Scanner scanner = new Scanner(System.in);
while(true){ // add this after Scanner ... declaration
...
} // end of existing else block
} // end of while loop, so add this single brace
...

How to print each number up to a certain number

I am taking an online MOOC to learn Java, the only problem i have is it is from the university of Helsinki in Finland i live in the US so there are limited times when i can be awake to ask for help on an exercise. my current exercise is to ask the user for a number and then print each whole number up to that number while using a
while {
}
statement
this is the code i have currently
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int number = Integer.parseInt(reader.nextLine());
System.out.print("up to what number?:"+ number);
while (number<=number){
System.out.println(number);
number++;
}
}
and what it looks like it is doing is ignoring the
while (number<=number) {
System.out.println(number);
part of my code and proceeding straight to the
number++;
portion of my code do i need to declare another int(variable) to store a value?
the way the course has the test cases for grading i can't simply declare a variable with a definite value as they run several test cases like positive numbers and negative numbers.
is there a way to use the reader to store a value to two separate variables so that they can be compared against each other and only print the numbers up to that number?
i also know that i am missing a
Break;
statement but i am not sure where i would place it in the code i have, i have tried to use
} else {
break;
but get an error stating that i have an else without an if.
i am using netbeans as it is required for my course because the server submissions are setup through TMC.
thinking about it now i'm sure its not skipping the while statement but simply continues to print because as it prints and increments the users input is incremented as well since i only have the one variable but i am again not sure how i would go about storing the user input value in two different variables where i can compare them with the less than or equal to statement and stop the printing once it reaches the number input by the user, in that case i would not necessarily need the break statement as it would stop once it prints up to the number input.
ANSWERED: here is what i finally came up with as my answer.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("up to what number?:");
int numbers = 1;
int number = Integer.parseInt(reader.nextLine());
while (numbers <= number){
System.out.println(numbers);
numbers++;
}
}
You are comparing number to itself. So (number <= number) is always true.
Use a different variable, such as count to actually count up. Initialize it at zero.
Change the condition to (count < number), then in the loop change the increment to count++ and then output count.
Oh, and you should probably prompt for the number before you read it in.
ie your whole program will be:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("up to what number?:");
int number = Integer.parseInt(reader.nextLine());
int count = 0;
System.out.println(number);
while (count<number){
count++;
System.out.println(count);
}
}
You need another variable to increment upto inserted number
int i=1;
while (i<=number){
System.out.println(i++);
}
What your loop is doing
while (number<=number){
System.out.println(number);
number++;
}
for example number=10 so it's checking like this 10<=10 do you need this,absolutely not.
So for your code you need an another variable to increment up to entered number.
This would do it:
public static void main(String[] args) {
int startingInt = 1; //begin printing from 1
System.out.println("Up to what number?");
Scanner reader = new Scanner(System.in);
int number = Integer.parseInt(reader.nextLine());
while (startingInt <=number){
System.out.println(startingInt);
startingInt++;
}
}
i'm c# expert, so first of all please use c#.
But I know I know you can't always select your laguagued, ;)
Here is solution , it works on my machine.
while (number<=number){
System.out.println(number);
number++;
if (number==arg[0]) break;
}
Enjoy the solution!
System.out.println("Up to what number?");
int number = Integer.parseInt(reader.nextLine());
int n = 1;
while (n <= number) {
System.out.println(n);
n++;
}

java program that finds average with average method

I have a program that will average your numbers from the command line. Everything is in the main method.
1. The program should run allowing you to enter one number at a time and when you press enter it asks you for another number or offers the ability to press Q to get your average.
2. The program has a limit set to 20 numbers added. When you hit 21 the program notifies you that you added to many numbers and shuts down.
3. If you enter multiple numbers on the same line and press enter, for every number you enter it System.out.println a message once for every number instead of just once.
I would like to understand how to change the program to do these things.
How to get the System.out.println to only appear one time per entry.
How to get the program to output the average of 20 before it ends when someone enters 21
how do i change it to create a method for averaging outside of main then call on the averaging method inside the main.
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double sum = 0;
int count = 0;
System.out.println ("Enter your numbers to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) {
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
while(scan2.hasNextDouble()) {
sum += scan2.nextDouble();
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
if(count == 21)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
inputs = scan.nextLine();
}
System.out.println("Your average is: " + (sum/count));
}
1.
scan2.hasNextDouble()
is parsing the line which contains multiple entries so it must be removed in the while loop. You can parse yourself using string tokenize and print the message only once.
2 . Simply add this line:
System.out.println("Your average is: " + (sum/count));
before returning in if condition to print the average before quitting.
3 . that really depends on what kind of function would you like. May be you can create a function that takes an array of numbers and prints out their average or maybe you want something else.
one possible function:
public double findAverage(ArrayList<Integer> numbers){
int sum=0;
for (Integer i: numbers){
sum+=i;
}
return sum/(double)numbers.size();
}
You can try with the following:
public static void main(String[] args){
if(args.length==20)
{
int sum=0;
sum += Integer.parseInt(args[0]); //do this for 20 array elements using loop
// do required calculation
}
else //print error message
}

Categories