Program crashes when given high values - java

My coding, im trying to make a program that wont crash whatever the input is from user, the program will divide and print out the answer. i have searched but could not find any help!
The coding works fine for numbers smaller than 100000000 or 199999999 you get the point.
Scanner in = new Scanner(System.in);
double n1 = in.nextInt();
double n2 = in.nextInt();
double n3 = n1/n2;
System.out.println(n3);

You are using in.nextInt() which will read an integer whose value less than 2^31 -1 (of course it gets converted to double). But when you give values more than (2^31) - 1 like 12589691475, nextInt() can not read them as they are very big numbers.
Use in.nextDouble() instead.

Use
in.nextDouble();
or
in.nextLong();

For arbitrary big numbers, use java.math.BigInteger or java.math.BigDecimal.
Scanner in = new Scanner(System.in);
BigInteger n1 = new BigInteger(in.nextLine());
BigInteger n2 = new BigInteger(in.nextLine());
BigInteger n3 = n1.divide(n2);
System.out.println(n3);

Related

How to reverse a number in java in a user generated program

My teacher wants me to be able to ask this question an infinite number of times until the user decides to terminate it themselves. This works for the most part however, If I input a number too big I get an error because its a int data type. I have tried longs and doubles to but for some reason I get answers like infinity or the negative of the numbers. How do I fix this so I can put in as long of a number that I want and still get the positive integer reversal? Thank You so Much. Please keep it simple. This is literally my 5th computer class in my life.
import java.util.Scanner;
public class reverseInt3
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int number;
int reverse = 0;
int number2;
int reverse2 = 0;
char repeat;
System.out.println("Please enter any numbers you choose and I will reverse them for you");
number = keyboard.nextInt();
keyboard.nextLine();
while( number != 0 )
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
}
System.out.println("Reverse of entered number is "+reverse);
System.out.println("Do you want to repeat the process using different numbers? Y or N");
repeat = keyboard.nextLine().charAt(0);
while( repeat == 'Y' || repeat == 'y')
{
System.out.println("Please enter your new set of numbers");
number2 = keyboard.nextInt();
keyboard.nextLine();
while( number2 != 0 )
{
reverse2 = reverse2 * 10;
reverse2 = reverse2 + number2%10;
number2 = number2/10;
}
System.out.println("The reverse of entered number is "+reverse2);
System.out.println("Do you want to repeat the process using different numbers? Y or N");
repeat = keyboard.nextLine().charAt(0);
}
}
}
First let's talk about your problem:
If the user input goes beyond the bound of int, long or double your program provides a negative reverse.
That's because when you try to store a very big number in smaller capacity variable, an overflow happens and after that your stored number is not valid and if you try to print it you will get a negative number instead which is not the exact negative for the user input.
If you want to overcome this, one way is to store the user input in a String variable. Then you can check if the input (which is stored in a String type variable) is really an integer or not, and if it was, you can reverse it.
I don't think this is actually what your teacher want you to do. Because the algorithm of reversing an integer (you implemented) can not be used to reverse such a big integer stored in a String variable. So I think your code is good and get it easy because probably your teacher don't expect you to maintain very big integers now. If you so worry about some bigger integers you can use long instead of int but as you know it has its own limitation about 18 digits approximately and it should not be bigger than Long.MAX_VALUE.
Your code is good for the start and I'm going to express some advice in order to provide a better and cleaner code:
It's obvious that you've repeated these part of codes:
System.out.println("Please enter any numbers you choose and I will reverse them for you");
number = keyboard.nextInt();
keyboard.nextLine();
and
while( number != 0 )
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
}
and
System.out.println("Reverse of entered number is "+reverse);
If you studied methods so far, you may want to define these two first blocks in two different methods. One is responsible for getting input from user and the other one is responsible for getting an int as input and return the reversed int (If you used long for user input, this method's input and output should be of type long).
Another tip is why repeat those blocks? Why have two number and number2 variables and also reverse and reverse2?
Isn't it better to omit them and write your while for the repetition of the process in the first time too? Start by initializing the char repeat = 'Y'; and omit the first time you manually get the job done outside of the while( repeat == 'Y' || repeat == 'y') loop.
Hope this helps.

ways to simplify large amount of nextInt/nextDouble?

so I'm creating a program that will to determine a final semester class grade given assignment and test grades and the percentages that they count for in that grade. The grade and percentage information for a single student will be given on a single line. Soooo, I just one question:
q1 = input.nextInt();
q1p = input.nextDouble();
q2 = input.nextInt();
q2p = input.nextDouble();
q3 = input.nextInt();
q3p = input.nextDouble();
l1 = input.nextInt();
l1p = input.nextDouble();
l2 = input.nextInt();
l2p = input.nextDouble();
l3 = input.nextInt();
is there a better way to simplify this mess of input of int & double??
From what I can see from your input variable, it looks like you're working with the Scanner API, am I right ? If so, well there's something pretty nice that you could do using a simple look and the condition has next from the Scanner to verify that there's input to read. Finally, to detect if input is a double or an int, we're gonna make a easy check to make sure !
Collection<Integer> integers= new ArrayList<>();
Collection<Double> doubles = new ArrayList<>();
while(input.hasNext())
{
if (input.hasNextInt()) {
integers.add(input.nextInt());
}else if(input.hasNextDouble()) {
doubles.add(input.nextDouble());
}else
input.next(); // will simply move to next value in the line
}
This way not only you don't have to check everytime like you did before nextInt or NextDouble with a static user input, you won't have to worry. And if the input isn't a double or an int, well, the lists will remain empty !
UPDATE
Change the use of List for the Collections in order to cause less troubles during run time ! The solution should work out great for you at the moment. I also added a clause in the if structure in order to make the loop complete when hasNext == false
You can use two arrays and loop over them:
int numberOfInputs = XXX;
int[] ints = new int[numberOfInputs];
double[] doubles = new double[numberOfInputs];
for (int i = 0; i < numberOfInputs; i++)
{
ints[i] = input.nextInt();
doubles[i] = input.nextDouble();
}
If you need it more flexible and have no problems with (un)boxing you could use a Colletion:
Collection<Integer> ints = new ArrayList<>();
Collection<Double> doubles = new ArrayList<>();
while (moreInput)
{
ints.add(input.nextInt());
doubles.add(input.nextDouble());
}
moreInput is an arbitrary condition that you need to adjust to your needs.
You might add conditions in the loops if there are for example 2 ints and 1 double.

How do i declare and read values into integer values?

I'm really new to java and i'm taking an introductory class to computer science. I need to know how to Prompt the user to user for two values, declare and define 2 variables to store the integers, and then be able to read the values in, and finally print the values out. But im pretty lost and i dont even know how to start i spent a whole day trying.. I really need some help/guidance. I need to do that for integers, decimal numbers and strings. Can someone help me?
You can do this by using Scanner class :
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
For example, this code allows a user to read a number from System.in:
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
int j = scan.nextInt();
System.out.println("i = "+i +" j = "+j);
nextInt() : -Scans the next token of the input as an int and returns the int scanned from the input.
For more.
or to get user input you can also use the Console class : provides methods to access the character-based console device, if any, associated with the current Java virtual machine.
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
or you can also use BufferedReader and InputStreamReader classes and
DataInputStream class to get user input .
Use the Scanner class to get the values from the user. For integers you should use int, for decimal numbers (also called real numbers) use double and for strings use Strings.
A little example:
Scanner scan = new Scanner(System.in);
int intValue;
double decimalValue;
String textValue;
System.out.println("Please enter an integer value");
intValue = scan.nextInt(); // see how I use nextInt() for integers
System.out.println("Please enter a real number");
decimalValue = scan.nextDouble(); // nextDouble() for real numbers
System.out.println("Please enter a string value");
textValue = scan.next(); // next() for string variables
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
If you still don't understand something, please look further into the Scanner class via google.
As you will likely continue to run into problems like this in your class and in your programming career:
Lessons on fishing.
Learn to explore the provided tutorials through oracle.
Learn to read the Java API documentation
Now to the fish.
You can use the Scanner class. Example provided in the documentation.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

Java - simple way to have the program create doubles

The input of the program contains n amount of doubles.
I want each double stored as: a(n), where n = n++
like this:
input 6,57 4,56 1,23
should be stored as:
a(0) = 6,57
a(1) = 4,56
a(2) = 1,23
etc.
This is what i've tried to do:
double a;
int n = 0;
scanner = new Scanner(System.in);
a(n) = scanner.nextDouble();
while (scanner.hasNextDouble()) {
a(n) = scanner.nextDouble();
n++;
break;
}
This does not work out,
any ideas?
Thanks in advance.
You don't know about size inadvance ,So I suggest to use List<Double> instead of array.
You have number in local format (seperated by ,) so use NumberFormat class to get the java format.
Numbers are separated with space and are stored in a line in your input,so use next() method.
Try this code.
List<Double> a = new ArrayList<Double>();
scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String number = scanner.next();
NumberFormat numberFormat = NumberFormat.getInstance();
a.add(numberFormat.parse(number).doubleValue());
}
You will need to use an array. Arrays are fixed size so you must know the number of elements in advance.
Create the array with double[] a=new double[size] where size is the array size you want.
You can now set the array's values with a[n]=scanner.nextDouble();. Remember that n will go from 0 to size-1. You can read out values this way as well, for example `System.out.println(n[2]);

