2017-06-02 8 views
-1

我試圖創建一個Java程序,它從文本文件中讀取一行中的三個數字,並將它們解釋爲三角形的三條邊的長度,然後打印出:創建一個讀取.txt並識別三角形邊長的Java程序

"Equilateral" - if the three lines are equal length 

"Isosceles" - if only two of the three lines are equal 

"Scalene" - for any other valid length 

...or "Not a Triangle" 

我的文本文件看起來像這樣...

1 1 1 

2 2 1 

2 x 3 

到目前爲止,我有這個,不知道去哪裏從那裏任何幫助,將不勝感激謝謝!

import java.util.Scanner; 
import java.io.File; 
import java.util.NoSuchElementException; 
import java.io.FileNotFoundException; 

public class Triangle { 

public static void main (String[] args){ 

File fileName = new File("input.txt"); 
Scanner scan = null; 

try { 
    Scanner file = new Scanner(new File("input.txt"); 
} 
    while(scan.hasNextLine()) { 
    } 

catch(FileNotFoundException){ 
} 

回答

0
import java.util.Scanner; 
import java.io.File; 
import java.util.NoSuchElementException; 
import java.io.FileNotFoundException; 

public class Triangle { 

public static void main (String[] args) 
{ 

    File fileName = new File("input.txt"); 
    Scanner scan = null; 
    String str[]; 
    int s1=0,s2=0,s3=0; 
try 
{ 
    Scanner file = new Scanner(new File("input.txt")); 
    String line; 
    while((line=file.nextLine())!=null) 
    { 
     str = line.split(" "); 

     if(str.length==3) 
     { 
      try 
      { 
       s1 = Integer.parseInt(str[0]); 
       s2 = Integer.parseInt(str[1]); 
       s3 = Integer.parseInt(str[2]); 

       if(s1+s2>=s3 && s2+s3>=s1 && s1+s3>=s2) 
       { 
        if(s1==s2 && s2==s3) System.out.println("Equilateral"); 
        else if(s1==s2 || s2==s3 || s3==s1) System.out.println("Isosceles"); 
        else System.out.println("Scalene"); 
       } 
       else 
       { 
        System.out.println("Not a Triangle"); 
       } 
      } 
      catch(Exception e) 
      { 
       System.out.println("Not a Triangle"); 
      } 

     } 
     else 
     { 
      System.out.println("Not a Triangle"); 
     } 
    } 
} 
catch(Exception e) 
{ 

} 

} 

} 
+0

如果你需要一些解釋請評論 – sjboss

+0

感謝sjboss,這有很大幫助。之前沒有使用過Interger.parseInt,但查找了那些我沒有見過的部分,並且它們一起來了。再次感謝。 – JESbashingwitya

0
while(scan.hasNextLine()) { 
    String[] line = (scan.nextLine()).split("\\s+"); 
    if(line.length != 3) { 
     // the next line doesn't have exactly 3 integers, do something 
    } 
    try { 
     int side1 = Integer.parseInt(line[0]); 
     int side2 = Integer.parseInt(line[1]); 
     int side3 = Integer.parseInt(line[2]); 
     // check if it is a triangle, and what kind of triangle is it 
    } 
    catch(NumberFormatException e) { 
     // there is something else in the line, other than integer value(s) 
    } 
} 

這裏是你如何能接受輸入(可能的途徑之一)。

  • 檢查輸入流中是否有更多行。
  • 如果有更多的行,請閱讀下一行。
  • Tokenise下一行(提取每個令牌)。
  • 您期待每行應該有3個整數。
  • 因此,首先檢查下一行是否有精確的3個標記。如果否,則相應處理。
  • 如果確切有3個標記,嘗試將它們中的每一個轉換爲整數。
  • 如果它們中的任何一個不能轉換爲整數,則相應處理。
  • 如果所有3個標記都成功轉換爲整數,則您的三角形有三條邊。現在你可以檢查它是否是三角形,它是什麼樣的三角形。