Java - simple way to have the program create doubles - java

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]);

Related

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 to use delimiters to ignore floats greater than 1?

So I'm reading in a two column data txt file of the following from:
20 0.15
30 0.10
40 0.05
50 0.20
60 0.10
70 0.10
80 0.30
and I want to put the second column into an array( {0.15,0.10,0.05,0.2,0.1,0.1,0.3}) but I don't know how to parse the floats that are greater than 1. I've tried to read the file in as scanner and use delimiters but I don't know how to get ride of the integer that proceeds the token. Please help me.
here is my code for reference:
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.*;
class OneStandard {
public static void main(String[] args) throws IOException {
Scanner input1 = new Scanner(new File("ClaimProportion.txt"));//reads in claim dataset txt file
Scanner input2 = new Scanner(new File("ClaimProportion.txt"));
Scanner input3 = new Scanner(new File("ClaimProportion.txt"));
//this while loop counts the number of lines in the file
while (input1.hasNextLine()) {
NumClaim++;
input1.nextLine();
}
System.out.println("There are "+NumClaim+" different claim sizes in this dataset.");
int[] ClaimSize = new int[NumClaim];
System.out.println(" ");
System.out.println("The different Claim sizes are:");
//This for loop put the first column into an array
for (int i=0; i<NumClaim;i++){
ClaimSize[i] = input2.nextInt();
System.out.println(ClaimSize[i]);
input2.nextLine();
}
double[] ProportionSize = new double[NumClaim];
//this for loop is trying to put the second column into an array
for(int j=0; j<NumClaim; j++){
input3.skip("20");
ProportionSize[j] = input3.nextDouble();
System.out.println(ProportionSize[j]);
input3.nextLine();
}
}
}
You can use "YourString".split("regex");
Example:
String input = "20 0.15";
String[] items = input.split(" "); // split the string whose delimiter is a " "
float floatNum = Float.parseFloat(items[1]); // get the float column and parse
if (floatNum > 1){
// number is greater than 1
} else {
// number is less than 1
}
Hope this helps.
You only need one Scanner. If you know that each line always contains one int and one double, you can read the numbers directly instead of reading lines.
You also don't need to read the file once to get the number of lines, again to get the numbers etc. - you can do it in one go. If you use ArrayList instead of array, you won't have to specify the size - it will grow as needed.
List<Integer> claimSizes = new ArrayList<>();
List<Double> proportionSizes = new ArrayList<>();
while (scanner.hasNext()) {
claimSizes.add(scanner.nextInt());
proportionSizes.add(scanner.nextDouble());
}
Now number of lines is claimSizes.size() (also proportionSizes.size()). The elements are accessed by claimSizes.get(i) etc.

java, correct number of inputs on one line entry

Forgive me if this has already been asked, but I am trying to fill an array of user defined size, but I want to make sure any extra input is either dumped or triggers an error to reprompt for input. My assignment requires that all input for an array is done on one line, with spaces separating individual values. The program works fine, and seeing how we are still in the beginning of the class I don't think that we are expected to know how to filter the quantity of inputs on a single line, but it is something that still bugs me.
I have searched for some time now for a solution, but everything thing I find is not quite what I am looking for. I thought doing a while(scannerVariable != "\n") would work, but once I thought about it more I realized that wouldn't do anything for my problem since the new line character is only being encountered once per array regardless of the number of inputs. The snippet with the problem is below:
public static double[] getOperand(String prompt, int size)
{
System.out.print(prompt);
double array[];
array = new double[size];
for(int count = 0; count < size; count++)
{
array[count] = input.nextDouble();
}
return array;
}
All I need is some way of validating the number of inputs or dumping/ignoring extra input, so that there is no trash in the buffer to skip input that follows. The only way I can think of is counting the number of spaces and comparing that against the size of the array -1. I don't think that would be reliable though, and I'm not sure how to extract a whitespace character for the count unless I were to have all the input go into a string and parse it. I can post more code or provide more details if needed. As always, thanks for any help!
This can help you. Function that allows the entry of numbers on a line separated by spaces. Valid numbers are stored in a list of type Double.
public static void entersDouble () {
Scanner input = new Scanner(System.in);
String s;
ArrayList<Double> numbers= new ArrayList<>();
System.out.print("Please enter numbers: ");
s=input.nextLine();
String [] strnum = s.split("\\s+");
int j=0;
while(j<strnum.length){
try {
numbers.add(Double.parseDouble(strnum[j++]));
}
catch(Exception exception) {
}
}
for (Double n : numbers)
System.out.println(n);
}
It seems to me that rather than trying to work out the number of inputs up front you would be better off trying to read them one by one and then taking appropriate action if it's too long or too short.
For example
public static double[] getOperands(String prompt, int size) {
double[] operands = new operands[size];
while (true) {
System.out.println(prompt);
Scanner scanner = new Scanner(System.in);+
int operandCount = 0;
while (scanner.hasNextDouble()) {
double val = scanner.nextDouble();
if (operandCount < size)
operands[operandCount++] = val;
}
if (operandCount == size)
return operands;
else
System.out.println("Enter " + size + " decimals separated by spaces.");
}
}

