Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm supposed to write exceptions to prevent invalid objects, such as Strings having no blanks or the double and int numbers being in a certain range. I am really confused on how to do this. Am I supposed to use an if/else statement? Or more try/catch statements?
EDIT: Each object needs to be validated. The strings cannot have blanks or contain only blanks, and the numbers cannot be less than zero. There are five other try/catch statements but I only included one. My question is what would I write so that the exception output is different for the different problems and is there a way to write it to avoid writing each exception for each separate try/catch? I looked at other posts about writing exceptions but I haven't learned what super is or does and cannot use it.
public class CD {
String artistname = "";
String albumname = "";
double cdprice = 0;
int amountinstock = 0;
public CD(final String artistname, final String albumname, final double cdprice, final int amountinstock) {
this.artistname = artistname;
this.albumname = albumname;
this.cdprice = cdprice;
this.amountinstock = amountinstock;
}
public static void main(final String[] arg) throws Exception {
try {
final CD cd1 = new CD("Muse", "The Resistance", 11.99, 20);
System.out.println(cd1.toString());
System.out.println("=========================");
} catch (final CDException cde) {
System.out.println(cde.getMessage());
System.out.println("=========================");
}
}
}
I would check the String, int,... with an if-statement and if something is incorrect throw an IllegalArgumentException.
First you have to write conditions (i.e. if statements) that check if the input is invalid. When you detect invalid input, you should throw an exception.
You can write custom exception like mentioned here.
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
You can give some logical name to your custom exception like IntegerNumberOutofRangeException.
And then you can use if else in your code and throw that custom exception for specific condition you have mentioned.
Code
int intNumber = 50;
if (intNumber > 60 && intNumber < 100) {
// Do your work
} else {
throw new CustomException("Integer number out of expected range of 60 to 100");
}
You should use IF to make validations.
A best practice is to not throw an exception from the constructor of a class.
Another best practice is to not make validations in the constructor of the class.
So a ruff improvement of your code would be (i didn't run it and there are still improvements to be made):
public class CD {
String artistname = "";
String albumname = "";
double cdprice = 0;
int amountinstock = 0;
public String ValidationMessage = "";
public CD(final String artistname, final String albumname, final double cdprice, final int amountinstock) {
this.artistname = artistname;
this.albumname = albumname;
this.cdprice = cdprice;
this.amountinstock = amountinstock;
}
public boolean ValidateCD()
{
this.ValidationMessage = "";
if (/*insert validation condition here*/)
{
this.ValidationMessage = "CD IS NOT VALID BECAUSE TITLE IS WRONG";
return false;
}
return true;
}
public static void main(final String[] arg) throws Exception {
final CD cd1 = new CD("Muse", "The Resistance", 11.99, 20);
final boolean isValid = cd1.ValidateCD();
if (!isValid) {
System.out.println(cd1.ValidationMessage);
}
}
}
Related
This question already has answers here:
Get variable by name from a String
(6 answers)
Closed 4 years ago.
I would like it so that a user can tell my code that when a certain variable has a certain value it should do something. I have written a simple code sample of what I would like this to look like and I hope you can make sense of it. Is it in any way possible to make a String and let Java check wheter the variable that carries the same name is equal to the value of another variable.
int turn = 1;
String variable = "turn";
int compareToThisValue = 1;
if (variable.toVariable() == compareToThisValue) {
System.out.println("Yes it works thank you guys!");
{
I guess the following code can help. It uses java Reflection to get the job done. If you have some other requirements this can be tweaked to do so.
import java.lang.reflect.*;
class Test {
int turn = 1;
boolean checkValueVariable(String variableName, int value) throws Exception {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals(variableName))
return field.getInt(this) == value;
}
return false;
}
public static void main(String... args) {
Test test = new Test();
String variableName = "turn";
int variableValue = 1;
try {
System.out.println(test.checkValueVariable(variableName, variableValue));
} catch (Exception e) {
e.printStackTrace();
}
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I keep receiving this error but I cannot see any logical errors in my code.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
private double getValueOrDefault(String symbol, double defaultValue) {
double value = getValue(symbol);
if (value != -1)
return value;
else
return defaultValue;
}
public void createStocks() {
// try get stock realtime values
stocks.add(new TechStock("BB", 30.3));
stocks.add(new TechStock("GOOG", getValueOrDefault("GOOG", 5.8)));
stocks.add(new TechStock("AMZN", getValueOrDefault("AMZN", 6.3)));
stocks.add(new FinanceStock("GLNG", getValueOrDefault("GLNG", 121)));
}
public static double getValue(String symbol) {
// read data
try {
URL url = new URL(API_URL.replace("XXX", symbol));
Scanner s = new Scanner(url.openStream());
// find price
while (s.hasNextLine()) {
String line = s.nextLine();
if (line.startsWith("\"price\"")) {
// split shenanigans
String[] f = line.split("\"");
return Double.parseDouble(f[3]);
}
}
// if we reached here: the stock is invalid
return -1;
} catch (Exception ex) {
ex.printStackTrace();
}
return -1;
}
public class StockFrame extends Frame
{
private int amount;
private Portfolio portfolio;
private ArrayList <StockMarket> stocks = new ArrayList<StockMarket>();
private TextArea stockDetails;
private TextField purchaseCode;
private boolean found = false;
private int locateStock() {
for(int i = 0; i<stocks.size(); i++) {
if(stocks.get(i).getCode().equals(purchaseCode.getText())) {
return i;
}
}
return -1;
}
private void a() {
int position = locateStock();
if(position != -1){
StockMarket bs = stocks.get(position);
.....
}
I tried changing I to 1 but I still receive the NullPointerException.
The error seems to be located at the int position = locateStock(); but I am unsure.
A NullPointerException occurs when you try to reference an object that hasn't been declared at that point in the execution of your program.
The fact that you still got the exception when you tried changing the initial value of i to 1 tells me that when you call locateStock(), your List of TechStocks hasn't been initialized with a new List<TechStock>() statement prior to calling locateStock(). Therefore, when you try to declare the for loop using stocks.size(), you get an exception, since stocks is null at that point.
However, it's difficult to say how to exactly fix your problem because you didn't really offer enough information in your snippet for anyone to know how that code fits in context with the rest of your program.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am a bit lost...I'm learning Java and have to program a small poll command line application.
We are supposed to program it in german first(to be consistent between us all), so I'll try to translate it, so it's easier to read for you.
My problem is, that it's throwing an exception (while compiling) as following:
Exception in thread "main" java.lang.NullPointerException
at communication.Poll.addQuestionItem(Poll.java:18)
at main.PollTool.main(PollTool.java:8)
am I initializing my array "questionItems" wrong? Aren't I supposed to do it like that? What's wrong here? Did I forget something? :(
main.PollTool:
package main;
import communication.Poll;
public class PollTool {
public static void main(String[] args) {
Poll poll = new Poll ("Best Smartphone:",3);
poll.addQuestionItem("iPhone"); //<--line 8
poll.addQuestionItem("Android");
poll.addQuestionItem("Windows Phone");
poll.askQuestions("This poll determines the polularity of different Smartphones.");
}
}
communication.Poll:
package communication;
import java.util.Scanner;
import calculations.QuestionItem;
public class Poll {
private String questionTitle;
private QuestionItem[] questionItems;
private int count;
private Scanner in = new Scanner(System.in);
public Poll(String s,int arraySize){
questionTitle = s;
questionItems = new QuestionItem[arraySize]; //<--problem here?
}
public void addQuestionItem(String s){
if(count<questionItems.length){
questionItems[count++].setItemText(s); // <--exception here
}
}
public void askQuestions(String topic){
System.out.println(topic);
System.out.println(questionTitle);
for(int i=0; i<questionItems.length; i++){
System.out.println("- - - "+ questionItems[i].getItemText() +" - - -");
System.out.print("Your numerical answer: ");
questionItems[i].vote(in.nextInt());
}
}
void evaluation(){
//not ready :)
}
}
calculation.QuestionItem:
package calculation;
public class QuestionItem {
int count;
int overall;
String text;
public void vote (int pointValue){
overall += pointValue;
count++;
}
public double getDurchschnitt(){
return (double) overall/count;
}
public void setItemText(String s){
text = s;
}
public String getItemText(){
return text;
}
}
When you initialize an array of objects like this:
questionItems = new QuestionItem[arraySize];
All of the values are null by default.
In addQuestionItem, you try to call a method on an object in the array. However, that object starts off null, so this line of code doesn't work:
questionItems[count++].setItemText(s);
What you have to do is initialize the object before setting the text:
questionItems[count] = new QuestionItem();
questionItems[count].setItemText(s);
count++;
Alternatively, you can do what Constant suggested, and initialize all the objects when you initialize the array.
By the looks of it, you're making the array but it doesn't contain the objects yet. You probably want this in the constructor instead.
questionItems = new QuestionItem[arraySize];
for(int i = 0; i < questionItems.length; i++) {
questionItems[i] = new QuestionItem();
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am doing a project at the moment and am kind of stumped with one aspect of it,
The project tag is:
Create a class encapsulating the concept of a file. Include a constructor, getter/setter, toString method, equals method. The added bit is to one I have trouble with
Also write a method returning the extension of the File, i.e. the letters after the last dot(.) in the
filename
If the filename is hello1.doc, then the method should return doc
If there is no dot(.) in the filename, then the method should return “unknown extension”
Here is my code so far for the File class proper
public class File {
private String fileName;
public File()
{
}
public File(String fn)
{
this.fileName = fn;
}
public String getName()
{
return this.fileName;
}
public void setName(String name)
{
this.fileName = name;
}
public String toString()
{
return fileName;
}
public boolean equals(File f1)
{
if (f1.getName().equals(fileName))
{
return true;
}
else
{
return false;
}
}
public void String(File f1){
if (f1.toString().contains(".")){
String h=f1.toString();
String[] parts = h.split(".");
String i= parts[0];
String j= parts[1];
System.out.println("File is of type"+" "+parts[1]);
}
else{
System.out.println("Unkown file extension.");}
}
}
I am completely stumped as to how to complete this. I think the problem is that when I instantiate a new 'file' object the string isn't passed through my final if/else. A nudge in the right direction would be greatly appreciate :)
Cheers
Ps here is my test class (I know the if/else should be in the main file above :) )
public class Filemain {
public static void main(String[] args) {
File f1 = new File();
File f2 = new File ("test.pdf");
File f3= new File ("results.doc");
System.out.println(f2);
System.out.println(f3);
if (f2.equals(f3))
{
System.out.println("You have not got complete documentation");
}
else
{
System.out.println("You have the complete documentation");
}
i think the problem is in the constructor when you do
f1.toString()
when you need to be doing
f1.getName()
plus your class name already exist in java, try using MyFile instead
finally you want to use
public void toString(File f1)
or
public void extString(File f1)
instead of
public void String(File f1)
is it even compiling?
public void String(File f1){ is not a valid constructor, this is a simple method that returns nothing.
Also the toString() method isn't overloaded so it will use the default implementation which is to not the filename.
int lastDot = f1.fileName.lastIndexOf(".");
if (lastDot >= 1) { System.out.println( f1.subString(lastDot); }
Will tell you where the extension starts if there is one and will print out the extension.
Everything else code wise that you posted is way incorrect and just noise.
I think you have one issue reproted - bad method/ constructor names.
For extn:
String has lastIndexOf, use that? 5 lines :
String getExtn()
int i = fileName.lastIndexOf(".");//can use last index of character too
String extn = “unknown extension”;
if(i > -1 ){
extn = fileName.subString(i + 1) ;
}
return extn;
}
One edge case is dot is last char - you should get an empty stirng then, can do something else by checking if i < fileName len
You can use regex to extract the extension:
public String getExtension() {
if (!fileName.contains("."))
return "unknown extension";
return fileName.replaceAll(".*\\.([^.]*)", "$1");
}
Although this might seem to be a curiosity, this is honestly how I would code it.
I want to list all names that end with "Reda" and ignore case sensitivity, I have tried the condition in the toString method at the bottom, but it would not print any thing.
public class Customer {
public static void main(String[] args) throws IOException {
File a = new File("customer.txt");
FileWriter v = new FileWriter(a);
BufferedWriter b = new BufferedWriter(v);
PrintWriter p = new PrintWriter(b);
human Iman = new human("Iman", 5000);
human Nour = new human("Nour", 3500);
human Redah = new human("Redah", 0);
human iman = new human("iman", 200);
human MohamedREDA = new human("MohamedREDA", 3000);
human Mohamed_Redah = new human("Mohamed Redah", 2000);
human[] h = new human[6];
h[0] = Iman;
h[1] = Nour;
h[2] = Redah;
h[3] = iman;
h[4] = MohamedREDA;
h[5] = Mohamed_Redah;
p.println(Iman);
p.println(Nour);
p.println(Redah);
p.println(iman);
p.println(MohamedREDA);
p.println(Mohamed_Redah);
p.flush();
}
}
class human {
public String name;
public double balance;
public human(String n, double b) {
this.balance = b;
this.name = n;
}
#Override
public String toString() {
if (name.equalsIgnoreCase("Reda") && (name.equalsIgnoreCase("Reda"))) {
return name + " " + balance;
} else
return " ";
}
}
Please avoid putting condition in toString method. Remove the condition there
public String toString() {
return name + " " + balance;
}
and change your logic in Customer class
human[] h = new human[6];
h[0] = Iman;
h[1] = Nour;
h[2] = Redah;
h[3] = iman;
h[4] = MohamedREDA;
h[5] = Mohamed_Redah;
for (int i = 0; i < h.length; i++) {
if (h[i].name.toLowerCase().endsWith("reda")) { // condition here
p.println(h[i]);
}
}
And make use of loops do not duplicate the lines of code.Every where you are manually writing the lines.
Check Java String class and use required methods to add condition.
String redahname = ("Redah").toLowerCase(); //put your h[0] instead of ("Redah")
if(name.endsWith("redah")){ //IMPORTANT TO BE IN LOWER CASE, (it is case insenitive this way)
//your code here if it ends with redag
System.out.println(redahname);
} //if it does not end with "redah" it wont out print it!
You can use this, but can you please explain your question more? What exactly do you need?
try this
#Override
public String toString() {
if (name.toLowerCase().endsWith("reda"))) {
return name + " " + balance;
} else
return " ";
}
String.equals() is not what you want as you're looking for strings which ends with "Reda" instead of those equal to "Reda". Using String.match or String.endsWith together with String.toLowerCase will do this for you. The following is the example of String.match:
public class Reda {
public static void main(String[] args) {
String[] names = {"Iman", "MohamedREDA", "Mohamed Redah", "reda"};
for (String name : names) {
// the input to matches is a regular expression.
// . stands for any character, * stands for may repeating any times
// [Rr] stands for either R or r.
if (name.matches(".*[Rr][Ee][Dd][Aa]")) {
System.out.println(name);
}
}
}
}
and its output:
MohamedREDA
reda
and here is the solution using endsWith and toLowerCase:
public class Reda {
public static void main(String[] args) {
String[] names = {"Iman", "MohamedREDA", "Mohamed Redah", "reda"};
for (String name : names) {
if (name.toLowerCase().endsWith("reda")) {
System.out.println(name);
}
}
}
}
and its output:
MohamedREDA
reda
You shouldn't put such condition in toString() method cause, it's not properly put business application logic in this method.
toString() is the string representation of an object.
What you can do, is putting the condition before calling the toString() , or making a helper method for this.
private boolean endsWithIgnoringCase(String other){
return this.name.toLowerCase().endsWith(other.toLowerCase());
}
None of your humans are called, ignoring case, Reda, so your observation of no names printed is the manifestation of properly working logic.
Your condition is redundant: you perform the same test twice:
name.equalsIgnoreCase("Reda") && (name.equalsIgnoreCase("Reda"))
If you need to match only the string ending, you should employ a regular expression:
name.matches("(?i).*reda")
toString is a general-purpose method defined for all objects. Using it the way you do, baking in the business logic for just one special use case, cannot be correct. You must rewrite the code so that toString uniformly returns a string representation of the object.