Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. import java.io.FileNotFoundException;
  2. import java.io.PrintWriter;
  3. import java.util.Scanner;
  4.  
  5. public class wektory {
  6. public static void main(String[] args){
  7. Scanner skaner = new Scanner(System.in);
  8.  
  9. boolean flaga = false;
  10. float[] wektor1 = null;
  11. float[] wektor2 = null;
  12.  
  13. do{
  14. System.out.println("Podaj pierwszy wektor: ");
  15. wektor1=podajWektor();
  16.  
  17. System.out.println("Podaj drugi wektor: ");
  18. wektor2=podajWektor();
  19.  
  20. try {
  21. SumujWektory(wektor1, wektor2);
  22. }catch(WektoryRoznejDlugosciException e)
  23. {
  24. System.out.println("Zlapano wyjatek: " + e);
  25. }
  26.  
  27. }while(wektor1.length != wektor2.length);
  28. skaner.close();
  29. }
  30.  
  31. static void SumujWektory(float[] w1, float[] w2) throws WektoryRoznejDlugosciException{
  32.  
  33. if(w1.length == w2.length) {
  34. float[] wektorSumy = new float[w1.length];
  35. for(int i=0; i<w1.length; i++) {
  36. wektorSumy[i] = w1[i]+w2[i];
  37. //System.out.println(wektorSumy[i]);
  38. }
  39.  
  40. ZapiszDoPliku zapis = new ZapiszDoPliku();
  41. try {
  42. zapis.Zapisuj(wektorSumy);
  43. } catch (FileNotFoundException e) {
  44. System.out.println("Wystapil blad podczas zapisu");
  45. }
  46. }else
  47. throw new WektoryRoznejDlugosciException(w1.length,w2.length);
  48. }
  49.  
  50. static float[] podajWektor() {
  51. Scanner skaner = new Scanner(System.in);
  52. float[] wektor = null;
  53. boolean flaga = false;
  54. do {
  55. try {
  56. String input1 = skaner.nextLine();
  57. String[] splitted1 = input1.split(" ");
  58. wektor = new float[splitted1.length];
  59.  
  60. for (int i=0; i<splitted1.length; i++) {
  61. wektor[i]=Float.parseFloat(splitted1[i]);
  62. }
  63. flaga = true;
  64. }catch(NumberFormatException ex) {
  65. System.out.println("Podano niepoprawne wartosci wektora");
  66. flaga=false;
  67. }
  68. }while(flaga != true);
  69.  
  70. return wektor;
  71. }
  72. }
  73.  
  74.  
  75. class WektoryRoznejDlugosciException extends Exception{
  76. public WektoryRoznejDlugosciException(int v1Dlugosc, int v2Dlugosc) {
  77. System.out.println("Dlugosc wektroa pierwszego wynosi "+v1Dlugosc+ " a wektora drugiego "+v2Dlugosc);
  78. }
  79. }
  80.  
  81. class ZapiszDoPliku {
  82. public void Zapisuj(float wektor[]) throws FileNotFoundException {
  83. PrintWriter writer = new PrintWriter("wektor.txt");
  84.  
  85. for(int i=0; i < wektor.length; i++) {
  86. writer.print(wektor[i]+" ");
  87. }
  88. writer.close();
  89. System.out.print("Wektor wynikowy zapisano w pliku wektor.txt \n");
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement