Home > database >  Usage of String in method
Usage of String in method

Time:11-13

I need a lit help here. So I want my first method to read the file "./data/textfiles/zahlen01.txt" (there are some numbers i want to add together, this works). And I want my second method to do the same but with a string in the method. So how do i name the method in the main method?

public static double countSumOf(Scanner in) {
    PrintWriter out = new PrintWriter(System.out);

    double sum = 0;
    while (in.hasNext()) {
        double b = in.nextDouble();
        sum = sum   b;
    }
    
    out.println(sum);
    out.flush();

    return sum;

}

public static double countSumOf(String filename) {
    DirtyFileReader dfr = new DirtyFileReader(filename);
    Scanner in = new Scanner(dfr);
    return countSumOf(in);

}


public static void main(String[] args) { 
    Locale.setDefault(Locale.US); 
    PrintWriter out= new PrintWriter (System.out); 
    DirtyFileReader dfr = new DirtyFileReader("./data/textfiles/zahlen01.txt"); 
    Scanner in = new Scanner(dfr); 
    countSumOf(in); 
    countSumOf(); 
    out.flush(); 
 } 

CodePudding user response:

Not sure i correctly understand so i rephrase: You want to sum up some numbers, once using a file as source that contains the numbers and once using a java string that contains the numbers?

I found this interesting piece of code: https://github.com/alquesh/PR1PRAXIS/blob/master/PR1PRAXIS/src/pr1/a04/FirstInput.java

To sum it up: Scanner can take a String as an argument to the constructor to scan that string instead so where you have Scanner in = new Scanner(dfr); you can instead use Scanner in = new Scanner(meineZeichenkette);

Grüße

  •  Tags:  
  • java
  • Related