I have made quite a simple number rounding application, since I am quite a beginner, there may be some errors, some debugging to do and we could go on and on however that is not why I am here. Whenever I type in an integer that is larger than the capacity of the value "int", it either returns "-1" or an incredibly large small number (it's negative so further away from zero) such as "-572589576". I want to why and how the JVM returns this. The code for my program is listed below:
import java.util.Scanner;
public class NumberRounder {
private static Scanner userInput2;
public static void main(String[] args) {
System.out.println("--- Number Rounder ---");
Scanner userInput = new Scanner(System.in);
System.out.println("The number you enter will round it to the nearest value.");
System.out.print("Enter any decimal number: ");
if (userInput.hasNextDouble()) {
System.out.println("\nCalculating...");
System.out.println("Number Rounding...");
double chosenNumber = userInput.nextDouble();
int roundedNumber = (int) Math.round(chosenNumber);
if (roundedNumber == -1) {
System.out.println("\nAn ERROR occured.");
System.out.println("That number is too large for our servers. Sorry for the inconvenience.");
System.exit(0);
}
System.out.println(chosenNumber + " has been rounded to " + roundedNumber);
} else if (!(userInput.hasNextDouble())) {
System.out.println("\nThat is an illegal response...");
userInput2 = new Scanner(System.in);
System.out.println("\nThe number you enter will round it to the nearest value.");
System.out.print("Enter any decimal number between 1-10: ");
double chosenNumber = userInput2.nextDouble();
int roundedNumber = (int) Math.round(chosenNumber);
System.out.println(chosenNumber + " has been rounded to " + roundedNumber);
} else {
System.out.println("Something wrong happened...");
}
}
}
I have solved the problem of when it returns "-1" however I still don't know how to completely solve this problem. That is why I am here asking the question:
Why does the JVM return such as random number?
Whenever I type in an integer that is larger than the capacity of the value "int"
What did you expect to get from it? Exception?
it will not be there. Java just circle from MAX_VALUE to MIN_VALUE
Just try:
System.out.println(Integer.MAX_VALUE + 1);
System.out.println(Integer.MIN_VALUE);
And look what it prints.
PS. that is about how number sign represented in actual binary format of int value.
You're forcing a double (64-bits) into an int, so the resulting value is truncated and you see these "random" (although they're not random) values. You should use a long to provide additional space for your numbers.
Related
I am doing an open university course in Java, it's been smooth sailing up until now. We are covering loops in this section and the problem I am stuck on asks for the following.
Write a program that reads values from the user until they input a 0.
After this, the program prints the total number of inputted values
that are negative. The zero that's used to exit the loop should not be
included in the total number count.
This is my the program I have written and I have run the program and it works as it should, however I keep getting failed test back with the following statement.
When input was: 5 4 -3 1 0 "Give a number:" text should appear a total of 5 times. Now the count was 0 expected:<5> but was:<0>
Here is my code, as I said when I run the program locally it seems to work just as asked for.
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0){
break;
}
if (number >= 1){
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
You have two problems with the code :
In the number test line,you check if a number is greater than or equal to one (number >= 1), but you should check that it is less than 0 because it is need to be negative numbers. (In the question : the total number of inputted values that are negative)
You are using with scanner.nextLine() But you don't get a line, you get a number (Int if it's integers, double if it's decimal numbers) on you to change it to : scanner.nextInt() :
Here the code :
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());// Scanner number !!
if (number == 0){
break;
}
if (number < 0){ // Less then zero !!!
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
Your problem statement says that the count of negative numbers should be the output. But what you are returning is the count of positive numbers. Change the condition from if (number >= 1) to if (number < 0).
Hope this helps.
You need the total number of inputted values that are negative. So the condition in the while loop has to change from number >= 1 to number < 0.
Check this
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());
if (number == 0) {
break;
}
if (number < 0) {
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
Also, prefer to use nextInt() because you know your input is of integer type.
I could not get the exact problem. But some observations.
If you really input all numbers at the first ask and then hitting ENTER, obviously it would throw NumberFormatException as "5 4 -3.." is not a valid number and the loop wont proceed. Try input each number and hit ENTER.
Scanner must be closed. If you are using JDK 8, use "try (Scanner scanner = new Scanner(System.in)) {...}. This would automatically close the scanner.
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: ");
}
}
below is the code:
Scanner scan = new Scanner(System.in);
String input = scan.next();
try{
double isNum = Double.parseDouble(input);
if(isNum == Math.floor(isNum)) {
System.out.println("Input is Integer");
//enter a double again
}else {
System.out.println("Input is Double");
//break
}
} catch(Exception e) {
if(input.toCharArray().length == 1) {
System.out.println("Input is Character");
//enter a double again
}else {
System.out.println("Input is String");
//enter a double again
}
}
taken from here: how to check the data type validity of user's input (Java Scanner class)
however, when i input 1.0 or 0.0, it is still considered as an integer, is 1.0 not considered a double?
Please help guys, thank you!
If you want to treat 1.0 as a Double an 1 as an Integer, you need to work with the input variable, which is of type String.
Java will always treat Double x = 1 in the same way as Double y = 1.0 (meaning 1 is a valid Double), so you will not be able to distinguish them with code.
Since you have the original string representation of the input, use a regex or some other validation to check it. For instance a sample regex pattern for double would look like "[0-9]+(\.){0,1}[0-9]*" and for an integer "[0-9]+" or "\d+"
Here is an example:
final static String DOUBLE_PATTERN = "[0-9]+(\.){0,1}[0-9]*";
final static String INTEGER_PATTERN = "\d+";
Scanner scan = new Scanner(System.in);
String input = scan.next();
if (Pattern.matches(INTEGER_PATTERN, input)) {
System.out.println("Input is Integer");
//enter a double again
} else if (Pattern.matches(DOUBLE_PATTERN, input)) {
System.out.println("Input is Double");
//break
} else {
System.out.println("Input is not a number");
if (input.length == 1) {
System.out.println("Input is a Character");
//enter a double again
} else {
System.out.println("Input is a String");
//enter a double again
}
}
1.0 is typically considered a valid double, but the code has been written explicitly to threat whole numbers as invalid doubles(printing that they are intergers). To change this behavior remove the inner if:
try{
double isNum = Double.parseDouble(input);
System.out.println("Input is Double");
} catch(Exception e) {
if(input.toCharArray().length == 1) {
System.out.println("Input is Character");
}else {
System.out.println("Input is String");
}
}
Check, if the string you are validating contains a dot - then, if parseDouble succeeds, it could be treated as a double value (even for 1.0).
You check if 1.0 is equal to 1, which mathematically is correct. Therefore your first if will return true, and it will be considered an int. It seems that the whole idea with the program is to check doubles and see if they have decimals or not.
Math.floor(x)
returns a double, and since 1.0 is indeed the same as 1.0, your program will enter the first if-block.
I think your test is flawed. You say "0.0 and 1.0 are parsed as integers" based on the condition
isNum == Math.floor(isNum)
Double-precision floating-point numbers are not a random garbage of bits: they express a precise quantity, and it happens that the numbers zero and one can be represented exactly (see the bit patterns) and thus they are equal to Math.floor(val) (btw, this happens for lots of integer values, not only zero and one)
So you should reconsider your test before your code. Consider that likely a user will never input an integer or a double: what she types is a decimal number, and you should deal with the input depending on what it's used for (the choice is among String, BigDecimal, Number, Integer, Double and so on...)
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.
import java.io.IOException;
import java.util.*;
public class task2 {
public static void main (String [] args) throws IOException {
int a;
int b;
String y;
String x;
Scanner input = new Scanner(System.in);
System.out.println("Please enter number A:");
a = input.nextInt();
System.out.println("\nPlease enter number B:");
b = input.nextInt();
System.out.println("\nLastly, enter A if you wish it to be the dividor and/or subtractor, or if you wish it to be B, please enter B :"); //stops running properly here...
y=input.nextLine();
System.out.println("\nWhat would you like to do? Multiply (*), Divide (/), Subtract (-) or Add (+)? Please enter the symbol of which process you would like to have completed:");
x=input.nextLine();
if (y=="b"+"B") {
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + a*b);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + a/b);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + a+b);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (a-b));}}
else
if (y=="a"+"A"){
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + b*a);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + b/a);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + b+a);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (b-a));}}
}
}
I dont know why it stops but where indicated by "//" the program suddenly stops letting me input information and does not continue the processes i want it to do. I wont bother explaining the program in detial because i believe it is fairly obvious from the code itself what i want to do.
Thanks in adavance for all the help!
Use
input.next();
not
input.nextLine();
Since nextLine() skips over the input and sets the scanner to the NEXT line and returns a string representation of what was skipped. Your program throws the errow because the NEXT line does not exist
Your string comparisons are incorrect--you need to compare strings using the equals() method, like x.equals("*") in order for any of them to work. (This is a pretty common mistake, so even though it's homework, freebie :)
There's no loop, so it'll stop after the first time "through"; this may or may not be what you want.