I am doing my first Java assignment and I'm struggling with an error here.
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ctof;
/**
*
* #author Braydon
*/
import java.util.Scanner;
public class CtoF {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Enter temperature in Celsius:");
Scanner temp = new Scanner(System.in);
String T = scan.nextLine();
T = (T - 32) * 5/9;
System.out.println("Temperature in Fahrenheit =" + T);
}
}
The error it gives me is as follows.
run:
Enter temperature in Celsius:
Exception in thread "main" java.lang.UnsupportedOperationException: Not supported yet.
at ctof.scan.nextLine(scan.java:19)
at ctof.CtoF.main(CtoF.java:21)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
The error is in the line where I perform the math, but I've tried everything and I can't seem to fix it. Please help!
You're calling the wrong function.
You need to call temp.nextLine() instead of scan.nextLine() in order to read the next line. (scan isn't even defined in the code you posted)
HOWEVER: You shouldn't use nextLine() when you need to read a number.
Therefore: Call temp.nextInt() or temp.nextDouble() instead.
I believe you are newbie to java. First of all, you will have to learn about the data types. Well, you can google basics about programming and learn from it.
The solution for your problem :
public class CtoF {
public static void main(String[] args) {
System.out.println("Enter temperature in Celsius:");
Scanner temp = new Scanner(System.in);
int T = temp.nextInt();
T = (T - 32) * 5 / 9;
System.out.println("Temperature in Fahrenheit =" + T);
}
}
Try to use good names for the variables (just a suggestion)
Related
I have a rather complex MILP, but the main problem is the number of continuous variables, not the number of binaries. I just "hard-coded" the linear relaxation to understand its output, and it takes approx. 10-15 minutes to solve (which is not extremely surprising). If I run the MILP with outputs, I don't see anything happening for the first 10 minutes, because it takes those 10 minutes to construct a first integer-feasible solution. So it would help to be able to enable the same outputs I am seeing when solving the linear relaxation "manually" (so something like Iteration: 1 Dual objective = 52322816.412592) within the B&B output.
Is this possible? I googled at bit, but I only found solutions for steering the solution algorithm, or for deriving linear relaxations using callbacks, while I am interested in a "simple" output of the intermediate steps.
It sounds like you are asking for extra detailed logging during the linear relaxation part of the solve during the B&B. Have a look at the CPLEX parameter settings like IloCplex.Param.MIP.Display (try setting this to 5) and also IloCplex.Param.Simplex.Display (try setting to 1 or 2).
within java you could rely on IloConversion objects that will allow you to locally change the type of one or more variables.
See the sample AdMIPex6.java
/* --------------------------------------------------------------------------
* File: AdMIPex6.java
* Version 20.1.0
* --------------------------------------------------------------------------
* Licensed Materials - Property of IBM
* 5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5655-Y21
* Copyright IBM Corporation 2001, 2021. All Rights Reserved.
*
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with
* IBM Corp.
* --------------------------------------------------------------------------
*
* AdMIPex6.java -- Solving a model by passing in a solution for the root node
* and using that in a solve callback
*
* To run this example, command line arguments are required:
* java AdMIPex6 filename
* where
* filename Name of the file, with .mps, .lp, or .sav
* extension, and a possible additional .gz
* extension.
* Example:
* java AdMIPex6 mexample.mps.gz
*/
import ilog.concert.*;
import ilog.cplex.*;
public class AdMIPex6 {
static class Solve extends IloCplex.SolveCallback {
boolean _done = false;
IloNumVar[] _vars;
double[] _x;
Solve(IloNumVar[] vars, double[] x) { _vars = vars; _x = x; }
public void main() throws IloException {
if ( !_done ) {
setStart(_x, _vars, null, null);
_done = true;
}
}
}
public static void main(String[] args) {
try (IloCplex cplex = new IloCplex()) {
cplex.importModel(args[0]);
IloLPMatrix lp = (IloLPMatrix)cplex.LPMatrixIterator().next();
IloConversion relax = cplex.conversion(lp.getNumVars(),
IloNumVarType.Float);
cplex.add(relax);
cplex.solve();
System.out.println("Relaxed solution status = " + cplex.getStatus());
System.out.println("Relaxed solution value = " + cplex.getObjValue());
double[] vals = cplex.getValues(lp.getNumVars());
cplex.use(new Solve(lp.getNumVars(), vals));
cplex.delete(relax);
cplex.setParam(IloCplex.Param.MIP.Strategy.Search,
IloCplex.MIPSearch.Traditional);
if ( cplex.solve() ) {
System.out.println("Solution status = " + cplex.getStatus());
System.out.println("Solution value = " + cplex.getObjValue());
}
}
catch (IloException e) {
System.err.println("Concert exception caught: " + e);
}
}
}
if you use OPL then you could have a look at Relax integrity constraints and dual value
int nbKids=300;
float costBus40=500;
float costBus30=400;
dvar int+ nbBus40;
dvar int+ nbBus30;
minimize
costBus40*nbBus40 +nbBus30*costBus30;
subject to
{
ctKids:40*nbBus40+nbBus30*30>=nbKids;
}
main {
var status = 0;
thisOplModel.generate();
if (cplex.solve()) {
writeln("Integer Model");
writeln("OBJECTIVE: ",cplex.getObjValue());
}
// relax integrity constraint
thisOplModel.convertAllIntVars();
if (cplex.solve()) {
writeln("Relaxed Model");
writeln("OBJECTIVE: ",cplex.getObjValue());
writeln("dual of the kids constraint = ",thisOplModel.ctKids.dual);
}
}
I'm supposed to create a simple program in Java that will take a value for a price and another for a discount. The price must be float and the discount must be int. I managed to create the program well enough to apply the discount properly.
To further on my problem here's my code:
import java.util.Scanner;
public class Ex_g {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner dados = new Scanner(System.in);
float preco;
int desconto;
// System.out.println("preco?");
do {
preco = dados.nextFloat();
} while (preco > 1000.00);
// System.out.println("desconto?");
do {
desconto = dados.nextInt();
} while ( (desconto < 0) && (desconto > 100));
float res = (float)preco - (preco * desconto/100);
System.out.printf("%.2f\n", res);
}
}
It is nothing complicated but the problem resides on how it takes the values, I'm supposed to enter the price as "500.00" for example, yet the program only takes "500,00" difference being it needs a comma.
I am aware that netbeans (I'm using netbeans) does this kind of thing but what made me come here and write this post is the fact that the values are printed with commas (,) too instead of dots ( . ) and thus the platform I'm sending this code to considers the exercise to be wrong...
I'll be trying another compiler but at the same time I'd like to hear someone's opinion on why I can't enter decimal values separated by a dot. And if possible, how can I fix it.
Thanks in advance.
This question already has answers here:
Getting error "cannot find or load main class HelloWorld"
(3 answers)
Closed 6 years ago.
So I need to write a program in java that takes 2 user inputed temperatures in celsius and converts it to Fahrenheit and kelvin. i wrote the code and it works in eclipse but my teacher strictly said it has to work in cmd. it compiles fine but when i go to run it it states could not find or load main class temperatureTester (name of the class with my main). This is my first post so if you need more info please ask and i'm looking for any ideas why this is happening. below is my code for the question.
import java.util.Scanner;
public class temperatureTester{
public static void main (String[]args){
//create 2 objects connecting to temperatureC
temperatureC firstValue = new temperatureC();
temperatureC secondValue = new temperatureC();
// initialize scanner
Scanner stdin = new Scanner (System.in);
//initialize variables
double firstC = 0;
double secondC = 0;
//prompt user for both values
System.out.print("Please enter initial temperatures: ");
firstC = stdin.nextDouble();
secondC = stdin.nextDouble();
//call object set methods and pass entered values as arguments
firstValue.setC(firstC);
secondValue.setC(secondC);
//display the values for the values for different temp. units
System.out.println("1) The current temperature in Celcius is: " + firstValue.getC());
System.out.println("1) The current temperature in fahreinheit is: " + firstValue.getF());
System.out.println("1) The current temperature in kelvin is: " + firstValue.getK());
System.out.println("---------------------------------------------------------------");
System.out.println("2) The current temperature in Celcius is: " + secondValue.getC());
System.out.println("2) The current temperature in fahreinheit is: " + secondValue.getF());
System.out.println("2) The current temperature in kelvin is: " + secondValue.getK());
this is the second class
public class temperatureC{
private double C;
/**
The setC method stores the value in the C field
# param initialC the value stored in C
*/
public void setC(double initialC){
C = initialC;
}
/**
The getC returns the C value and also sets a lower limit,
if a number below is entered it sets it ti the limit.
#Return the value of the C
*/
public double getC(){
if(C < -273.15){
C = -273.15;
}
return C;
}
/**
the getF method calculates and returns a value for C in fahrenheit
#return the computed for C in fahrenheit
*/
public double getF(){
return C * 1.8 + 32;
}
/**
The getK method computes and returns a value for temperature C in kelvin
#return the computed Kelvin value
*/
public double getK(){
return C + 273.15;
}
}
The Best approach might b that you export your project as executable jar file to achieve this have a look on following official ecclipse link http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-37.htm
then next part you need to run it from Command line this is a fun part just change the directory to the path where your jar file is located and then here comes the following command
java -jar yourJar.jar
pause
and then it will b executing like a charm!
Simply compile your both files in cmd using javac
After successfully compiling simply run your main class i.e temperatureTester class using java. It successfully executed.
I am currently trying to Design and implement a stringed musical instrument class.
The instructions for this assignment are:
Data fields for your instrument should include number of strings, an array of string names representing string names (e.g. E,A,D,G),
boolean fields to determine if the instrument is tuned, and if the instrument is currently playing. You are welcome to add additional data fields if you like.
A constructor method that set the tuned and currently playing fields to false.
Other methods 1) to tune the instrument,
to start the instrument playing, and 3) to stop the instrument from playing.
Other methods as you see fit (Add at least one unique method).
That is the main file, I then have to:
create a Java test class that simulates using your instrument class. In your test class be you should at a minimum: a) Construct 10 instances of your instrument,
b) tune your instruments,
c) Start playing your instrument,
d) Call your unique method, and
e) Stop playing your instruments.
(Hint: Arrays and Loops will make your job easier and result in more efficient code!)
I have created both files but my main project file has some issues that prevent me from seeing an output when I test it. (I’m using netbeans to test the program if that helps at all.)
My current test file has no errors but I know that is necessary for the outputs to print on the main java file so I also attached that as well.
here is my main project java file:
import java.io.*;
/* File: KenMasonp3.java
* Author: Kenneth Mason
* Date: 19-04-2014
* Purpose: Design and implement a stringed musical instrument class
* Code edited/modified by myself with sources from LEO classroom modules, Liang
* book, javaprogrammingforums.com, dreamincode.net, and the instructor
*/
public class KenMasonp3 { // start main class
// start main method
public static void main(String[] args) throws IOException {
//creates a file named from the command line argument
File outputFile = new File(args[0]);
PrintWriter output = new PrintWriter(outputFile);
//creates an array of 10 objects
instrument[] guitarArray = new instrument[10];
/*calls methods to construct, tune, play,
*get the string names and stop the instrument array
*/
instrument.constructGuitarArray(guitarArray, output);
instrument.tuneGuitar(guitarArray, output);
instrument.playGuitar(guitarArray, output);
instrument.getStrings(guitarArray, output);
instrument.stopGuitar(guitarArray, output);
//close the file
output.close();
} // main method end
} // end main class
// Guitar class
class instrument {
//method to construct the instrument array
public static instrument[] constructGuitarArray(instrument[] array,
PrintWriter file) {
//creates a random instrument
for (int i = 0; i < array.length; i++) {
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
error is:
* " constructor instrument in class instrument cannot be applied to given types;
required: no arguments
found: int
reason: actual and formal argument lists differ in length "
*/
array[i] = new instrument((int) (1 + Math.random() * 12));
//prints the creation message to file
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol variable createdMessage
* location: class instrument
*/
file.println(array[i].createdMessage);
}
//returns array to main method
return array;
}
//method that calls the tune method for the instrument array
public static void tuneGuitar(instrument[] array,
PrintWriter file) {
//tunes all objects in the array
for (int i = 0; i < array.length; i++) {
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol method
* location: class instrument
*/
array[i].setTune(true);
//prints the tuned message to file
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
*error is: cannot find symbol variable tunedMessage
* location: class instrument
*/
file.println(array[i].tunedMessage);
}
}
//method that calls the play method for the instrument array
public static void playGuitar(instrument[] array, PrintWriter file) {
//plays all objects in the array
for (int i = 0; i < array.length; i++) {
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol method setPlay(boolean)
* location: class instrument
*/
array[i].setPlay(true);
//prints the tuned message to file
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol variable playMessage
* location: class instrument
*/
file.println(array[i].playMessage);
}
}
//method that calls the getStrings method for the instrument array
public static void getStrings(instrument[] array, PrintWriter file) {
for (int i = 0; i < array.length; i++) {
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol method setString(boolean)
* location: class instrument
*/
array[i].setString(true);
//prints the tuned message to file
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol variable stringMessage
* location: class instrument
*/
file.println(array[i].stringMessage);
}
}
//method that calls the stopGuitar method for the instrument array
public static void stopGuitar(instrument[] array, PrintWriter file) {
for (int i = 0; i < array.length; i++) {
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol method setStop(boolean)
* location: class instrument
*/
array[i].setStop(true);
//prints the tuned message to file
/******** CODE BELOW ALWAYS GIVES ME THIS ERROR EVEN WHEN I COPY PASTE ******
* error is: cannot find symbol variable stopMessage
* location: class instrument
*/
file.println(array[i].stopMessage);
}
}
Note: file outputFile = new File(args[0]);
because I need to write the output from your Instrument class methods to a text file that a user entered from the command line arguments
If you can see, my main problem seems to be this line of code:
array[i] = new instrument((int) (1 + Math.random() * 12));
The error says in netbeans:
" constructor instrument in class instrument cannot be applied to given types;
required: no arguments
found: int
reason: actual and formal argument lists differ in length "
I think it's because of this error that I'm getting cannot find symbol on many of my other parts of code.
If anyone needs my text file it is here (but has no apparent errors):
/* File: KenMasonp3.java
* Author: Kenneth Mason
* Date: 19-04-2014
* Purpose: Design and implement a stringed musical instrument class
* Code edited/modified by myself with sources from LEO classroom modules, Liang
* book, javaprogrammingforums.com, dreamincode.net
*/
public class KenMasonp3test { // start main class
public static void main(String[] args) {
}
//instrument class
class guitarInstrument {
//private variable declarations
private boolean tuned, playing;
private String guitarType;
private String[] stringNames;
//public variable declarations
public String playMessage, tunedMessage, createdMessage;
public StringBuilder guitarStringsNames;
//default constructor that generates a random 6 string instrument
public guitarInstrument() {
int strings = (int) (1 + Math.random() * 12);
//generates array based on number of strings
String[] stringNames = new String[strings];
//fills string array with random string names
for (int i = 0; i < stringNames.length; i++) {
stringNames[i] = String.valueOf((char)('A' + Math.random() *
('G' - 'A' + 1)));
}
this.stringNames = stringNames;
//sets instrument name
guitarType = "random " + strings + "-string instrument";
//sets tuned and playing to false
tuned = false;
playing = false;
//sets string for construction of the instrument
createdMessage = "You created a " + guitarType;
} // end of guitar() method
//constructor allowing specific amount of strings
public guitarInstrument(int strings) {
//creates specific instrument based on number of strings input
if (strings == 6) {
//creates and fills string array
String[] stringNames = {"E", "A", "D", "G", "B", "E"};
this.stringNames = stringNames;
//names instrument
guitarType = "guitar";
} // end if
else {
//creates and fills string array
String[] stringNames = new String[strings];
//fills array with random string names
for (int i = 0; i < stringNames.length; i++) {
stringNames[i] = String.valueOf((char)('A' + Math.random()
* ('G' - 'A' + 1)));
}
this.stringNames = stringNames;
//names instrument
guitarType = strings + "-string instrument";
} // end else
//sets tuned and playing to false
tuned = false;
playing = false;
//sets string for construction of the instrument
createdMessage = "You created a " + guitarType;
} // end guitar (in strings) method
//method to tune or untune the instrument
public void setTune(boolean tune) {
this.tuned = tune;
//sets string for tuned instrument
if (tuned == true) {
tunedMessage = "The " + guitarType + " is now in tune";
} // end tuned if
//sets string for untuned instrument
else {
tunedMessage = "The " + guitarType + " is out of tune";
} // end of tuned else
} // end of setTune method
//method to play or stop the instrument
public void playGuitarInstrument(boolean play) {
this.playing = true;
// sets string for playing instrument
if (playing == true) {
playMessage = "The" + guitarType + "is now playing";
} // end playing if
// sets string for unplayed instrument
else {
playMessage = "The" + guitarType + "has stopped";
} // end play else
} // end of playGuitarInstrument method
//method to display the string names of the instrument
public void getStrings() {
//sets stringbuilder with default intro statement
StringBuilder guitarStringNames = new StringBuilder();
System.out.println("The has the following strings:"
+ guitarStringNames);
} // end of getString method
} // end of guitarInstrument method
} // end of main class
Any help would be greatly appreciated.
new instrument((int) (1 + Math.random() * 12));
This line has your problem. instrument does not have a constructor which takes an integer as a parameter.
I am really new to programming, on netbeans i have deleted all the other text, all i have is the following, Why wont the program run?
The error i get is, no main Class found.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package findcost2;
public class Main
/* a program to calculate and display the cost of a product after
* sales tax has been added*/
public class FindCost2
Public static void main (String[] args)
{
double price,tax;
price = 500;
tax = 17.5;
price = price * (1 + tax/100);// calculate cost
// display results
System.out.println("***Product Price Check");
System.out.println("Cost after tax = " + price);
}
}
Try this exactly and name your java file FindCost2.java
package findcost2;
public class FindCost2{
public static void main (String[] args)
{
double price,tax;
price = 500;
tax = 17.5;
price = price * (1 + tax/100);// calculate cost
// display results
System.out.println("***Product Price Check");
System.out.println("Cost after tax = " + price);
}
}
You're missing a curly bracket after class Main and you have two public classes in the same source file. Delete public class Main and change Public to public.
You should probably also use decimal numbers for dealing with currencies
Sooner or later, everyone trying to calculate money in Java discovers that computers can't add.
Why is Public capitalized? Shoud be:
public class FindCost2 {
public static void main(String[] args) { ... }
}
Numerous problems with this code:
The outer class (Main) does not have an opening bracket. Insert the { bracket.
The inner class (FindCost2) does not have an opening bracket. Insert the { bracket.
The public modifier for the main method is capitalized. Start with a lowercase p.
The main method is nested in an inner class. This is really bad form. To make it work anyway, the inner class needs to be static. Insert the static keyword.
When put like this, it compiles:
public class Main {
/*
* a program to calculate and display the cost of a product after sales tax
* has been added
*/
public static class FindCost2 {
public static void main(String[] args) {
double price, tax;
price = 500;
tax = 17.5;
price = price * (1 + tax / 100);// calculate cost
// display results
System.out.println("***Product Price Check");
System.out.println("Cost after tax = " + price);
}
}
}
However, there is absolutely no point to the outer class (Main). Just delete this. When the outer class is removed, the inner class (FindCost2) need not be static anymore. Remove the keyword.
It is really bad form to declare multiple variables on one line (as in double price, tax;). Split that to two lines:
double price;
double tax;
There are good reasons not to use the double type for monetary values. With a little extra work, you can easily write a simple Money class. Check javapractices.com for a good overview on that.
Hope that helps!