Is it possible to stream double values from an array using scanner? - java

I have a method that needs single values as the input, but I only have the information in an array. I have searched and found out that Scanner can stream values but only in string form. So I thought I should change the array into string and then convert it back into double before returning the value.
Here is what I had written.
double E;
public double StreamValue (double[]g2){
Scanner s = new Scanner(Arrays.toString(g2)); //PROBLEM HERE
while (s.hasNext()){
E = Double.parseDouble(s.next());
}
return E;
}
When I ran the code, it failed. My question is, is the idea right but I'm missing any part, or it's completely invalid?
Edited:
I need to feed the streaming values into a methode that will analyze each values and return an int.
This is kind of a short example of it:
public int EventAnalyzer(double E) {
if (E > c_max)
a = 0;
else
a = 1;
return a;
}
The returned value will be used for this method:
private void isDetected (int a){
CharSequence t0 = "No breathing";
CharSequence t1 = "Normal breathing";
TextView textView = (TextView)findViewById(R.id.apnea);
if(a==0)
textView.setText(t0);
if(a==1)
textView.setText(t1);
}

I think, your idea is right.
But your result E must be an array of double:
double[] E;

Your goal is not completely clear to me, but
if you have double[] g2:
You can use an enhanced for-loop:
for(double d : g2)
System.out.println("This is a double from array: "+ d);
If you need to return one double from the array, then you can retrieve it using the index by doing
return g2[x];
where x is a valid index between 0 and g2.length - 1.

#Alexander Anikin had answered the question in the comment. I'm working on the Arrays.stream but it requires API 24 while I have API 19. I'm looking for other way possible. Thanks everyone for the responses!

Related

Returning value from method and "The Value Assigned Is Never Used" [duplicate]

