2013-08-24 5 views
0

사용자 입력을 통해 요소의 위치를 ​​검색하는 방법은 무엇입니까? 예를 들어, 사용자에게 "배열 [21.1, 1.3, 81.1]에서 어떤 요소를 검색 하시겠습니까?"라고 묻고 사용자가 "81.1"을 입력하면 위치가 지정됩니다. 이 숙제 같은 소리에도 불구하고배열의 요소 위치를 찾는 방법은 무엇입니까?

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; 
    } 
} 

답변

0

신속하게 기존 코드를 수정했습니다. 간단히 말해서, 나는 사용자 입력을 double로 검색하는 메소드를 추가했습니다. 그런 다음 double을 가져 와서 제공된 배열을 반복합니다. 일치하는 항목을 찾으면 요소가 발견 된 배열의 위치를 ​​인쇄합니다.
희망이 도움이됩니다.

package lowesttemperature; 

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

     double term = searchTerm(); 
     for (int i = 0; i<temps.length; i++) 
     { 
      if(temps[i] == term){ 
       System.out.println("The term you searched for is at position " + i + " in the array"); 
      } 
     } 
    } 

    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 searchTerm(){ 
     Scanner scan = new Scanner(System.in); 
     System.out.println("Enter a double: "); 
     double input = scan.nextDouble(); 
     return input; 
    } 

    public static double fToC(double f) 
    { 
     return (f-32)*5/9; 
    } 
} 
+0

감사합니다. 도움에 감사드립니다! – user2690972

0

, 당신은 적어도 지금까지의 대부분을 시도했습니다

내가 함께 그렇게하려고 시도하는 코드입니다.

이 작동합니다 :

Scanner inputScan = new Scanner(System.in); 
double input = inputScan.nextDouble(); 

int pos = 0; 

for (int i = 0;i < temps.length;i ++){ 
    if (temps[i] == input){ 
     pos = i; 
     break; 
    } 
} 

System.out.println("Temperature matching your search: "+temps[pos]); 

당신은 검색 아무것도 일치하지 않는 경우 또는 여러 결과가있는 경우 처리하기 위해 여기에 추가 할 수 있습니다.

+0

두 번 발견되면 루프에서 '중단;'해야합니다. –

+0

하하, 아니요, 실제로 숙제가 아닙니다. 숙제는 "최고 평균 기온"을 더한다. 나는 그것을하는 방법을 아는 것에 관심이 있습니다. – user2690972

+0

.. 그리고'nextDouble()'을 사용하여 double을 읽는다. –

0

앞으로의 조언. 변수 highestlowest은 배열의 첫 번째 요소에 지정됩니다. 그렇다면 그것은 보편적입니다. 온도가 -1도보다 낮 으면 어떨까요?

나는 그것이 문제와 관련이 없다는 것을 알고있다.

+0

나는 모양을 가지고 있었고, 나는 이미 그것이 가능하지 않다는 것을 이미 알고있었습니다. 그래서 나는 -1을했다. 분명히 숫자를 -9999로 올릴 것입니다. – user2690972

+0

나는 어떤 숫자에 대한 해결책을 생각했다. 아니오, 최대, 그러나 보편적 인 해결책에 다른 일정한 것을 주어서. 신경 쓰지 마:). – Pawel

0

indexOf(Double d) 방법 느릅 목록에서 지정된 값의 첫번째 발생의 인덱스를 반환 (또는 사용 후 온도를 저장하기위한 기본 배열 double[] 대신 ArrayList<Double> 사용을 고려 -1 경우는 포함되지 않는다 가치).

온도를 포함하는 객체를 구성하는이 ArrayList (TreeSet tree = new TreeSet(temps);)에서 TreeSet을 구성한 다음 가장 낮은 온도와 가장 높은 온도를 얻으려면 tree.first()tree.last() 메서드를 사용하십시오.

관련 문제