Increase Array Size Based on Total Numbers Entered

I have an issue for creating an array based on the total amount of numbers entered into the array.
Essentially the program is expected to work as the following: the user is prompted for n numbers to enter into an array. So until the user types '000' as their input, the user will be prompted for a new number.
Note: for this array, I do not want the user to input the amount of numbers they want to enter for the array size. Instead, I want the user to continue inputting random numbers until '000' has been inputted, then, the total amount of numbers that has been entered into the array, is the size of such array.
For example: this would work if we have int array[] = {1, 2, 4, 6}, this will automatically set array size to 4, without actually explicitly declaring the array size as 4 elements. Similarly, with my code, I want it where the numbers that the user enters is added to the array, and then the array size is automatically given from the amount of numbers the user has entered like above.
It is important to note that we do not know the length of the array until the user has entered all n numbers.
I have attempted a skeleton, but it returns a cannot find symbol error:
Code:
//Array Code
import java.util.*;
class setArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int stopInput = 000;
int number;
System.out.print("Enter a number: ");
number = input.nextInt();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
int array[] = {number};
}
System.out.print("Array size: " + array.length);
} // Main brace
} // Class brace
setArray.java:19: error: cannot find symbol
System.out.print("Array Size: " + array.length);
symbol: variable array
location: class setArray
1 error
You have a few errors here. The first is understanding why you get your immediate error. The variable array is declared within the scope of the while loop. It can not be seen outside of this loop. That is why the compiler is complaining.
The second is that the size of the array (if declared outside of the loop) will always be 1. From my understanding of what you have written as an attempt to solve the problem you have describe shows that you are not tackling the problem correctly.
While you don't known the the final length of the array to be entered; you do need to store the values entered (my inference) to populate the final array. To store the value entered by the user you need a list that will grow with the input.
List<Integer> values = new ArrayList<>();
while (number != stopInput) {
System.out.print("Enter a number: ");
values.add(Integer.valueOf(input.nextInt()));
}
Integer[] array = values.toArray(new Integer[values.size()]);
Firstly, the compilation error is because the array variable is not visible from the System.out.println line. This is because it's declared inside the while loop, so is only visible inside the while loop.
To make it visible to the whole method, declare it before the while loop.
Secondly, arrays cannot be resized. You declare an array to be a certain size, and you cannot add or remove elements.
My suggestion would be to use an ArrayList. Declare one before your loop, and add the new number inside the loop. After the loop, the size should be how many numbers were entered.
Finally, there's no difference between 000 and 0. Is 0 a valid input number?
You can use
List<Integer> array=new ArrayList<Integer>();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
array.add(number);
}
This sounds like a job for java.util.ArrayList - this is the array that doesn't have a fixed size and is growing as you add values to it automatically under the covers.
The error is caused because you are creating the array only within the scope of the while loop. You need to create it outside the loop. Secondly, standard arrays are not dynamic, so you would need to either set the size and increase it as needed, or just simply use an ArrayList.
Psuedo:
ArrayList<Integer> list = new ArrayList<Integer>()
...
while(not stop number)
list.add(number)
...
print(list.size())
If you really want to use an Array, here is how you can do it
public static void main(String[] args){
STOP_ENTRY = "000";
scan = new Scanner(System.in);
entry = "";
while(true){
System.out.print("Enter #: ");
String tempS = scan.nextLine();
if(tempS.equals(STOP_ENTRY)) break;
else entry += tempS + ":";
}
String[] split = entry.split(":");
int[] intArray = new int[split.length];
System.out.println("Length of created intArray = " + intArray.length); //length of created array
for(int i = 0; i < intArray.length; i++){
intArray[i] = Integer.parseInt(split[i]);
System.out.println("intArray[" + i + "] => " + String.valueOf(intArray[i]));
}
}
I would recommend an ArrayList, as it dynamically changes is size when you add an element, but do whatever you'd like.
An important note, this does not handle any malicious entry that you might not want (characters, symbols), and will error if they are entered, something you can easily add if you need

