Invalid Character Constant in Java? - java

Here is my code:
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
/*
Medium Speed
Air 1100 feet per second
Water 4900 feet per second
Steel 16,400 feet per second
Write a program that asks the user to enter "air", "water", or "steel", and the distance that a sound wave will
travel in the medium. The program should then display the amount of time it will take.
You can calculate the amount of time it takes sound to travel in air with the following formula:
Time = Distance / 1100
You can calculate the amount of time it takes sound to travel in water with the following formula:
Time = Distance / 4900
You can calculate the amount of time it takes sound to travel in steel with the following formula:
Time = Distance / 16400
*/
public class SpeedOfSound
{
public static void main(String[] args)
{
String input;
char timeTraveled;
Scanner keyboard = new Scanner(System.in);
double distance;
double time;
double time2;
double time3;
time = (distance/ 1100);
time2 = (distance/ 4900);
time3 = (distance/ 16400);
DecimalFormat formatter = new DecimalFormat("#0.00");
System.out.println("Enter air, water, or steel: ");
input = keyboard.nextLine();
System.out.print("Enter distance: ");
distance = keyboard.nextDouble();
switch(timeTraveled)
{
case 'air':
System.out.printf("The total time traveled is " + formatter.format(time) + ".");
break;
case "water":
System.out.printf("The total time traveled is " + formatter.format(time2) + ".");
break;
case "steel":
System.out.printf("The total time traveled is " + formatter.format(time3) + "seconds.");
timeTraveled = input.charAt(0);
break;
keyboard.close();
}
} // main()
} // class SpeedOfSound
Why is case 'air': giving me the error invalid character constant twice? My professor has a different example for a different program and it's almost the same as what I'm doing but he doesn't get the error. Why do I get this error?

You've got several problems here.
First, single quotes are reserved for single characters, like 'a'. Whole strings need to be placed in double quotes.
Second, timeTraveled is never assigned anything anyway by the time you use it, so it "might" not have been initialized by the time you try to run it (and get things to compile). You probably want to use input instead.
This is to say, as long as you're using Java 7 or newer, you should write this as your switch argument:
switch(input) {
// statements to follow
}
I'm not sure what that assignment at the end of your "steel" case is meant to do, but you may want to move its logic out of the switch statement entirely.