This question already has answers here:
What does the "Assigned value is never used" warning mean?
(5 answers)
Closed 3 months ago.
I'm following Princeton's introductory computer science course (I'm not a student, just teaching myself). I working on this assignment.
Main is calling two methods: amplify and reverse, both of which return an array. Amplify multiplies all values in the array by a constant alpha. Reverse returns an array that lists the original array values in reverse order, ex. {1,2,3} -> {3,2,1}.
Amplify works fine, but nothing happens when I call reverse and I get a bug that states: The Value Assigned Is Never Used
public class audiocollage {
// Returns a new array that rescales a[] by a factor of alpha.
public static double[] amplify(double[] a, double alpha) {
for (int i = 0; i < a.length; i++) {
a[i] = a[i] * alpha;
}
return a;
}
// Returns a new array that is the reverse of a[].
public static double[] reverse(double[] a) {
double[] b = new double[a.length];
for (int i = a.length - 1, j = 0; i >= 0; i--, j++) {
b[j] = a[i];
}
return b;
}
// Creates an audio collage and plays it on standard audio.
public static void main(String[] args) {
double[] samples = StdAudio.read("cow.wav");
double alpha = 2.0;
samples = amplify(samples, alpha);
samples = reverse(samples);
}
}
It sounds like you have two questions:
Why doesn't anything happen when I call reverse(samples)?
The code you're showing does nothing with the result of reverse(samples) other than store it in the variable samples (overwriting its previous value). You will need to do something with samples after that to observe the new array (like printing samples, which should now appear to be reversed).
Which leads into the next question:
Why do I get a warning about "the value assigned to samples is never used"?
This is a warning saying that the code you wrote doesn't do anything.
Dead store to local variable is the first line of the warning, which describes what's happening: the value stored to samples is "dead" -- it is never used again, and so we may as well have skipped that line altogether. That causes your compiler (or extension) to give us a warning because it's almost certain that the code you wrote is not doing what you intended, so in many cases that warning can be helpful for spotting mistakes.
This warning can be resolved by using samples somehow, such as by printing it, calling another function with it, etc.
The previous line
samples = amplify(samples, alpha);
doesn't generate that warning because it's output is used in the following call to reverse():
samples = reverse(samples);
// ^ usage of `samples` variable!
This is made even clearer by using different variables for all your arrays:
public static void main(String[] args) {
// No warning; samplesRaw used later
double[] samplesRaw = StdAudio.read("cow.wav");
double alpha = 2.0;
// No warning; samplesAmplified used later
samplesAmplified = amplify(samplesRaw, alpha);
// WARNING! samplesReversed is never used!
samplesReversed = reverse(samplesAmplified);
}
If the hint is related to the last line, it means you have a local variables samples which has not used ( you assigned a value but never read it)

How to replace the overridden methods with a Recursive implementation

I want to use recursion in order to collapse the overridden add() methods in the code and allow the user to provide any number of terms.
I've made a couple of changes to my code, but I'm not getting the desired result.
Examples of user input and expected output.
Output (for input 3 + 4)
7.0
Output (for input 3 + 4 + 5)
12.0
The code I have:
import java.util.*;
public class Recursion {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String exp = input.nextLine();
System.out.println(solver(exp.split(" ")));
}
public static double solver(String[] expression) {
double result = 0;
if (expression.length == 3) {
result = add(Double.parseDouble(expression[0]), Double.parseDouble(expression[2]));
}
else if (expression.length == 5) {
result = add(Double.parseDouble(expression[0]), Double.parseDouble(expression[2]),
Double.parseDouble(expression[4]));
}
else if (expression.length == 7) {
result = add(Double.parseDouble(expression[0]), Double.parseDouble(expression[2]),
Double.parseDouble(expression[4]), Double.parseDouble(expression[6]));
}
else if (expression.length == 9) {
result = add(Double.parseDouble(expression[0]), Double.parseDouble(expression[2]),
Double.parseDouble(expression[4]), Double.parseDouble(expression[6]),
Double.parseDouble(expression[8]));
}
else if (expression.length == 11) {
result = add(Double.parseDouble(expression[0]), Double.parseDouble(expression[2]),
Double.parseDouble(expression[4]), Double.parseDouble(expression[6]),
Double.parseDouble(expression[8]), Double.parseDouble(expression[10]));
}
return result;
}
public static double add(double a, double b) {return a + b;}
public static double add(double a, double b, double c) {return a + b + c;}
public static double add(double a, double b, double c, double d) {return a + b + c + d;}
public static double add(double a, double b, double c, double d, double e) {return a + b + c + d + e;}
public static double add(double a, double b, double c, double d, double e, double f) {return a + b + c + d + e + f;}
}
That's doable with recursion.
But before diving into recursive implementation, it's worth to find out how to solve this problem iteratively because it'll give you a better understanding of what the recursion does.
Firstly, I want to point out at issues with the code you've provided.
Your existing solution is brittle since it depends on the consistency of the user input, and it will fail because of the single additional white space or if a white space will be missing.
Another draw-back is that you have a lot of methods and with them, you are able to handle only a limited number of arguments in the given expression. Let's fix it.
Since your code is intended to perform the arithmetical addition, I think it'll be better to split the input on the plus symbol + and give a user a bit of freedom with white spaces.
For that, we need to pass the following regular expression into the split() method:
"\\s*\\+\\s*"
\s* - implies 0 or more white spaces;
\+ - plus symbol has a special meaning in regular expressions and needs to be escaped with a back-slash.
And since there's more than one arithmetical operation (and you also might want to implement others letter on). It's better to extract your the logic for splitting the user input into a separate method:
public static double add(String expression) {
return addIteratively(expression.split("\\s*\\+\\s*"));
}
expression.split() will return an array of numeric strings that will allow to substitute all your methods with a single method that expects a string array String[] or varargs String... expression (which will allow you to pass as an argument either an array of strings or arbitrary number of string values).
public static double addIteratively(String[] operands) {
double result = 0;
for (String next: operands) {
result += Double.parseDouble(next);
}
return result;
}
Now, when it's clear how to deal with this task iteratively (remember every problem and could be addressed using iteration is also eligible for recursion and vice versa) let's proceed with a quick recap on recursion.
Every recursive method consists of two parts:
Base case - that represents a simple edge-case (condition when recursion terminates) for which the outcome is known in advance.
Recursive case - a part of a solution where recursive calls are made and where the main logic resides.
To process the given array recursively, we can track the position in the array by passing it with each method call.
The base case will represent a situation when there's no more elements left in the array, i.e. current position is equal to the array's length. Since there's no element under the given position, the return is 0.
In the recursive case we need to parse the number under the current position and add the result of the recursive call with position incremented by 1 to it. That will give us the return value.
The recursive implementation might look that:
public static double addAsDouble(String[] operands, int pos) {
if (pos == operands.length) { // base case
return 0;
}
// recursive case
return Double.parseDouble(operands[pos]) + addAsDouble(operands, pos + 1);
}
Method responsible for splitting the user input.
public static double add(String expression) {
return addAsDouble(expression.split("\\s*\\+\\s*"), 0); // recursion starts at position 0
}
main() - here, you just need to call the add() providing a string inter by the user and bother of what is happening inside add. That makes code cleaner and easier to read.
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String exp = input.nextLine();
System.out.println(add(exp));
}
Output
3 + 4 +5
12.0
You are not passing the correct indexes to the various add methods. For example, if you want to add three numbers, you should do the following:
result = add(Double.parseDouble(expression[0]), Double.parseDouble(expression[1]), Double.parseDouble(expression[2]));

Need to print top three values in console

I just found elements (around 100 float values) via XPath and printed them on console using System.Out.. Now I need to sort them and print top three values from them. Please help me in this regard.
Thanks
I dont know about selenium, My code is related to java. If your float number are strings like this (5.3 6.366), You can use below code:
String floatNumber = "5.3 6.366";
String[] numbers = floatNumber.split(" ");
Arrays.sort(numbers);
for(int i=0; i<numbers.length;i++){
System.out.println(numbers[i]);
}
Since yo are using SeleniumWebdriver, you probably have this as a data structure: List<WebElement>.
Lists are part of the java.util.Collection framework and therefore it is not very hard to implement a sorting. Something like this could work, if list contains the List<WebElement> and the float values that you want to sort after are in an attribute called toSortAfter:
Collections.sort(list, new Comparator<WebElement>(){
#Override
public int compare(WebElement e1, WebElement e2){
String fl1Str = e1.getAttribute("toSortAfter");
String fl2Str = e2.getAttribute("toSortAfter");
if (fl1Str != null && fl2Str != null){
float f1 = Float.parseFloat(fl1Str);
float f2 = Float.parseFloat(fl2Str);
if (f1 < f2){
return -1;
}
else if (f1 > f2) {
return 1;
}
}
return 0;
}
});
I leave better handling of Exceptions to the interested reader... Also, note that I wrote this out of my head and without a Java-Compiler at hand. So there might be syntax or other mistakes.
Note:
Without the knowledge of the HMTL nodes you are collectiong it is not possible to help you any further. It might be, that the attribute is called differently, of that the float value is not an attribute altogether. If is it the content of the Elements, you can access this with WebElement.getText() method.

Working with Generic arrays [duplicate]

This question already has answers here:
Java generics and Array's
(5 answers)
Closed 8 years ago.
Good day. I have been learning java the last few months. So I created a generic array as follows.
public class Implementation<T> implements IMatrix<T>{
private T[][] genMatrix;
private Integer numberRows;
private Integer NumberCols;
public Implementation(){
generateMatrix();
for(int i = 0;i< numberRows;i++)
{
for(int j =0;j< numberCols;j++)
{
JOptionPane.showInputDialog("Enter value for row " + (i+1) + " and for column " + (j+1)))
}
}
multiplyScalar(5);
}
//generate the array
public void generateMatrix(){
String rowString = JOptionPane.showInputDialog("Enter the number of rows!");
numberRows = Integer.parseInt(rowString);
String colString = JOptionPane.showInputDialog("Enter the number of cols!");
numberCols = Integer.parseInt(colString);
final Object[][] arrayO = (T[][])new Object[numberRows][numberCols];
genMatrix = (T[][])arrayO;
}
//writeElements to the array;
public void writeElem(int x, int y, T value){
genMatrix[x][y] = value;
}
//now that those members are done I have created a method to access the data
public T getElem(Integer i, Integer j){
return (T)genMatrix[i][j];
}
This is where my problem now exists. I have made this two dimensional array. I would like to multiply each value in this array by a Integer c. I have attempted it in the following way and all failed.
public IMatrix<T> multiplyScalar(Integer c) throws MatrixException {
// TODO Auto-generated method stub
for(int i = 0; i< numberRows; i++)
{
for(int j=0;j<numberCols;j++)
{
/**
THIS IS THE POINT AT WHICH IT CRASHES
*/
System.out.println(((Integer)(getElement(i, j)) * c));
}
}
return null;
}
}
The program crashes because of a ClassCastException. I have tried everything in my knowledge to get this to work. I can not multiply the two dimensional array with a Integer. Please help. This uses a interface with many more functions that is irrelevant. Please note that there is a strong possibility that this code crashes as I can not upload the original code.
The problem is that Java doesn't support operator polymorphism. You need T to extend Number and then use method calls. Its a bit more verbose than what one might like though. Its explained quiet well here:
Predefining multiplication for generics in java

