How to fix the error <identifier> expected? - java

A code returns error <identifier> expected. I don't know why this error is occuring.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
intro();
time();
}
public static void intro() {
System.out.println("Welcome");
System.out.println("What is your name");
Scanner input = new Scanner(System.in);
String name = input.nextLine();
System.out.println("Nice to meet you," + name + " where are you travelling to?");
String dest = input.nextLine();
System.out.println("Great!" + dest + " sounds like a great trip");
}
public static void time() {
Scanner input = new Scanner(System.in);
int hours, minutes;
float perd, perdc, change;
System.out.println("How many days are you going to spend travelling?");
int days = input.nextInt();
hours = days * 24;
minutes = hours * 60;
System.out.println("How much money in USD are you going to spend?");
Double money = input.nextDouble();
perd = (money / days);
System.out.println("What is the three letter currency symbol of your destination?");
String curr = input.nextLine();
System.out.println("How many" + curr + "are there in 1USD?");
Double ex = input.double();
change = money * ex;
perdc = perd * ex;
System.out.println("If you are travelling for" + days + "that is the same as" + hours + "or" + minutes + "minutes");
System.out.println("If you are going to spend" + money + "$USD that means per day you can spend upto $" + perd + "USD");
System.out.println("Your total budget in" + ex + "is" + change + ex + ",which per day is " + perdc + curr);
}
}

I'am glad to see peaple learning Java, and i'am happy to see peaople helping the juniors.
When i see your code, my first advise is to get a good IDE like Eclipse, IntelliJ or Netbeans, it will help you to see quickly the compilation errors.
My second advise is to get a look to the dev norms, as a junior i think is the first methodology you have to study to have a comprehensive and maintainable code.
for example please avoid adding several blank lines between the method signature and the first statment.
I barely touched your code to get it works.
I hope you will enjoy Java.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
intro(input);
time(input);
}
public static void intro(Scanner input) {
System.out.println("Welcome");
System.out.println("What is your name");
String name = input.nextLine();
System.out.println("Nice to meet you, " + name + " where are you travelling to?");
String dest = input.nextLine();
System.out.println("Great! " + dest + " sounds like a great trip");
}
public static void time(Scanner input) {
int hours, minutes;
float perd, perdc, change;
System.out.println("How many days are you going to spend travelling?");
int days = input.nextInt();
hours = days * 24;
minutes = hours * 60;
System.out.println("How much money in USD are you going to spend?");
Float money = input.nextFloat();
perd = money / days;
System.out.println("What is the three letter currency symbol of your destination?");
String curr = input.nextLine();
System.out.println("How many " + curr + " are there in 1USD?");
Float ex = input.nextFloat();
change = money * ex;
perdc = perd * ex;
System.out.println("If you are travelling for " + days + " that is the same as " + hours + " or " + minutes + " minutes");
System.out.println("If you are going to spend " + money + " $USD that means per day you can spend upto $" + perd + " USD");
System.out.println("Your total budget in " + ex + " is " + change + ex + " ,which per day is " + perdc + curr);
}

Related

Connecting a Driver File to its Corresponding File and Using Methods within that file that connect to the Driver File

This project has had me stuck for 3 days now and I am needing personal help. To give some background, I am very much the epitome of a beginner so try to explain it to me in the simplest way possible. Below is the driver file and the UML Diagram of methods I am supposed to use within the other file that connects to the driver. It is a simple calculator project, and help is much appreciated =). The param and return methods I don't need to know so don't feel the need to explain those. Really I just need to know how to set up my file to work with this driver and use the methods in the UML diagram. I hope this provides all the information needed to give a good answer.
import java.util.Scanner;
public class DriverMyCalculator{
static Scanner keyboard = null;
public static void main(String[] args) {
int num1, num2;
int max, min;
keyboard = new Scanner(System.in);
System.out.println("Plesae Enter an integer: ");
num1 = readInt();
System.out.println("Please enter another integer: ");
num2 = readInt();
min = MyCalculator.getMin(num1, num2);
max = MyCalculator.getMax(num1, num2);
System.out.println("min = " + min);
System.out.println("max = " + max);
MyCalculator.displayRange(min, max);
MyCalculator.displayAllEven(min, max);
MyCalculator.displayAllOdd(min, max);
MyCalculator.display5Multiples(min, max);
System.out.println("rangeSum = " + MyCalculator.rangeSum(min, max) );
System.out.println("rangeAvg = " + MyCalculator.rangeAvg(min, max) );
System.out.println("rangeProduct = " + MyCalculator.rangeProduct(min, max) );
System.out.println("rangePower = " + MyCalculator.power(min, max) );
System.out.println();
System.out.println(min + " isPrime = " + MyCalculator.isPrime(min) );
System.out.println(min + " smallestFactor = " + MyCalculator.smallestFactor(min) );
System.out.println(min + " factorial = " + MyCalculator.factorial(min) );
System.out.println();
System.out.println(max + " isPrime = " + MyCalculator.isPrime(max) );
System.out.println(max + " smallestFactor = " + MyCalculator.smallestFactor(max) );
System.out.println(max + " factorial = " + MyCalculator.factorial(max) );
} // end main
/**
* Do NOT change! Thank you!
*
* #return int
*/
public static int readInt(){
String temp = "";
int number = -999;
temp = keyboard.nextLine();
try {
number = Integer.parseInt(temp);
}catch(NumberFormatException e) {
System.out.println("ERROR: " + e.getMessage());
}
return number;
} // end method
} // end class
UML Diagram

