How to Turn Strings into Numbers in Java - dummies

By Barry Burd

Java has a class named Integer, and the whole Integer class has a static method named parseInt. If someone hands you a string of characters, and you want to turn that string into an int value, you can call the Integer class’s parseInt method.

import java.util.Scanner;
import static java.lang.System.out;
class AddChips {
 public static void main(String args[]) {
  Scanner keyboard = new Scanner(System.in);
  String reply;
  int numberOfChips;
  out.print("How many chips do you have?");
  out.print(" (Type a number,");
  out.print(" or type 'Not playing') ");
  reply = keyboard.nextLine();
  if (!reply.equals("Not playing")) {
   numberOfChips = Integer.parseInt(reply);
   numberOfChips += 10;
   out.print("You now have ");
   out.print(numberOfChips);
   out.println(" chips.");
  }
  keyboard.close();
 }
}

You want to give each player ten chips. But some party poopers in the room aren’t playing. So two people, each with no chips, may not get the same treatment. An empty-handed player gets ten chips, but an empty-handed party pooper gets none.

image0.jpg

So, you call the Scanner class’s nextLine method, allowing a user to enter any characters at all — not just digits. If the user types Not playing, you don’t give the killjoy any chips.

If the user types some digits, you’re stuck holding these digits in the string variable named reply. You can’t add ten to a string like reply. So you call the Integer class’s parseInt method, which takes your string and hands you back a nice int value. From there, you can add ten to the int value.

Java has a loophole that allows you to add a number to a string. The problem is, you don’t get real addition. Adding the number 10 to the string “30” gives you “3010”, not 40.

Don’t confuse Integer with int. In Java, int is the name of a primitive type. But Integer is the name of a class. Java’s Integer class contains handy methods for dealing with int values. For example, the Integer class’s parseInt method makes an int value from a string.