In my QuestionnaireUI.java class
private void btnProceedActionPerformed(java.awt.event.ActionEvent evt) {
tblResults.setRowSelectionAllowed(true);
int temp = tblResults.getSelectedRow();
Global.manu = tblResults.getValueAt(temp, 1).toString();
Global.mod = tblResults.getValueAt(temp, 2).toString();
Global.price = "R" + (Integer)tblResults.getValueAt(temp,3).toString(); //line of code that gives me the error message
this.dispose();
new PaymentUI().setVisible(true);
}
In my Global.java class that I use for all my global variables
public class Global {
public static int rowSelect;
public static String manu;
public static String mod;
public static int price;
public static int financeprice;
public static int rate = 9;
}
you are Adding R (a String) to (Integer)tblResults.getValueAt(temp,3).toString()
There are a few issues here:
tblResults.getValueAt(temp,3).toString() returns a String, which is not an integer so can not be cast to an integer.
Adding a String to anything will always give you a String, so "R" + something will always return a String. which you are then trying to assign to an Integer.
As the + operator with String as one of the arguments converts the other argument to String:
Global.price = "R" + tblResults.getValueAt(temp,3);
Unless price declared as int in which case:
Global.price = (Integer)tblResults.getValueAt(temp,3);
Related
Hi I am unable to know what I am doing wrong.
I have a string which is pass as an argument to a my class.
I have to split that string and assign the respective values to the member variable but it is not working properly.
Here is my class.
package virtusa;
public class pratice {
String getName;
Double getPrice;
int getQuantity;
String temp[] = null;
public pratice()
{
}
public pratice(String rawInput)
{
temp = rawInput.split("$$##",2);
getName = temp[0];
getPrice = Double.parseDouble(temp[1]);
getQuantity =Integer.parseInt( temp[2]);
}
public String getGetName() {
return getName;
}
public Double getGetPrice() {
return getPrice;
}
public int getGetQuantity() {
return getQuantity;
}
}
here is my main class
package virtusa;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String stub = in.nextLine();
pratice temp = new pratice(stub);
System.out.println(temp.getName);
System.out.println(temp.getQuantity);
System.out.println(temp.getPrice);
}
}
My Input = apple$$##12.5$$##9
error i am having -
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at virtusa.pratice.<init>(pratice.java:17)
at virtusa.demo.main(demo.java:12)
String::split take regex as a parameter, so the $ has special meaning. You will need to escape it with a \
One of problems in your code in not escaping special characters as some comments are mentioning. In my opinion clearest solution is to use Patter quote
rawInput.split(Pattern.quote("$$##"), 3);
Other problem is that you clearly need to get there elements since you are trying to get temp[0], temp[1] and temp[2]
So the final code should look something like this
String getName;
Double getPrice;
int getQuantity;
String temp[] = null;
public Practice() {
}
public Practice(final String rawInput) {
temp = rawInput.split(Pattern.quote("$$##"), 3);
getName = temp[0];
getPrice = Double.parseDouble(temp[1]);
getQuantity = Integer.parseInt(temp[2]);
}
public String getGetName() {
return getName;
}
public Double getGetPrice() {
return getPrice;
}
public int getGetQuantity() {
return getQuantity;
}
When I run my code, the error I get says "incompatible types: char cannot be converted to a string"
public class Credit {
public static void main(String[] args) {
long numberLong = Comp122.getLong("Number: ");
String number = numberLong + "";
System.out.println(Integer.parseInt(number.charAt(0)) * 2 + Integer.parseInt(number.charAt(1)) * 2);
System.out.println("VISA");
}
}
char is actually int that holds ASCII number of the given character. So to transform e.g. character 5 to int value, you have to find difference between (char)5 and (char)0.
public class Credit {
public static void main(String[] args) {
long numberLong = 123456789L;
String numberStr = String.valueOf(numberLong);
System.out.println(toInt(numberStr, 0) * 2 + toInt(numberStr, 1) * 2);
System.out.println("VISA");
}
private static int toInt(String numberStr, int index) {
return numberStr.charAt(index) - '0';
}
}
To answer your question title:
Character.toString(char)
This converts a char to a String.
To answer what you are trying to do:
Character.digit(char,int)
Converts a character to the value of the digit it represents in the specified base. In your case you are using base 10.
I'm working on a calculator and I search how I can optimize my code.
The thing is that I have much code duplication due to if I'm working on the first number of the calculation or the second. So I'm searching if it is possible to modify the value of an attribute sent in argument of a function ? (I think not because I saw nowhere the answer).
Maybe I'm expressing myself badly so here is a code below to explain what I'm talking about:
public class MyClass
{
private static int number1 = 1;
private static int number2 = 2;
public MyClass()
{
changeValueOf(number1, 3);
}
private static void changeValueOf(int number, int value)
{
//Change here the value of the correct field
}
}
First of all, you can modify static variables inside the method:
private static void changeValueOf(int value)
{
number1 = value;
}
But I guess that is not what you a looking for :)
In Java (and in most other languages) primitive data type (int, short, long, etc) passed by value, e.g. the copy of value passes to the method (function).
And reference types (objects, e.g. created with new operator) passed by reference. So, when you modigy the value of reference type (object) you can see the changes in the outer scopes (for example, in method caller).
So, the answer is no - you cannot change the value of int so that the outer scope would see the updated value.
Howewer, you could wrap your int values with some object - and it change the value inside of it:
public class Example {
public static void main(String[] args) {
Example app = new Example();
// Could be static as well
Holder val1 = new Holder(1);
Holder val2 = new Holder(2);
app.changeValue(val1, 7);
System.out.println(val1.value); // 7
}
public void changeValue(Holder holder, int newValue) {
holder.value = newValue;
}
static class Holder {
int value;
Holder(int value) {
this.value = value;
}
}
}
Also, you could create an array with 2 values and update them inside the method, but it's not very good approach IMO
And finally, you could just return updated value and assign it to your variables:
public class Example {
private static int number1 = 2;
private static int number2 = 3;
public static void main(String[] args) {
Example app = new Example();
number1 = app.mul(number1, 7);
number2 = app.mul(number2, 7);
System.out.println(number1); // 14
System.out.println(number2); // 21
}
public int mul(int a, int b) {
return a * b;
}
}
One possibility is to use an array to store your variables, instead of separate variables with numbers affixed. Then you would write number[1] instead of number1 for example. You can pass the array index number around to indicate which variable you are referring to.
public class MyClass
{
private static int[] variables = {1, 2};
public MyClass()
{
// change value of first variable
changeValueOf(0, 3);
// now variable[0] = 3
}
private static void changeValueOf(int number, int value)
{
variables[number] = value;
}
}
My instance of the class "Conversion" returns this error when I compile the program.
import java.util.Scanner;
public class Convert {
private class Conversion{
public String getConversion(int inchInput) {
int yards = (inchInput - (inchInput % 36)) / 36;
int feet = (inchInput % 36) - ((inchInput % 36) % 12);
int inches = (inchInput % 36) % 12;
return yards + "yards, " + feet + "feet, and " + inches + "inches.";
}
} // end of class Conversion
public static void main( String[] args ) {
Scanner scanner = new Scanner(System.in);
int inchInput;
Conversion conversion;
conversion = new Conversion();
// prompt
System.out.println("Please enter an amout of inches (integer): ");
inchInput = scanner.nextInt();
String output = conversion.getConversion(inchInput);
} // end of method main()
} // enf of class Convert
Make the Conversion class static so that there is an accesible enclosed instance of the class
private static class Conversion {
...
}
Conversion is inner class to Convert.So you can't access it directly.
You need to create Conversion object like this.
Convert convert =new Convert();
Conversion conversion;
conversion = convert.new Conversion();
or declare the Conversion as static
class Convert {
private static class Conversion{
...............
............
}
}
and create Conversion object like this
Conversion conversion = new Convert.Conversion();
set modifier of class to static
private static class Conversion
at
You need probably:
Convert.Conversion cc = new Convert().new Conversion();
cc.getConversion(...);
...
public class Fraction
{
public Franction(int n, int d)
{
int num = n;
int denom = d;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
Hello, I'm trying to learn Java... The book I'm working out of suggests that the output of the code above should print "Fraction = 5/10", but when I try it I just receive "Fraction = Fraction#33469a69" which I assume is printing the reference to where it is stored? I understand how it is suppose to work with the constructor I just don't receive the expected output. Any help would be greatly appreciated... Thanks!
To get the desired output, you need to overload toString() method in the Franction class. This method is used to determine textual representation of the object. By default, it is ClassName#hashCode.
Also, you probably would like to store the values you receive in the constructor as fields. Right now, you store the numerator and denominator in constructor's local variables, that are destroyed as soon as the constructor exits.
Try something like this:
public class Fraction
{
private final int num
private final int denom;
public Franction(int n, int d)
{
this.num = n;
this.denom = d;
}
#Override
String toString()
{
return String.format("%d/%d", num, denom);
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
You need to override the toString method for the same
public String toString(){
StringBuilder stringToReturn = new StringBuilder();
stringToReturn.append(this.num);
stringToReturn.append("/");
stringToReturn.append(this.denom);
return stringToReturn.toString();
}
You have to override the toString() function in your Fraction class.
As per docs of toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
So
Fraction#33469a69 is the textual representation of Fraction class.
To get the required output, write the logic in overridden toString method in Object class and return the string there.
A simple toString implementation looks like
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.someMemeber); //will be in String format
result.append(this.someMemeber);
return result.toString();
}
Try this
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1.getNum() + "/" + f1.getDenom());
}
}
Alternative (Better way to do this)
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
#Override
public String toString(){
return (f1.getNum() + "/" + f1.getDenom());
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1 );
}
}
You need to study more about encapsulation , the Object class and the toString() method.
Happy Coding :)
Try the following:
public class Fraction {
private final int num;
private final int denom;
public Fraction(int num, int denom) {
this.num = num;
this.denom = denom;
}
#Override
public String toString() {
return num + "/" + denom;
}
public static void main(String[] args) {
Fraction f1 = new Fraction(5, 10);
System.out.println("Fraction = " + f1);
}
}
You have to store the values in the object you create. Then override the toString method of Object to get your desired output.
Output:
Fraction = 5/10
All you are doing is printing out the Object.
If you want to print the contents of the Object you will to create a toString method in you class.
see http://www.javapractices.com/topic/TopicAction.do?Id=55