I\'m having trouble figuring out how to fix these errors I keep getting for my code
import java.util.Scanner;
public class Unit02Prog1 {
public static void
In this situation you need parse from string to integer. Here you have an example:
String simplenumber= "10";
int num = Integer.parseInt(simplenumber);
In your code:
public static void main(String[] args) { Scanner input = new Scanner(System.in);
String name;
System.out.print("name");
name = input.next();
String catagory;
System.out.print("Catagory");
catagory = input.next();
String numWords;
System.out.print("numWords");
numWords = input.next();
int price;
int numWordsInt = Integer.parseInt(numWords);
if (numWordsInt >= 50) {
price = (int) (((numWordsInt -50) * .08) + 5.00);
System.out.println("customer:" + name);
System.out.println("Placed an ad in catagory:" + catagory);
System.out.println("Ad length is" + numWords + "words, at a price of $" + price);
}
else {
price = (int) (numWordsInt * .10);
System.out.println("customer:" + name);
System.out.println("Placed an ad in catagory:" + catagory);
System.out.println("Ad length is" + numWords + "words, at a price of $" + price);
}}
if (numWords >= 50) {
numWords is a string, and >=
only works on numbers.
You have 2 options for fixing this:
Read the number in as a String and convert it to a number
temp = input.nextLine();
numWords = Integer.parseInt(temp);
This way means you can check manually, and do not need to catch an exception if the number is wrong.
Read the number in as a number straight away
numWords = input.nextInt();
This way is less code, but you will need to catch a NumberFormatException
if the input is not an integer.
input.next()
a lot, depending on your inputs you may want to use nextLine
insteadSystem.out.printf
to clean up your printing codeyour variable numWords
is string, please parse it to integer first for comparing. Then, update price
to double as well. Sample code is as per below.
int numWords;
System.out.print("numWords");
numWords = input.nextInt();
double price;
if (numWords >= 50) {
price = ((numWords -50) * .08) + 5.00;
System.out.println("customer:" + name);
System.out.println("Placed an ad in catagory:" + catagory);
System.out.println("Ad length is" + numWords + "words, at a price of $" + price);
}
numWords
is a String
, not an int
. Parse the String to get an int.
int num_words = Integer.parseInt(numWords);