Java double input

I am trying to let the user freedom of entering a number at his own style like he can choose to enter 2 or 2.00 but as you know the double cannot accept this (2). i want the double to accept this with 2 decimal places only (basically i am representing money).
this is what i am not sure how to take the input and convert that in to the 2decimals format. New to java.tks
Tried google but cant find where i can format at the input itself, means dont even let the user type any more decimal places other than 2decimal places, not post-process after entered in to multiple different variables., tks
public static void add()
{
double accbal;
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Enter account balance");
accbal = sc.nextDouble();
//this is the part where i need to know the entered value is formated to only 2 decimal places
}
Since showing decimal places is really a formality to the end user, you could read your value in as a String instead and convert it to a Double or BigDecimal, the latter being preferred if you're working with actual finances.
Related: What Every Computer Scientist Should Know About Floating-Point Arithmetic
public static void add() {
BigDecimal accbal; // could declare a Decimal
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("Enter account balance");
accbal = new BigDecimal(sc.nextLine());
System.out.println(df.format(accbal.doubleValue()));
}
Try this:
DecimalFormat df = new DecimalFormat ("#.##");//format to 2 places
accbal = sc.nextDouble();
System.out.print(df.format(aacbal));//prints double formatted to 2 places
however I see you say:
Tried google but cant find where i can format at the input itself,
means dont even let the user type any more decimal places other than
2decimal places
If the above is your intention for whatever reason then simply read in the input using nextLine() and then check to make sure after the decimal point it only has a length of 2:
double accbal=0;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter account balance");
String s = sc.nextLine();
if (s.substring(s.indexOf('.') + 1).length() <= 2)//accept input and convert to double
{
accbal = Double.parseDouble(s);
break; //terminates while loop
} else {
System.out.println("Incorrect input given! Decimal places cant exceed 2");
}
}
System.out.println("Balance: "+accbal);
If you want to accept input of the form "#.##" just specify a custom regex for Scanner.hasNext :-)
final Scanner input = new Scanner(System.in);
final Pattern pattern = Pattern.compile("\\d+\\.\\d{2}?");
while (input.hasNext()) {
System.out.println((input.hasNext(pattern) ? "good" : "bad")
+ ": " + input.nextDouble());
}
Using the following input:
2.00
3.14159
2
The result is: (also found here)
good: 2.0
bad: 3.14159
bad: 2.0
This way allows you to verify they enter an amount with two decimal places.
Even though you said you do not want a mere post-processing solution, in case you already have an amount and wish to convert it to use 2 decimal places, and you're focused on precision (since this is money), maybe try using BigDecimal -- in particular, see BigDecimal.setScale:
while (input.hasNextBigDecimal()) {
System.out.println(input.nextBigDecimal().setScale(2, RoundingMode.HALF_UP));
}
The output is thus:
2.00
3.14
2.00

Categories