Frage

Okay, so the program that I'm trying to figure out how to code (not really fix), I have to use Java to accept continuous input from the user until they enter a period. It then must calculate the total characters that the user input up to the period.

import java.io.*;
class ContinuousInput
{
    public static void main(String[] args) throws IOException
    {
    InputStreamReader inStream = new InputStreamReader (System.in);
    BufferedReader userInput = new BufferedReader (inStream);
    String inputValues;
    int numberValue;
    System.out.println("Welcome to the input calculator!");
    System.out.println("Please input anything you wish: ");

    inputValues = userInput.readLine();

    while (inputValues != null && inputValues.indexOf('.')) {
    inputValues = userInput.readLine();
    }
    numberValue = inputValues.length();
    System.out.println("The total number of characters is " + numberValue + ".");

    System.out.println("Thank you for using the input calculator!");
    }
}

Please don't suggest the use of Scanner, the Java SE Platform we're stuck using is the SDK 1.4.2_19 model and we can't update it. Explanation of empty braces: I thought that if I put in the empty braces that it would allow for continuous input until the period was put in, but clearly that wasn't the case...

Edit: Updated code Current Error: won't end when . is inputted.

War es hilfreich?

Lösung

You have to switch the if/else statement with while.

Sample :

inputValues = userInput.readLine();
while (!".".equals(inputValues) {
   //do your stuff
   //..and after done, read the next line of the user input.
   inputValues = userInput.readLine();
}

Note: Never compare the values of String objects with the == operator. Use the equals() method.

If you just want to test, whether the sentence the user inputs contains a . symbols, you just have to switch from equals() to contains(). It's a built-in method from the java.lang.String class.

Sample:

 while (inputValues != null && !inputValues.contains(".")) {
    //do your stuff
 }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top