In some programming languages, single quotes (') and double quotes (") are interchangeable. In Java (and also in C and C++), they are not.
If you want to specify a multi-character string literal, use double quotes: "air".
Additionally, it is not clear what do expect to happen when you compare a char (timeTraveled) to a string ("air").

I dont understand the logic of this program. If U need to enter the word and then do something depending on it try to make something like
String timeTraveled;
if (timeTraveled.equals("air")){
//do something
} else if (timeTraveled.equals("water")) {
//do something
} ...

I found multiple issue in your code:
It should be "air" not 'air' (solution for your op).
Datatype of timeTraveled is char but you are trying to match it with String (like "air", "water", etc.).
timeTraveled is not initialized.
distance is not initialized while doing calculation for time, time1 & time2.
keyboard.close(); is unreachable code. Move it outside the switch block or add it in default case.
Ideally, you should be using chars in your switch case or create enum for better clarity.

#justaregularguy - You are getting this error because you have taken air as a character.
mention air as String and you will be fine.
This will help you to - in case you will try non permitted values.
"Cannot switch on a value of type Float. Only convertible int values, strings or enum variables are permitted"

'air' is using single quotes. Single quotes denote a character constant. What you're looking for is "air", a String constant.
You seem to be a new programmer. I made some improvements to your program, and I'll show you them here:
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
/*
Medium Speed
Air 1100 feet per second
Water 4900 feet per second
Steel 16,400 feet per second
Write a program that asks the user to enter "air", "water", or "steel", and the distance that a sound wave will
travel in the medium. The program should then display the amount of time it will take.
You can calculate the amount of time it takes sound to travel in air with the following formula:
Time = Distance / 1100
You can calculate the amount of time it takes sound to travel in water with the following formula:
Time = Distance / 4900
You can calculate the amount of time it takes sound to travel in steel with the following formula:
Time = Distance / 16400
*/
public class SpeedOfSound {
public static void main(String[] args) {
char timeTraveled; //what is this even doing here?
Scanner scanner = new Scanner(System.in);
double time = (distance/ 1100);
double time2 = (distance/ 4900);
double time3 = (distance/ 16400);
DecimalFormat formatter = new DecimalFormat("#0.00");
System.out.println("Enter air, water, or steel: ");
String material = scanner.nextLine();
System.out.print("Enter distance: ");
double distance = scanner.nextDouble();
switch (material) {
case "air":
System.out.printf("The total time traveled is " + formatter.format(time) + ".");
break;
case "water":
System.out.printf("The total time traveled is " + formatter.format(time2) + ".");
break;
case "steel":
System.out.printf("The total time traveled is " + formatter.format(time3) + "seconds.");
timeTraveled = material.charAt(0); //what is this even doing here?
break;
}
scanner.close();
} // main()
} // class SpeedOfSound
Made the spacing and indenting more consistent
Renamed your Scanner object. "keyboard" is not an appropriate name for a Scanner object, since scanner works with not only keyboard input, but also string and file input.
I combined the declaration of your "time" variables and the definition
E.g.
double time; //a declaration of "time"
time = (distance/ 1100); //a definition of "time"
//becomes:
double time = (distance/ 1100); //a declaration AND definition of "time"
changed 'air' to "air"", also, changed the switch case variable to "material" (which used to be called "input", and is the string that holds the user's input), rather than it using timeTraveled (some miscellaneous character?)
Since your program is only going to be displaying one time of the three possibilities, why calculate all 3? I suggest you rework your algorithm as follows:
Ask the user for the material and distance they want. Set a variable "speed" equal to 1100, 4900, or 16400 depending on the user's choice of air, water or steel. Then, calculate time as distance / speed.
This saves you from repeating 3 identical System.out.println() statements, saves you from having 3 time variables (when you only need 1),

Related

Unexpected outcome with System.out.println

I'm in the process of making a program using input from a text file, it only has 2 lines of text in it which is
120 (this is the time)
2 (this is changes)
My code is meant to read the user's input which converts hours to minutes, and then asks for a number of changes. If the hours entered are 02:00 which is 120 minutes and the changes entered are 2 or less then it will come back saying 'acceptable', and if not it will read 'unacceptable' however I am having a bit of trouble formulating this. If anybody could provide assistance I would appreciate it greatly!
Code to follow:
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class InputOutput {
public static void main(String[] args) throws IOException{
final Scanner S = new Scanner(System.in);
final Scanner inFile = new Scanner(new FileReader("task.txt"));
// open file and associate objects
int IOminutes = Integer.parseInt(inFile.next());
int changes = Integer.parseInt(inFile.next());
// close the input file
inFile.close();
System.out.print("Specify Time (HH:MM): ");
String givenTime = S.next();
System.out.print("Specify Changes: ");
String givenChanges = S.next();
// save the index of the colon
int colon = givenTime.indexOf(':');
// strip the hours preceding the colon then convert to int
int givenHours = Integer.parseInt(givenTime.substring(0, colon));
// strip the mins following the colon then convert to int
int givenMins = Integer.parseInt(givenTime.substring(colon + 1, givenTime.length()));
// calculate the time's total mins
int mins = (givenHours * 60) + givenMins;
// using given time
System.out.println(givenTime + " = " + mins + " minutes");
if (!givenTime.equals(IOminutes) && changes >= 3) {
System.out.println("Time: " + givenTime + ", Changes: " + givenChanges + " = unacceptable!");
} else if (givenTime.equals(IOminutes) && changes <= 2) {
System.out.println("Time: " + givenTime + ", Changes: " + givenChanges + " = acceptable!");
}
S.close();
}
}
Your inputs (file-based and user-based) look reasonable.
By the time you reach your if-elseif logic on line 40, you have the following values (all values based on the problem description in the question):
loaded from "task.txt"...
IOminutes: 120
changes: 2
user input:
givenTime="02:00"
givenChanges=2
givenHours=2
givenMins=0
mins=2*60+0 = 120
Your conversion from strings to integers looks like no problem.
Your desired outcome of "acceptable" / "unacceptable" is hard for me to understand; not what it is doing, but Why it is doing that.
I'm having trouble understanding why you have two "changes".
This would make more sense to me if you just had:
task.txt: IOminutes=120, changes=2
given: time="hh:mm"
Now compute difference (in minutes) between task.txt's IOminutes and user's given time. Let's call that difference givendiff. Then you have something like:
if givendiff > changes then unacceptable.
Examples (user input values more or less made up):
task.txt: IOminutes=120, changes=2
test 1: given time="02:00" (computed givendiff=0, so acceptable)
test 2: given time="01:50" (computed givendiff=-10, so unacceptable)
test 3: given time="02:05" (computed givendiff=5, so unacceptable)
test 3: given time="02:02" (computed givendiff=2, so acceptable)
test 3: given time="01:58" (computed givendiff=-2, so acceptable)
I would encourage you to review the original requirements and verify whether your user is supposed to be give you an extra "changes" in addition to task.txt's changes. Or if you're supposed to compute a the difference between task.txt's IOminutes and the user-entered value, and complain if that difference exceeds task.txt's changes value.
I would go further but this seems like a homework or code-challenge problem; if so, hopefully this is enough to help nudge your perspective to re-thing what "changes" means in the original requirements. Good luck.

passing user input to methods java

Hey guys i am a complete beginner in java and i am trying to write a program that goes this way:
painting company has determined that for every 115 square feet of wall
space, one gallon of paint and eight hours of labor will be required.
The company charges $18.00 per hour for labor.
Write a program that allows the user to enter the number of rooms to
be painted and the price of the paint per gallon. It should also ask for
the square feet of wall space in each room. The program should have
methods that return the following data:
The number of gallons of paint required
The hours of labor required
The cost of the paint
The labor charges
The total cost of the paint job
Then it should display the data on the screen
this is what i have so far. i can get the user input and the number of gallons but when i try to calculate the number of hours of labor what it does is it calculates the labor from the result of the previous calculation which is not what i want..this is what i have so far
int resultnumberofhours = hoursoflabor(numberofsquarefeet,115,8);
System.out.println("the number of hours needed are " + resultnumberofhours);
}
public static int hoursoflabor(int numberofsquarefeet, int squarefeet,int labor){
int resultnumberofhours = numberofsquarefeet/115*8;
return resultnumberofhours;
}
Rather then taking one by one you can try code like this
Scanner dd = new Scanner(System.in);
int[] vars = new int[5];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}
The only problem that I can see with the code is that you are not doing anything with the results. Try the following:
int result = numberofsquarefeet(numberofsquarefeet, 115, 1);
System.out.println("Number of square feet: " + result);
When returning something from a java function you can either assign that value to a variable of the same type you specify as the return type of the function, or you can use the output in a print statement for example. If you do nothing with the output, that result is lost.
Hope this helps.
You have to either print the result at the end:
System.out.println("enter number of square feet");
numberofsquarefeet = Keyboard.nextInt();
int resultSqFeet = numberofsquarefeet(numberofsquarefeet, 115, 1);
System.out.println("number of square feet is" + resultSqFeet);
}
or inside the methods:
public static int numberofsquarefeet(int numberofsquarefeet, int squarefeet, int paint) {
int result = numberofsquarefeet / 115 * 1;
System.out.println("number of square feet is " + result);
return result;
}
The same goes with hoursoflabor
I suggest you step back from writing the code and analyze your problem a bit first.
You have a data model and a process which you can describe in more detail. This will help you come up with a good design for your classes and methods. If you immediately start writing code, especially as a beginner, it usually ends up like a pile of spaghetti.
Here is my suggestion for the data model:
PaintingCompany
PAINT_GALLONS_PER_SQUARE_FOOT = 1 / 115
LABOR_HOURS_PER_SQUARE_FOOT = 8 / 115
LABOR_DOLLARS_PER_HOUR = 18
Room
wallSpaceSquareFeet
Paint
dollarsPerGallon
gallons
calculatePaintCostInDollars()
Project
rooms
paint
calculateGallonsOfPaintRequired()
calculateHoursOfLaborRequired()
calculateLaborChargesInDollars()
calculateTotalCostInDollars()
Note that the PaintingCompany class only contains constants. You could put the main() method in this class if you like.
The type and amount of paint are modeled as a single class 'Paint'. You could argue this is inaccurate and have a separate PaintType (enum) representing known types of paint and their prices but I figured this was feature creep at this point. So with the model above you need to instantiate a Paint instance with the correct price and then set the amount of paint on it. The Paint class will then have a function to calculate the total paint price.
It would be an idea to model the units explicitly. The model is now fixed on dollars and gallons but in future you might wish to switch to euros and liters in order to sell the application in Europe. For now I didn't model units because it probably over complicates the exercise. To avoid confusion it is important that the units are specified clearly as part of the variable or method name Space rockets have been known to crash due to errors of this genre.
The process could look like this:
Create a new Project
Ask the user for the paint price
Set the paint price on the project's Paint object
Start an iteration:
Add a new Room object to the Project
Ask the user for the wall space of the Room in square feet
Ask the user if there is another room
If yes, iterate from step 4
If no, print a report with the required project data
Note that some of these process steps are good candidates for separate classes:
Iteration could be put in the PaintingCompany class
Getting input from the user. It's good to keep this separate so you can easily change it later without affecting other code.
Printing the report. Reporting is usually a bit complex, has output formatting etc and is a nice separate concern. You also want to be able to change the report implementation without affecting other code.
If you post new code based on this (or your own) design I am happy to comment on it or help you with any questions.

