Reputation:
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.
Upvotes: 1
Views: 2366
Reputation: 1
If you want the donuts to be an input you need to set the scanner equal to something other than donuts and set the donuts as an integer. Try this:
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.");
int donuts = in .nextInt();
int price;
price = 2;
System.out.print("Price of " + donuts + " donuts is ");
System.out.println(donuts * price);
}
}}
Upvotes: 0
Reputation: 698
To take input form console u should use the Scanner class object
Try this
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 scr = new Scanner(System.in);
int donuts = scr.nextInt(); /*scr is object of Scanner class and next int is used to take integer input*/
int price; price = 2;
System.out.print("Price of " + donuts + " donuts is ");
System.out.println(donuts * price);
}
}
Upvotes: 1
Reputation: 1826
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();
Upvotes: 1