-1

The purpose of my program is to accept ints, doubles, and strings from the user and when the program is terminated by inputing the word "quit", the program averages the ints and doubles, and outputs the submitted strings. Here is what i have so far:

import java.util.*;

public class Lab09 {
    public static void main(String [] args) {
        Scanner console = new Scanner(System.in);

      double sumI = 0;
      double sumD = 0;
      String words = "";
      int numInputInt = 0;
      int numInputDoub = 0;
        do {
            System.out.print("Enter something: ");
            if (console.hasNextInt()) {
               int numI = console.nextInt();

            if (numI >= -100 && numI <= 100) {
               sumI += numI;
               numInputInt++;
            }
            else {
               System.out.println("Integer out of range!(-100 .. 100)");
            }

            }
         else if (console.hasNextDouble()) {
            double numD = console.nextDouble();
            if (numD >= -10.0 && numD <= 10.0) {
               sumD += numD;
               numInputDoub++;
            }
            else {
               System.out.println("Double out of range!(-10.0 .. 10.0)");
            }   

         }
         else {
            words = console.next();
         }

        } while (!words.equalsIgnoreCase("quit")); 
        System.out.println("Program terminated...");
      double avgInt = sumI / numInputInt;
      double avgDoub = sumD / numInputDoub;

      if (numInputInt > 0) {
         System.out.println("\tAveragae of Integers: " + avgInt);
      }
      else {
         System.out.println("\tNo intergers submitted");
      }
      if (numInputDoub > 0) {
         System.out.println("\tAverage of Doubles: " + avgDoub);
      }
      else {
         System.out.println("\tNo doubles submitted");
      }
      System.out.println(words);


   }

}

The ints and doubles get processed well, but im stuck in the strings. Any ideas on how to go about doing so? Thanks in advance!

GPC
  • 7
  • 2

3 Answers3

0

You could use

String input = "";
do {
    //...
    }
    else {
        input = console.next();            
        words += input + " ";
    }
    console.nextLine(); // Read the carriage return
} while (!input.equalsIgnoreCase("quit")); 
//...
System.out.println(words.trim());

to concatenate the text, but this is rather inefficient when done within a loop.

A better solution would be to use a StringBuilder...

StringBuilder work = new StringBuilder(128);
String input = "";
do {
    //...
    }
    else {
        input = console.next();            
        words.append(" ").append(input);
    }
    console.nextLine(); // Read the carriage return
} while (!input.equalsIgnoreCase("quit")); 
//...
System.out.println(words);
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thanks but i cannot use any other classes except the ones i have used – GPC Oct 30 '14 at 01:48
  • `StringBuilder` is about efficiently within the loop as you are not creating "lots" of temporary `String`s, otherwise, the first example should get you started... – MadProgrammer Oct 30 '14 at 01:56
  • Also, I wouldn't be using `words` to check the exit condition, it will only ever be true if the user entered `quit` for the first word... – MadProgrammer Oct 30 '14 at 01:57
0

While you could build a List<String> of words it looks like you just want to concatenate each new word to your String words like,

if (words.length() > 0) words += " "; // <-- add a space.
words += console.next(); // <-- += not =

Then change your loop test to something like,

while (!words.trim().toLowerCase().endsWith("quit"));

And it should work something like you would expect.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
-1

I just read your comment that you can't use any other class, try this:

import java.util.*;

public class Lab09 {
    public static void main(String [] args) {
        Scanner console = new Scanner(System.in);

      double sumI = 0;
      double sumD = 0;
      String words = "";
      int numInputInt = 0;
      int numInputDoub = 0;
        do {
            System.out.print("Enter something: ");
            if (console.hasNextInt()) {
               int numI = console.nextInt();

            if (numI >= -100 && numI <= 100) {
               sumI += numI;
               numInputInt++;
            }
            else {
               System.out.println("Integer out of range!(-100 .. 100)");
            }

            }
         else if (console.hasNextDouble()) {
            double numD = console.nextDouble();
            if (numD >= -10.0 && numD <= 10.0) {
               sumD += numD;
               numInputDoub++;
            }
            else {
               System.out.println("Double out of range!(-10.0 .. 10.0)");
            }   

         }
         else {
            words = words.concat(" ").concat(console.next());

         }

        } while (!words.contains("quit")); 
        System.out.println("Program terminated...");
      double avgInt = sumI / numInputInt;
      double avgDoub = sumD / numInputDoub;

      if (numInputInt > 0) {
         System.out.println("\tAveragae of Integers: " + avgInt);
      }
      else {
         System.out.println("\tNo intergers submitted");
      }
      if (numInputDoub > 0) {
         System.out.println("\tAverage of Doubles: " + avgDoub);
      }
      else {
         System.out.println("\tNo doubles submitted");
      }
      System.out.println(words);


   }

}
Dario
  • 331
  • 4
  • 16
  • Why use `buffer.append(" "+word);`? – MadProgrammer Oct 30 '14 at 01:58
  • In fact, why use `StringBuffer` at all? – MadProgrammer Oct 30 '14 at 01:58
  • i cannot use other class methods for this program – GPC Oct 30 '14 at 02:00
  • @MadProgrammer If the project needs any other extension or if he needs something more than a String, this class is very usefull and safe. – Dario Oct 30 '14 at 02:04
  • Do you understand why you should use `StringBuffer`, what it's trying to achieve? Cause your example demonstrates that you don't. Since it's not a threading program, there's no need for the added synchronization provided by `StringBuffer` and there are othe solutions available... – MadProgrammer Oct 30 '14 at 02:06
  • First of all why your downvote? And now I just explained you that he can use it for more complex project if needed. My answer is correct if you look at the first code, the second one is just an alternative. – Dario Oct 30 '14 at 02:08
  • Using your edited method, the program no longer accepts "quit" as the exit string – GPC Oct 30 '14 at 02:11
  • `buffer.append(" "+word);` is never correct - not the downvoter. It would also think that `words.concat(" ").concat(console.next())` would be more correct, but I've not looked into how `concat` works... – MadProgrammer Oct 30 '14 at 02:11
  • it works for me, here's a try: run: Enter something: 12 Enter something: sadf Enter something: 6 Enter something: quit Program terminated... Averagae of Integers: 9.0 No doubles submitted sadf quit BUILD SUCCESSFUL (total time: 9 seconds) @MadProgrammer I don't know exactly how concat works but take a look here: http://stackoverflow.com/questions/47605/string-concatenation-concat-vs-operator. I think that the double concat is more efficient. – Dario Oct 30 '14 at 02:17