Hi so I am wondering how it would be possible to read a string from input. for instance:
public class TestInput1{ public static void main (String[]args){ double firstNo = readDouble("First number?"); int operator = readInt("Operator - type 1 for *, 2 for +, 3 for -, or 4 for /"); Double secondNo = readDouble("Second number?"); if (operator == 1) { System.out.println(firstNo + " times " + secondNo + " = " + (firstNo*secondNo)); } else if (operator == 2){ System.out.println(firstNo + " plus " + secondNo + " = " + (firstNo+secondNo)); } else if (operator == 3){ System.out.println(firstNo + " minus " + secondNo + " = " + (firstNo-secondNo)); } else if (operator == 4){ System.out.println(firstNo + " divided by " + secondNo + " = " + (firstNo/secondNo)); } } public static int readInt(String prompt){ System.out.println(prompt); java.util.Scanner keyboard = new java.util.Scanner(System.in); return keyboard.nextInt(); } public static String readString(String prompt){ System.out.println(prompt); java.util.Scanner keyboard = new java.util.Scanner(System.in); return keyboard.nextLine(); } public static double readDouble(String prompt){ System.out.println(prompt); java.util.Scanner keyboard = new java.util.Scanner(System.in); return keyboard.nextDouble(); } }
When I first wrote this, I had it so that the user typed in the actual operator e.g. * or + however when I went to check the variable like this:
public class TestInput1{ public static void main (String[]args){ double firstNo = readDouble("First number?"); String operator = readString("Operator --> *, +, -, or /"); Double secondNo = readDouble("Second number?"); if (operator == *) { System.out.println(firstNo + " times " + secondNo + " = " + (firstNo*secondNo)); } else if (operator == +){ System.out.println(firstNo + " plus " + secondNo + " = " + (firstNo+secondNo)); } else if (operator == -){ System.out.println(firstNo + " minus " + secondNo + " = " + (firstNo-secondNo)); } else if (operator == /){ System.out.println(firstNo + " divided by " + secondNo + " = " + (firstNo/secondNo)); } } public static int readInt(String prompt){ System.out.println(prompt); java.util.Scanner keyboard = new java.util.Scanner(System.in); return keyboard.nextInt(); } public static String readString(String prompt){ System.out.println(prompt); java.util.Scanner keyboard = new java.util.Scanner(System.in); return keyboard.nextLine(); } public static double readDouble(String prompt){ System.out.println(prompt); java.util.Scanner keyboard = new java.util.Scanner(System.in); return keyboard.nextDouble(); } }
it didn't like it, and wouldn't check the variable, an error just appeared. I didn't post this in "what's wrong with my code?" because I solved the problem, but I would like to know how to solve this in future without the crude int variable instead.
thanks,
Skeptile