How to calculate a arithmetic expression (String) and return the answer?

I know how to calculate easy expression without variables. But how to do, when in line we have expression with "x"?
For example
(x+1)*(x-1)
In this example program should to return: x^2 - 1
It's a non-trivial endeavor. I would strongly suggest you look at what's out there. For example Symja
You might want to look at the scripting feature of java. It seems that you can execute Javascript (or other scripting languages) from Java using this scripting engine.
You will find some examples at https://today.java.net/pub/a/today/2006/04/11/scripting-for-java-platform.html.
What you are asking for, is letting a program transform (and possibly solve) mathematical equations. This is of course possible and there are tools and certainly APIs around which do it, but it's definitely beyond hacking a java program by your own.
In case you just like to calculate the result of a given formula, then this is doable. Interestingly, you can just throw an equation at Google (e.g. (5 + 3) * (8-4)) and it will give you the result. So, why not just use it? ;-)
When we go to the interview they asking the this logical type of question. i to met the same problem. but i couldn't able to success the interview because this type of questions. Later i found the result of my own after i search in in the internet. Friends who are all want to do this..
follow this operation. i will give this full of free.
I will enter the equation as string Like.
a*b*c+d/m-x.
get this equation as string object. and use following functions.#
public void calc() throws IOException
{
String equation,store,get;
StringBuilder sb= new StringBuilder();
DataInputStream dis= new DataInputStream(System.in);
System.out.println("Enter the equation");
equation= dis.readLine();
equation="%"+equation+"%";
byte[] buf= equation.getBytes();
for(int i=0;i<equation.length();i++)
{
if(buf[i]>=97&&buf[i]<=122)
{
System.out.println("Enter the value for "+(char)buf[i]);
get=dis.readLine();
sb.append(get);
}
else
sb.append((char)buf[i]);
}
store= sb.toString();
char[] buf1= new char[25];
for(int i=0;i<store.length();i++)
{
buf1[i]=store.charAt(i);
}
for(int i=0;i<buf1.length;i++)
{
no.append(buf1[i]);
}
System.out.println(no.toString());
int m,n=0;
for(int i=0;i<no.length()-1;i++)
{
if('/'==no.charAt(i))
{
leftCount=rightCount=0;
m=findLeftValue(i-1) / findRightValue(i+1);
no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
i=0;
}
}
for(int i=0;i<no.length()-1;i++)
{
if('*'==no.charAt(i))
{
leftCount=rightCount=0;
m=findLeftValue(i-1) * findRightValue(i+1);
no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
i=0;
}
}
for(int i=0;i<no.length()-1;i++)
{
if('+'==no.charAt(i))
{
leftCount=rightCount=0;
m=findLeftValue(i-1) + findRightValue(i+1);
no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
i=0;
}
}
for(int i=0;i<no.length()-1;i++)
{
if('-'==no.charAt(i))
{
leftCount=rightCount=0;
m=findLeftValue(i-1) - findRightValue(i+1);
no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
i=0;
}
}
for(int i=0;i<no.length();i++)
{
if('%'==no.charAt(i))
{
no.deleteCharAt(i);
i=0;
}
}
System.out.println(no.toString());
}
public int findLeftValue(int i)
{
StringBuilder sb= new StringBuilder();
int x=0;
while(no.charAt(i)!='*'&&no.charAt(i)!='+'&&no.charAt(i)!='-'&&no.charAt(i)!='/' &&no.charAt(i)!='%')
{
leftCount++;
sb.insert(0, no.charAt(i));
i--;
}
x=Integer.parseInt(sb.toString());
return x;
}
public int findRightValue(int i)
{
StringBuilder sb= new StringBuilder();
int x;
while(no.charAt(i)!='*'&&no.charAt(i)!='+'&&no.charAt(i)!='-'&&no.charAt(i)!='/' &&no.charAt(i)!='%')
{
rightCount++;
sb.append(no.charAt(i));
i++;
}
x=Integer.parseInt(sb.toString());
return x;
}
here may be unused variable may be there.please find and remove it.
I didn't set any preferences to the calculation. just i made up with the flow. if you change the flow the answer will be different. so, Keep in mind. and you can do the same for different operators also.
And One more thing is that, Please verify the equation before proceeding the function. because, it will not check whether the equation is correct or wrong.(a+*d++c). it is not correct equation.
The equation should be correct format.. Like a+b*c-d/x.
Enjoy ..Break the interview and get your correct job..

Categories

Resources