How to make it so only ints from the array can be chosen? Also how to find biggest integer from integers chosen?

I am making a program that prompts the user for 3 integers and prints out the biggest one chosen. I am stuck with 2 problems at the moment. I would like to know how I can make the program so that the user can only choose integers from the array. I would also like to know how to find and print out the biggest integer from the ones that the user chose. I'm quite new to programming so all feedback is appreciated.
Thanks!
import java.util.Scanner;
public class Lab14C // name of class file
{
public static void main(String [] args)
{
int[] array = {0,1,2,3,4,5,6,7,8,9};
for(int i=0; i<array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println("\n");
Scanner array1 = new Scanner(System.in);
System.out.println("What is your first integer? ");
double array11 = array1.nextInt();
Scanner array2 = new Scanner(System.in);
System.out.println("What is your second integer? ");
double array22 = array2.nextInt();
Scanner array3 = new Scanner(System.in);
System.out.println("What is your third integer? ");
double array33 = array3.nextInt();
System.out.println("\n");
}
}
I don't think there is a way to force a user to input an element. Few things you could do is :
Tell the user he has to select a number in a particular range.
Keep the input statement in a loop. If the entered element exists in array , go ahead. Else tell the user to enter again.
Printing the biggest integer can be done using Math.max(double,double) function. For three elements you can try System.out.println("Max of three is "+Math.max(array11,Math.max(array22,array33)))
You can do it yourself if you want instead of built in function like:
if(array1>array2&&array1>array3)
//print max as array1
else if(array2>array1&&array2>array3)
//print max as array2
else //print array3 as max
Also change your element types to int as you are reading integer.
1) There is no need to create a new Scanner all the time.
Just create one Scanner (which I would just call input or scanner or something that makes sense).
2) If you're reading int's why are you storing them in doubles?
3) To check for a certain condition you use if(*condition*) { /*do something */ }. So if you want to check if x is smaller than y you do if(x < y) { /* do something */ }. (In your case you'll want to check if current input is greater than biggest input and if so set the biggest input to current input.)
4) For a sorted array you can use Arrays.binarySearch(array, elementToSearch) which will return the index of the element when found, or a negative number if not found (the negative number is (-(insertionPoint)-1)). (So you can check if the number entered by the user is in the array and keep asking for a new number if is not.)
1) How I can make the program so that the user can only choose integers from the array.?
You are declaring array variable as int[] so it stores only integer values. Whenever you retrives the value from this array, it returns int value only so you don't have to worry about it.
2)how to find and print out the biggest integer from the ones that the user chose.?
To find the maximum or minimum from a set of values, Java provide a function name Math#max(). You can use it like this :
int maxValue = Math.max(Math.max(array11,array22),array33);
Here is the doc for Math library.

Categories