How do i keep track of correct answers?

public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String firstname =Keyboard.nextLine();
System.out.println("Welcome "+ firstname+ "!"+ " Please answer the following questions:");
int x = (int)(20 * Math.random()) + 1;
int y = (int)(20 * Math.random()) + 1;
int sum = (x+y);
System.out.println(x + " + " + y + " = ");
String sInput = Keyboard.nextLine();
int answer1 = Integer.parseInt(sInput);
if (answer1 ==sum){
System.out.println("Correct!");
}else{
System.out.println("Wrong!");
}
System.out.println("The correct answer is " +sum);
I have no clue on how to keep track of the correct answers. I need something to keep track of when it prints correct. I don't know what to do though. I know I just need to record the corrects and divide by four. Four because thats how many questions I have in my quiz.
If you just need to keep track of how many right answers were provided, just add an int variable starting with 0 as a value and increment it. If you want to keep track of the questions and answers which were right, create an empty ArrayList and add a string every time a correct answer is provided.
Here an example of the second option:
ArrayList<String> correctAnswers = new ArrayList<String>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String firstname =keyboard.nextLine();
System.out.println("Welcome "+ firstname+ "!"+ " Please answer the following questions:");
for (int i=0;i<10;i++) {
int x = (int)(20 * Math.random()) + 1;
int y = (int)(20 * Math.random()) + 1;
int sum = (x+y);
System.out.println(x + " + " + y + " = ");
String sInput = keyboard.nextLine();
int answer1 = Integer.parseInt(sInput);
if (answer1 ==sum){
System.out.println("Correct!");
correctAnswers.add(x + " + " + y + " = " + sum);
}
else{
System.out.println("Wrong!");
System.out.println("The correct answer is " +sum);
}
}
System.out.println("Correct answers:");
for (String correctAnswer : correctAnswers) {
System.out.println(correctAnswer);
}
It asks 10 questions, keeps track of the right answers and outputs them after the 10th question.
An example for the first option:
int correctAnswers=0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String firstname =keyboard.nextLine();
System.out.println("Welcome "+ firstname+ "!"+ " Please answer the following questions:");
int totalAnswers=4;
for (int i=0;i<totalAnswers;i++) {
int x = (int)(20 * Math.random()) + 1;
int y = (int)(20 * Math.random()) + 1;
int sum = (x+y);
System.out.println(x + " + " + y + " = ");
String sInput = keyboard.nextLine();
int answer1 = Integer.parseInt(sInput);
if (answer1 ==sum){
System.out.println("Correct!");
correctAnswers++;
}
else{
System.out.println("Wrong!");
System.out.println("The correct answer is " +sum);
}
}
System.out.println("Correct answers: "+ correctAnswers + "("+correctAnswers*100/totalAnswers+"%)");

How do I make this if statement?

