Java function doesnt work [closed] - java

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 have a small program for inserting data into a database with http.
I made a function to do this but when i call the function in my main file it seems that it does not work. I tried debugging it but when I set a breakpoint on the line it does not show that the function is used. Can someone help me?
public class School_Planner {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
HTTP_Conncetion.Connect();
}
}
.
public class HTTP_Conncetion {
public static void Connect(){
try {
// open a connection to the site
URL url = new URL("http://localhost:8080/HTTP_Connection/index.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print("firstKey=firstValue");
//ps.print("&secondKey=secondValue");
// we have to get the input stream in order to actually send the request
con.getInputStream();
// close the print stream
ps.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
EDIT
After the command of Jon Skeet, i think i have to be a little more specific. The problem i think is that the function does not work or that it skips over the function.

The posted code is just fine it calls the URL
http://localhost:8080/HTTP_Connection/index.php
with the parameter firstKey and its value firstValue
Unless you forgot to do the imports which would result in a compile error to begin with.
I guess your error is on the server side. Please double check the server.
For sure your question is very unspecific - no exception, no exact description of what "function" you think is not called. Not what you expect to happen and what you miss of happening. Please adjust your question in a way that there can be a more concrete answer to your question.

Related

How to debug an if statement that is not working? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
import java.util.*;
public class ass {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[]c={"sid","is","cool"};
List<String>list1=new ArrayList<String>();
for(String w:c){
list1.add(w);
}
String[]q={"is"};
List<String>list2=new ArrayList<String>();
for(String t:q){
list2.add(t);
}
EditList(list1,list2);
for(int i=0;i<list1.size();i++){
System.out.printf("%s ", list1.get(i));
}
}
public static void EditList(Collection<String>l1, Collection<String>l2){
Iterator<String>it=l1.iterator();
while(it.hasNext()){
if(l2.contains(it.next()));
it.remove();
}
}
}
In this programme I have two lists. I wanted to remove the items that are common in the first and second list from the first list and print it. I don't want a workaround or any other code suggestions. Can someone please explain why my code is not working?
I am following New Boston's tutorials.
Here:
if(l2.contains(it.next()));
it.remove();
That semicolon after if is a real statement.
Thus it.remove() happens always; like if ... that if not there!
Thus the real answer: always always always use
if (){
stuff
}
... even for single statements! Same for loops!
try
public static void EditList(Collection<String>l1, Collection<String>l2){
Iterator<String>it=l1.iterator();
while(it.hasNext()){
String current=it.next();
if(l2.contains(current)){
i1.remove(current); // assuming u wish to remove from l1
}
}
}

Turn void method into a boolean-java [closed]

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 7 years ago.
Improve this question
I'd like to make this into a boolean that will return true or false.
I simply got no idea how to , so I need some help.
public static void checkUSPASS(String a,String b) {
try {
con = DriverManager.getConnection(url,username, password);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
String sql;
sql = "SELECT * FROM db Where Email='"+a+"' and Password='"+b+"'";
ResultSet rs = stmt.executeQuery(sql);
if(rs.next())
{
//return true
}
else
{
//return false
}
}
catch (SQLException ex) {
ex.printStackTrace(); }
}
I should probably get all declarations out , but I'd like to hear what do you think guys.
While this is not the answer to your question, but I believe it will help you to make your method better. Probably comment will be more suitable, but comments with large piece of text are hard to read.
Don't use SQL query string composition like you do. Use PreparedStatement instead of that.
Process exceptions inside of your method or throw them further. Printing stack trace is not the exception processing, it hides the problem from the end-user.
To throw the exception further add throws SQLException to your method declaration, and remove try/catch construction from the method body. It will allow the caller to process the exception and will avoid many hard-to-catch bugs later.
Don't store passwords as Strings, it is a bad practice. Hash passwords with salt and store password hashcode.
And finally your method declaration should look like that:
public static boolean checkUSPASS(String username,String hashCode) throws SQLException
First change the method signature to return a value:
public static boolean checkUSPASS(String a,String b)
Then return a value from within the method:
return true;
or:
return false;
Note that all code paths must return some value. So you have this in your try block:
if (rs.next()) {
return true;
}
else {
return false;
}
But in the event of reaching your catch block, something must still be returned:
catch (SQLException ex) {
ex.printStackTrace();
return false;
}
To change a function to boolean in java all you have to do is change void to boolean in your function definition and return true or false at all end points.

I have an error with system.out.print and I don't know why? [closed]

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 9 years ago.
Improve this question
This is my code:
public class Outline {
int rowIndex=62;//hsample number
int colIndex=2;//sample number, will be determined by RNG when I'm done
String val=read1(rowIndex,colIndex);
System.out.print(val);//This is where the error is, I don't know what's wrong with it.
public static final String FILE_NAME = "Copy_of_Words.xls";
public static String read1(int rowIndex, int colIndex){
String value = new String();
HSSFWorkbook wb = null;
try {
wb= new HSSFWorkbook(new FileInputStream(FILE_NAME));
} catch (Exception e){//in here, say what needs to be done
}
HSSFSheet sheet=wb.getSheet("SAT"); //here, user input will determine sheet
HSSFRow row=sheet.getRow(rowIndex-1);
HSSFCell cell=row.getCell(colIndex-1);
DataFormatter formatter = new DataFormatter();
value = formatter.formatCellValue(cell);
return value;
}
}
What exactly is the problem with system.out.print(val)? I can't figure it out. I'm using apache and excel in the program, but I don't think that should cause problems.
You can't use
System.out.print(val);
Out side a method. You should put System.out.print(val); inside a method.
public void myMethod(){
System.out.print(val);
}
You try to execute a statement in the class body. You can't do that.
Every statement must be inside a method (or a constructor or an initializer block).
Only declarations (method/field/constructor/...) can be directly in the class body.
Your
System.out.print(val);
is out side the method scope.
System.out.print(val);
This statement must be present in some function.
Classes are defined this way:
class MyClass {
// field, constructor, and
// method declarations
}
You can't execute statements there. They should be located inside a method. See Declaring Classes.
You cant invoke
System.out.print(val);
on class level. If you want to execute some code then you need to place it in
methods (like public static void main(String[] args){...}),
constructors,
or initializing blocks
Write ur statement
System.out.print(val);
either in Function or main function.

Basic debugging with Java [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I don't know how to fix these errors:
class or interface expected errors
package doesn't exists
cannot find symbol
illegal start of type
cannot access java.lang
How can I better understand where the problems in my code are occurring? How can I debug these issues?
Here is my code:
import java.io.*;
public class ResourcesTesterApp {
public static void main(String[] args) {
String s1 = readLineWithResources();
String s2 = readLineWithFinally();
}
public static String readLineWithResources() {
System.out.println("Starting readLineWithResources method.");
try (RandomAccessFile in = new RandomAccessFile("products.ran", "r")) {
return in.readLine();
}} catch (IOException e) {
System.out.println(e.toString());
}
}
public static String readLineWithFinally() {
System.out.println("Starting readLineWithFinally method.");
RandomAccessFile in = null;
String s = null;
try {
in = new RandomAccessFile("products.ran", "r");
s = in.readLine();
} catch (IOException e) {
System.out.println(e.toString());
} finally {
if (in != null) {
try {
in.close();
System.out.println("RandomAccessFile closed");
} catch (IOException e) {
System.out.println("RandomAccessFile " + e.getMessage());
}
}
}
return s;
}
You question is how to better understand and debug these errors. Well all I can say is, look at the actual error message output, it will normally include a line number. Now you can look at the specific line of code and see if you can spot what is wrong.
I don't know if the formatting of the code in your question comes from a failed attempt at pasting it into stackoverflow.com or if that is also how you are working with it, but you should format it properly and that will help with spotting problems. For example, when I formatted your code above straight away you can see an additional closing curly brace.
Once you have the actual error messages and line numbers etc. your best bet is to google the error and try to understand what it means. Once you have exhausted that avenue come back here and formulate a specific question showing exactly what the error message is and the code you are running. Avoid grouping many problems into one question like you have done here.
this usually means you are writing code outside of a method.
this simply means you referenced a package that the java compiler cannot find.
this means you wrote a nonexistant variable.
this usually means you did not complete a statement, and you started writing the next one.
I dont know about this one, maybe be more specific?
I strongly suggest you take a look at the java tutorials, and follow their examples.
you can find them at http://docs.oracle.com/javase/tutorial/

Testing Java class using JUnit [closed]

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
public void printSummaryForPatient(String name){
Patient p = findPatient(name);
p.printPatientSummary();
p.computeBMI();
}
My method to test:
#Test
public void testPrintSummaryForPatient() {
Patient patient_adult=new Patient("Ted",24,1.90,70.0,"Leicester");
//Patient Patient_child=new Patient("Kate",4,1.90,70.0,"Leicester");
// Patient Patient_elderly=new Patient("Bill",124,1.90,70.0,"Leicester");
surgery_N.findPatient("Ted");
patient_adult.printPatientSummary();
assertEquals("Ted", patient_adult.getName());
assertEquals("-----------PATIENT SUMMARY: ---------"+"\n"+"NAME: "+patient_adult.name+"\n"+"Age: "+patient_adult.getAge()+"\n"+"Address: "+patient_adult.getAddress()+"\n"+"Height: "+patient_adult.getHeight()+"\n"+"Weight: "+patient_adult.getWeight()+"\n"+"------------------------------"+separator,ans.toString());
patient_adult.computeBMI();
assertEquals(19.390581717451525, patient_adult.computeBMI(), 0.0);
}`
The problem is that the way I use to test doesn't cover the original file at all. Hope I can get some help from you guys.
You could assign a different writer to System.out (assuming that's where your output goes) and inspect what gets written there. In general, you probably want to make the writer a parameter of printSummary or inject it into the class somehow.
So basically you want to do this:
#Test
public void testPrintSummaryForPatient() {
Patient patient_adult=new Patient("Ted",24,1.90,70.0,"Leicester");
surgery_N.printSummaryForPatient("Ted");
}
But can't do any asserts, because the Patient is not returned.
Do you want to return the patient?:
public Patient printSummaryForPatient(String name){
Patient p = findPatient(name);
p.printPatientSummary();
p.computeBMI();
return p;
}
After that you could use your assertions. It seems more like a conceptual problem of how you organize your methods.
You have methods in printSummaryForPatient, that don't seem to do anything. Their return value is not returned or saved.

Categories

Resources