How to find the location of an element in an array?
How would I go about searching for a location of an array through user
input. So for example, the user is asked "What element do you want to
search for in the array [21.1, 1.3, 81.1]?", the user inputs "81.1", the
location is given to them.
This is the code I attempted to do that with:
import java.net.URL;
import java.util.Scanner;
public class LowestTemperature
{
public static void main( String[] args) throws Exception
{
double[] temps =
arrayFromUrl("http://learnjavathehardway.org/txt/avg-daily-temps-atx.txt");
System.out.println( temps.length + " tempatures in database.");
double highest = -1, lowest = 9999.99;
Scanner input = new Scanner(System.in);
for ( int i = 0; i<temps.length; i++)
{
if ( temps[i] < lowest )
{
lowest = temps[i];
}
if ( temps[i] > highest)
{
highest = temps[i];
}
}
System.out.print( "The lowest average daily tempature was ");
System.out.println( lowest + "F (" + fToC(lowest) + "C)" );
System.out.print( "The highest average daily tempature was ");
System.out.println( highest + "F (" + fToC(highest) + "C)" );
}
public static double[] arrayFromUrl( String url ) throws Exception
{
Scanner fin = new Scanner((new URL(url)).openStream());
int count = fin.nextInt();
double[] dubs = new double[count];
for ( int i = 0; i<dubs.length; i++)
dubs[i] = fin.nextDouble();
fin.close();
return dubs;
}
public static double fToC( double f)
{
return (f-32)*5/9;
}
}
No comments:
Post a Comment