Apologies for the silly question, I am currently struggling to learn java. I need this code to work so that it will repeat unless '0' is entered for the studentNumber, I'm unsure of how to get the "please enter student number" part to work when I have to declare the int for that before the if statement? I'm not sure if I've approached this completely wrong or what, but I need to be able to repeat the data entry unless "0" is entered as the studentNumber. Thanks for any help!
class Main {
public static void main( String args[] ) {
int studentNumber = BIO.getInt();
if(studentNumber > 0) {
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
}
Use while()
while(studentNumber > 0){
studentNumber = BIO.getInt();
.........
........
}
See also
while in Java
Use while() instead of if, along with the following changes:
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.getInt();
while(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
System.out.print("#Please enter the student number : ");
studentNumber = BIO.getInt();
}
System.out.print("#End of data");
This, as opposed to the other answers, will ensure that even in the first iteration, you perform the check (and promt the user for the student number).
Using Scanner to get the input from the user and process the input value
import java.util.Scanner;
public class ConditionCheck {
public static void main(String[] args) {
Scanner BIO = new Scanner(System.in);
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.nextInt();
if(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.nextInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.nextInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
You should be using a while statement and do something as below:
class Main
{
public static void main( String args[] )
{
int studentNumber = 1;
While(studentNumber > 0)
{
studentNumber = BIO.getInt();
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber + " ex = " + examMark + " cw = " + courseWork + " mark = " + average);
}
else
{
System.out.print("#End of data");
}
}
}

Methods and arrays

Here is my code:
import java.util.*;
import java.text.*;
public class zadanko4
{
int ile;
public static final int vat8 = 8;
public static final int vat23 = 23;
public static final int vat5 = 5;
//deklaracje zmiennych tablicowych
static double[] price;
static String[] name;
static int[] quantity;
static int[] vat;
//tworzenie tablic
price = new double[ile];
name = new String[ile];
quantity = new int[ile];
vat = new int[ile];
public static void printSellerData(String tekst)
{
System.out.print(tekst);
}
public static void printBuyerData(String company, String taxNo, String phone, String email)
{
System.out.print(company + taxNo + phone + email);
}
public static void printInvoiceDate(Date data)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.print(dateFormat.format(data));
}
public static void printInvoiceHeader(String naglowek)
{
System.out.print(naglowek);
}
public static void printInvoiceProduct(String name, int quantity, double price, int vat)
{
System.out.printf(name + quantity + price + vat);
}
public static void readProductsData()
{
//uzytkownik wprowadza liczbe produktow
System.out.println("podaj liczbe produktow");
Scanner scanner = new Scanner(System. in );
ile = scanner.nextInt();
}
public static void main(String[] args)
{
int i;
String line;
for (i = 0; i < ile; i++)
{
System.out.print("Podaj cene produktu nr " + (i + 1) + ": ");
price[i] = scanner.nextDouble();
System.out.print("Podaj nazwe produktu nr " + (i + 1) + ": ");
name[i] = scanner.next();
System.out.print("Podaj ilosc produktu nr " + (i + 1) + ": ");
quantity[i] = scanner.nextInt();
System.out.print("Podaj vat produktu nr " + (i + 1) + ": ");
vat[i] = scanner.nextInt();
System.out.printf("Dane sprzedajacego\n");
printSellerData("Company: MaxDom Ltd, Kochanowskiego 17, 31-782 Krakow, Poland\n");
printSellerData("Tax no: 677-000-21-39\n");
printSellerData("Phone: +48123454943\n");
printSellerData("Email: office#maxdom.pl\n\n");
System.out.printf("Dane kupujacego\n");
printBuyerData("Softpol Ltd, Mickiewicza 5, 31-009 Krakow, Poland\n", "342-909-33-12\n", "+48505392100\n", "office#softpol.eu\n");
// printInvoiceNumber(+numer+);
Date data = new Date();
printInvoiceDate(data);
printInvoiceHeader("|No.|Product desciptrion |Quantity |Unit price |Total |VAT rate |VAT |Gross|");
printInvoiceHeader("|______________________________________________________________________________________________________|");
//printInvoiceProduct("name[i]", ilosc[prod], cena[prod], vat[prod]");
printInvoiceProduct("|" + (i + 1) + " |" + name[i] + " |" + quantity[i] + " |" + price[i] + " |" + (quantity[i] * price[i]) + " |" + (vat[i] / 100.0) + " |" + (quantity[i] * price[i] * (vat[i] / 100.0)) + " |" + (quantity[i] * price[i]) * (1 + (vat[i] / 100.0)));
}
}
}
and my problems:
I have 4 errors like: error: <identifier> expected. It is connected
with arrays but i have no idea what is wrong.
By the last line: printInvoiceProduct.... I want to display 1 product which user entered, but nothing displays.
Why is that?
Create new memory addresses for arrays as you refer them. Like;
static double[] price = new double[ile];
This is also not enough because these static arrays trying to make a static reference to a non-static variable, "ile". So if you want your arrays to be static, just make "ile" static also.
printInvoiceProduct method is declared to pass 4 arguments to it but you've called it by only one String object.
Even if you solve compilation errors you will face again problems.
For example you are creating an array with size zero This will fail. So instead of creating your array objects above; create in the main function after knowing size of array.
So get rid of ile variable. Take input in the main and then instantiate all the array.
Even I don't see a need of class level arrays all can be method local.
On top of that I don't think this is correct platform to solve such problem. Consider putting your problem on
https://codereview.stackexchange.com/

Java Currency Denomination Issue

I'm trying to teach myself Java and running into a little hiccup just two chapters into the book I got :P This is one from one of the exercises:
"Write a class that calculates and displays the conversion of an entered number of dollars into currency denominations---20s, 10s, 5s, and 1s."
I'm going on four hours of reading from 0 knowledge of coding thus far so hopefully this doesn't sound too simple a question to answer. I'm sure there's a much more efficient way of writing this entire thing, but my question pertains to how I can terminate the entire thing if the user answers "yes" or continue on with the revised version if they answer "no"?
Also any advice or guidance you guys can give me on learning Java would be much appreciated!
Thanks for taking the time to read this
import javax.swing.JOptionPane;
public class Dollars
{
public static void main(String[] args)
{
String totalDollarsString;
int totalDollars;
totalDollarsString = JOptionPane.showInputDialog(null, "Enter amount to be converted", "Denomination Conversion", JOptionPane.INFORMATION_MESSAGE);
totalDollars = Integer.parseInt(totalDollarsString);
int twenties = totalDollars / 20;
int remainderTwenty = (totalDollars % 20);
int tens = remainderTwenty / 10;
int remainderTen = (totalDollars % 10);
int fives = remainderTen / 5;
int remainderFive = (totalDollars % 5);
int ones = remainderFive / 1;
JOptionPane.showMessageDialog(null, "Total Entered is $" + totalDollarsString + "\n" + "\nTwenty Dollar Bills: " + twenties + "\nTen Dollar Bills: " + tens + "\nFive Dollar Bills: " + fives + "\nOne Dollar Bills: " + ones);
int selection;
boolean isYes, isNo;
selection = JOptionPane.showConfirmDialog(null,
"Is this how you wanted the total broken down?", "Select an Option", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
isYes = (selection == JOptionPane.YES_OPTION);
JOptionPane.showMessageDialog(null, "You responded " + isYes + "\nThanks for your response!");
isNo = (selection == JOptionPane.NO_OPTION);
int twenties2 = totalDollars / 20;
int tens2 = totalDollars / 10;
int fives2 = totalDollars / 5;
int ones2 = totalDollars / 1;
JOptionPane.showMessageDialog(null, "Total Entered is $" + totalDollarsString + "\n" + "\nTwenty Dollar Bills: " + twenties2 + "\nTen Dollar Bills: " + tens2 + "\nFive Dollar Bills: " + fives2 + "\nOne Dollar Bills: " + ones2);
}
}
First of all, you don't really seem to need the two booleans for isYes and isNo. Basically you asking the user whether he wants a different solution, that is one true/false value (or rather: isNo is the same as !isYes since the option pane will only return one of the values YES_OPTION and NO_OPTION).
What you'll want to do next is go to your 'refined' version if the user indicates that the first output was not what he wanted:
int selection = JOptionPane.showConfirmDialog(null,
"Is this how you wanted the total broken down?", "Select an Option", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (selection == JOptionPane.NO_OPTION) {
int twenties2 = totalDollars / 20;
int tens2 = totalDollars / 10;
int fives2 = totalDollars / 5;
int ones2 = totalDollars / 1;
JOptionPane.showMessageDialog(null, "Total Entered is $" + totalDollarsString + "\n" + "\nTwenty Dollar Bills: " + twenties2 + "\nTen Dollar Bills: " + tens2 + "\nFive Dollar Bills: " + fives2 + "\nOne Dollar Bills: " + ones2);
}
If the user selects 'Yes', your main method is done anyway, so there's no need to do anything in this case.

Categories

Resources