I’m new to Java and I want to make a program that calculates price of donuts by typing in how much donuts you want and then telling you what is the price depending on the number of donuts you want.
This is the code
import java.util.Scanner; class MyFirstProgram { public static void main(String args []){ System.out.println("How many donuts do you want? Type in a number."); Scanner donuts = new Scanner(System.in); int price; price = 2; System.out.print("Price of " + donuts + " donuts is "); System.out.println(donuts * price); } }
What am I missing in my code? I am getting an error in the last line. I think I need to declare donuts as an integer so I can multiply it with the price. What do I need to do?
EDIT: I figured it out. This is the working program now:
import java.util.Scanner; class MyFirstProgram { public static void main(String args []){ System.out.println("Koliko krafna želiš? Upiši broj."); Scanner krafne = new Scanner(System.in); int num = krafne.nextInt(); int cijena; cijena = 2; System.out.print("Cijena " + num + " krafni jest "); System.out.print(num * cijena); System.out.println(" kn."); } }
I wrote the program in Croatian.
Advertisement
Answer
donuts is a Scanner class object and not your input. Replace your line
Scanner donuts = new Scanner(System.in);
with the following
Scanner sc=new Scanner(System.in); int donuts=sc.nextInt();