Shipping Program

So I seem to have put together majority of this program correctly. Ask I skim through I realized I missed something and go back and add it in. Now as I run the program for a final test I realize that it is no longer calculating the miles correctly. I input 500 for example and will get 1 in return for number of miles shipped.
input = JOptionPane.showInputDialog("Enter package weight: ");
weight = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter approximate miles package is being shipped: ");
miles = Integer.parseInt(input);
miles = (miles+499)/500;
input = JOptionPane.showInputDialog("Enter number of units shipped: ");
units = Integer.parseInt(input);
I know I am not doing the math correctly in order to find the correct amount charged per unit but what is concerning for now is the miles being shown incorrectly in my output. Any suggestions? Thanks!
Assuming miles is declared as double (if it's not, you should declare it as double so you can assign it a real number). This line
miles = (miles+499)/500;
is making a integer division (int/int = int). To get a double, you must cast it:
miles = (double)(miles+499)/500;
or, as #Vulcan suggested
miles = (miles+499)/500.0; // here 500.0 is a double
It seems like the data type of miles variable is int.Please change it to double and re-run the application.
Also as per ur comment updating the logic :
Let the input you entered is :
double weight = 7; //input
double miles = 550; //input
double unit = 2; //input
double charges =0; //charge of the shipment initialise with 0
charges = (3.70*miles*unit*weight)/(500*7);
System.out.println("The charges is "+charges);
The charges of 1 unit is $3.70 per 7 pound weight per 500 miles.
Also update the existing code :
miles = Integer.parseInt(input); //Use double as conversion
miles = (miles+499)/500; // remove the line

exponential growth in java, return type array of doubles

Im working on a CS assignment and Im having a little trouble understanding how to output an array of doubles that represent the amt of money in a bank account at increments of time given a user specified growth rate. I have a main method that asks the user for initialAmount of $, a growthRate and the number of time intervals (denoted iA, gR and nP for inital Amount, growth Rate and number of Periods). this method then calls another method which is of return type double[]. My issue is with the code inside my for-loop, it compiles fine but outputs gibberish. heres the code:
import java.util.Scanner;
public class Benford {
public static double[] generateBenfordNumbers (double iA, double gR, int nP) {
double[] bankStatement = new double[nP];
for (int i = 0; i<nP; i++) {
bankStatement[i] = (iA*(Math.pow((1+(gR)), (i++))));
}
return bankStatement;
}
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double iA;
double gR;
int nP;
System.out.print("What is the initial amount of money that you are starting with? : ");
iA = scan.nextDouble();
System.out.println();
System.out.print("What is the amount of growth per time period? : ");
gR = scan.nextDouble();
System.out.println();
System.out.print("How many time periods would you like to use? : ");
nP = scan.nextInt();
System.out.println();
generateBenfordNumbers(iA, gR, nP);
System.out.print(generateBenfordNumbers(iA, gR, nP));
}
}
In the line
bankStatement[i] = (iA*(Math.pow((1+(gR)), (i++))));
i++ increments i a second time. You probably want:
bankStatement[i] = (iA*(Math.pow((1+(gR)), i + 1)));
or, if we clean it up,
bankStatement[i] = iA * Math.pow(1 + gR, i + 1);
i + 1 returns a value 1 greater than that of i, but does not actually increment the variable itself.
Also, do you really have to use Math.pow each time? Can't you just manually set the first element of your array to iA and subsequently use bankStatement[i-1] to compute bankStatement[i]? Doing something like this will probably improve your program.
i is incremented twice : at loop level and into the body
The gibberish output looks like this:
[D#1b67f74
which is s double array text representation. You could use:
System.out.print(Arrays.toString(generateBenfordNumbers(iA, gR, nP)));
You should not be incrementing i inside your call to Math.pow. This is because you already increment it in your for loop. The result is that elements of your array are getting skipped and not set. This is probably where the gibberish-ness is coming from.
You probably want to change:
bankStatement[i] = (iA*(Math.pow((1+(gR)), (i++))));
To:
bankStatement[i] = iA*Math.pow(1+gR, i);
Also, as an aside, you generally shouldn't use so many parenthesis because it makes it hard to read. If you're not sure what the order of operations is, look it up.
What the others said, you're incrementing i twice so I'm not going to repeat that. I just want to add that brackets are good to organize formulas and to ensure correct execution order of calculations, but if you overuse them, they can obfuscate the intention of your program and they may make the problem you're looking for harder to spot. Compare
bankStatement[i] = iA * Math.pow(1.0 + gR, i+1);
with
bankStatement[i] = (iA*(Math.pow((1+(gR)), (i))));
See what I mean?
EDIT - following ARS very valid remark about the initial value of i, I changed the cleaned up statement.

How to obtain and utilize next String in Java

I have been fighting with this for quite some time and have found a couple useful resources, yet the problem persists.
Here's my code:
import java.util.Scanner;
public class Stocks {
public static void main(String [] args){
// value of stock at beginning of year and end of year.
final int beginningStock = 10;
final int endStock = 20;
// value of stocks by quarter; there are three quarters.
int firstQuarter;
int secondQuarter;
int thirdQuarter;
String broker;
String Buy;
firstQuarter = 10;
secondQuarter = 30;
thirdQuarter = 20;
//Tell client the maximum value/price of the stock during the year.
System.out.println("The maximum price of a stock share in the year is: $" + secondQuarter + ".");
// Tell client the minimum value/price of the stock during the year.
System.out.println("The minimum price of a stock share in the year is: $" + firstQuarter + ".");
//Ask broker if you want to buy or sell
Scanner input = new Scanner(System.in);
System.out.println("Would you like to Buy or Sell stocks? Please use Buy or Sell commands.");
broker = input.next("");
if (broker == "Buy"){
//Calculate percentage increase of stock through year if the broker wants the client to buy.
//The values are relative to the start of the year.
double percentIncrease;
percentIncrease = (double)(endStock - beginningStock)/(beginningStock);
//Convert decimal to percentage and tell client percentage increase relative to beginning of year.
System.out.println("The percentage increase of the stock through the year, relative to beginning of year, is: %"+ ((int)(percentIncrease*100+.5))+ "." );
}
else if (broker == "Sell"){
//Calculate change relative to end of year
double endIncrease;
endIncrease = (double)(endStock - beginningStock)/(endStock);
//Convert decimal to percentage and tell client percentage increase relative to end of year.
System.out.println("The percentage increase of the stock through the year, relative to end of year, is: %"+ ((int)(endIncrease*100))+ "." );
}
}
}
The issue I am having is around line 29:
//Ask broker if you want to buy or sell
Scanner input = new Scanner(System.in);
System.out.println("Would you like to Buy or Sell stocks? Please use Buy or Sell commands.");
broker = input.next("");
if (broker == "Buy"){
//Calculate percentage increase of stock through year if the broker wants the client to buy.
//The values are relative to the start of the year.
double percentIncrease;
percentIncrease = (double)(endStock - beginningStock)/(beginningStock);
//Convert decimal to percentage and tell client percentage increase relative to beginning of year.
System.out.println("The percentage increase of the stock through the year, relative to beginning of year, is: %"+ ((int)(percentIncrease*100+.5))+ "." );
It will take the String but will not use it. I don't know what I am doing wrong. Forgive me this is my first post on here.
The problem is that == tests for reference-equality rather than value-equality; that is, it checks that the two sides are the same object, rather than equivalent objects. You need to change this:
if (broker == "Buy"){
to this:
if (broker.equals("Buy")){
Use equals() instead of == to compare strings.
== is the identity comparison operator, not equivalence.
As others said, you should use equals() to compare instances of String.
You have another problem in your code. You're using ScannerĀ“s method next(String pattern), which will return a String if it matches the passed pattern. Since you're passing an empty Stringas the pattern it will raise an exception. You should be using next() instead.
"Buy".equals(broker) should be condition check
In Java string comparison should be .equals not ==

Categories