-1

When I run the client and enter a number it is passed as a string. However it must be passed as an integer. How do I change this? and also change from while(true) to a do while so when the user enters "*" the program ends.

   while (true){
                   System.out.print("Enter a number ");
           String message = keyboard.nextLine(); 
           out.writeUTF(message); 
       }

4 Answers4

0

use int option = keyboard.nextInt();

seen here : if you want to know more

Community
  • 1
  • 1
osanger
  • 2,057
  • 3
  • 24
  • 28
0

Try this: Scanner.nextInt() is giving back an integer...

Example

    final Scanner in = new Scanner(System.in);
    int number = 0;
    while(true){
            System.out.print("Enter a number ");
            number = in.nextInt();
            out.writeUTF(number);
    }

UPDATE:

if you need to do this in a loop until the user enter a specific key (e.g. "*") then:

final Scanner in = new Scanner(System.in);
String input = "";
do {
    System.out.print("Enter a number ");
    int numberParsed = 0;
    input = in.nextLine();
    try {
        numberParsed = Integer.parseInt(input);
        System.out.println(numberParsed);
        out.writeUTF(numberParsed);
    } catch (final NumberFormatException ex) {
        System.err.println("That input could not be parsed to integer....");
    }
} while (!input.equals("*"));
ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
0

I imagine that keyboard is an object of type Scanner.

The Scanner has a method nextInt to retrieve the next integer.

Otherwise you can convert a string to an integer using the method Integer.parseInt as follow:

String message = keyboard.nextLine(); 
int myInt = Integer.parseInt(message);
Davide Lorenzo MARINO
  • 22,769
  • 4
  • 33
  • 48
0

Instead of using nextLine and writeUTF, I would use nextInt (and hasNextInt allowing you terminate input with a non-int) with writeInt. Using a try-with-resources and a ByteArrayOutputStream for testing, that might look something like

Scanner keyboard = new Scanner(System.in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(baos)) {
    System.out.print("Enter a number ");
    while (keyboard.hasNextInt()) {
        int v = keyboard.nextInt();
        out.writeInt(v);
        System.out.print("Enter a number ");
    }
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println(Arrays.toString(baos.toByteArray()));
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226