Syntax error in calling a method java (newbie) [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The 2 answers posted both fixed it. thank you very much and i am embarrassed by how simple it was.
sorry for posting such a basic question and thank you for your time.
From the menu method at the top i wish to call 2 different methods to complete an action based on the input. i cannot find anywhere how to call a void method.
I don't know why the second one wont work as i used a similar thing earlier on.
public void CheckOutMenu(ArrayList basket )
{
choice = 0;
while ( choice !=4 ) {
Scanner in = new Scanner ( System.in);
{
switch(in.nextInt()){
//print the number of items in the basket
case 1:
//working
break;
case 2:
//dont know how to call on option 2 the listBasket method
break;
case 3:
//to call the method
//error and wont compile
double totalCost = CalcTotalCost(totalCost = 0);
//printing what the method returns
System.out.print("The total price of your basket is £" );
break;
case 4:
choice = 4;
break;
default:
System.out.println("please enter a whole number that represents you're choice");
}
}
}
}
protected void listBasket(ArrayList basket )
{
//code inside works fine
}
public double CalcTotalCost(double total, ArrayList basket)
{
//code inside works fine
return total;
}

you can call a void method like any other method, except that you don't have to do anything with the return value because there isn't one.
case 2:
listBasket(basket);
break;
for your third case, you have to pass in both a double and an ArrayList if you want to pass 0 as your double, than you can just post a double literal.
case 3:
/* if you don't want totalCost to go out of scope right away,
* declare it above the switch statement */
double totalCost = CalcTotalCost(0.0, basket);
...
break;

Your error is here, as I'm sure you know:
double totalCost = CalcTotalCost(totalCost = 0);
However, your CalcTotalCost method is defined thus:
public double CalcTotalCost(double total, ArrayList basket)
You've sent it the total, but you haven't sent it a basket.

Related

Projekt Hangman game [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 2 years ago.
Improve this question
I am a beginner in Java and I am working right now with a small projekt, a hangman game. One of the functions I am working on right now is a method where it takes a char input, check if the input is already added to the list or not, if it is, a message will show up saying "You have already used that character!" and the user will have to guess again, otherwise the input will be added to the list. My issue right now is that nothing is happening, inputs are not added to the list at all.
This is what I have done so far:
Any advice/help would be appreciated!
public static ArrayList<Character> getGuesses(ArrayList<Character> allGuesses, char input){
for (int i = 0; i < allGuesses.size(); i++) {
if (allGuesses.get(i) == input) {
System.out.println("You have already used that character!");
}else {
allGuesses.add(input);
}
}
return allGuesses;
}
You are adding the input character on each iteration as you search the collection. You should only add it after you have searched the collection and not found it.
for (int index = 0 ; index < allGuesses.size() ; ++index) {
if (allGuesses.get(index) == input) {
System.out.println("You already used that character!");
return allGuesses;
}
}
allGuesses.add(input);
return allGuesses;
However, this can be simplified by using the Collection contains method such that you do not employ a loop.
if (allGuesses.contains(input)) {
System.out.println("You already used that character!");
return allGuesses;
}
allGuesses.add(input);
return allGuesses;
If possible, consider switching the type of allGuesses to a Set implementation (e.g. HashSet). A Set seems to better match how you are using your collection and allows you to reduce this method to...
if (! allGuesses.add(input)) {
System.out.println("You already used that character!");
}
return allGuesses;

How can i get my PrimeNumber generator to work? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
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.
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.
Improve this question
I tried to write an primenumber generator. The method calcall() should return prime numbers (2,3,5,7...). Unfortunately I get the error, that the method doesn't returns an integer, wich I don't understand. Here is my code:
package primenumber;
public class primecalc {
public static int calcall(int a) { //actual generator
int konstante = a; //is this number a prime num?
int divisor = a-1; //divisor
int var1 = 0; //variable = 0
while(divisor>1) {
int quotient = konstante%divisor; //calc modulo
if(quotient == 0) { //if modulo==0 switch var1 to
var1++; //1 -> no primenumber
break; //stop calculating
} else { //else keep calculculating
divisor--; //until divisor <= 1
}
}
if(var1==0) { //if var1 still 0;
return konstante; //is a primnumber ->
} //return konstante
}
public static void main(String[] args) { //main function
int number = 3; //start with 3
while(True) { //(i'll add 2 manually)
System.out.println(calcall(number)); //print the prime number
number++; //increase number by one
}
}
}
The error is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type int
at primenumber/primenumber.primecalc.calcall(primecalc.java:5)
at primenumber/primenumber.primecalc.main(primecalc.java:28)
What is wrong?
The gray lines on the code you posted are being ignored by the compiler.
The use of /* and */ makes everything between these seen by the compiler as comments. And that is why those lines are grayed out. If you want to comment on the same line as the code, I'd advise you to use //.
Also, it is common practise to use multi-line comments only to describe functions and place them just above the header of the function. Any other comments should be short, concise and describe functionality. Good variable names and well written code should do most of the explaining, and single line comments should be used when it's a bit harder toperceive what's going on.
Cheers

ArrayUtils has a bug? it does actually delete but [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 8 years ago.
Improve this question
In case You want to test it your self:
[link]https://gist.github.com/anonymous/091750563384024e0ffa
[link]https://gist.github.com/anonymous/1f05cdd1d1685d103326
Everything worked fine in deleteItem function it deleted what i wanted, but when i tried to see the array again it shows the original array again even though I already return a new array
public static ItemTracker[] deleteItem(ItemTracker[] listItems) {
for(int i = 0; i < listItems.length; i++) {
if (listItems[i] == null) {
break;
} else if(input.equalsIgnoreCase("Everything")){
listItems = ArrayUtils.remove(listItems, i); // ArrayUtils is actually deleting it but... see output in other function
System.out.println("Content of Array : " + Arrays.toString(listItems)); // It deleted the index that i want and return a new array
// return listItems; I tried to return here as well but same result
}
}
}
return listItems; // which is here
}
Original array: [naufal,joker,batman,null,null,null,null,null,null,null]
Output after delete items, I'm deleting joker as in index 1:
[naufal,batman,null,null,null,null,null,null,null]
It worked but..
After i run displayArray method:
public static void displayArray(ItemTracker[] listItems)
System.out.println("Content of Array : "
+ Arrays.toString(listItems));
}
I get:
[naufal,joker,batman,null,null,null,null,null,null,null]
same array;
I posted multiple of same questions, and tried all the solutions from people here but it doesn't work. What is the real problem over here?, seems like i couldn't of anything else.
For the sake of this problem this only applies to array not List or ArrayList
In your code at:
case 3:
deleteItem(listItems);
break;
you forgot to assign the returned array to listitems:
case 3:
listItems=deleteItem(listItems);
break;

Calculator in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Lately I've worked on simple calculator that can add, substract, multiply and divide.
public static void main(String arr[]){
double num1, num2;
String ans = null;
System.out.println("Calculator manu:");
System.out.println("\n"+"a for adding");
System.out.println("b for substracting");
System.out.println("c for multiplying");
System.out.println("d for dividing");
Scanner NumInput = new Scanner(System.in);
System.out.println("\n"+"Enter number one: ");
num1 = NumInput.nextDouble();
System.out.println("\n"+"Enter number two: ");
num2 = NumInput.nextDouble();
while(true)
{
Scanner AnsInput = new Scanner(System.in);
System.out.println("\n"+"Choose operation.");
String answer = AnsInput.next();
if(AnsInput.equals("1"))
{
answer = Double.toString(num1+num2);
System.out.println("\n"+"The sum of the first and second number is: "+answer);
}
else if(AnsInput.equals("2"))
{
answer = Double.toString(num1-num2);
System.out.println("\n"+"Subtraction of the first and the second number is: "+answer);
}
else if(AnsInput.equals("3"))
{
answer = Double.toString(num1*num2);
System.out.println("\n"+"The product of the first and second number is: "+answer);
}
else if(AnsInput.equals("4"))
{
answer = Double.toString(num1/num2);
System.out.println("\n"+"Ratio of the first and the second number is: "+answer);
}
}
}
But what if I want to wright program that works like an ordinary calculator; it adds, subtracts, multiplies, divides, ... ,but not only whit two but multiple numbers.
This can certainly be done! Although it requires substantial framework. However, if you want to use this type of simplistic code, what you need to do is store the numbers somewhere else, outside this function, and every two numbers you apply an operation to, you store it and use it as the first argument along the third you wanted to use. And so on. Does this make sense?

Cannot resolve nullpointerexception [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
System.out.println("Welcome to the Personal Contact Assistant!");
System.out.println("How can I help you?");
System.out.println("(add) (get) (quit)");
String option = input.nextLine();
Contact[] Contacts;
Contacts = new Contact[500];
int index = 0;
boolean finished = false;
while(finished==false){
switch (option) {
case "add":
System.out.println("You have selected add.");
Contact newContact = new Contact();//constructs new contact object called newContact
newContact.setNewInfo();//gathers input for newContact
System.out.println("Contact Will be Saved as:");
newContact.print();//prints gathered information
Contacts[index] = newContact;//saves contact to array
index++;//advances index
System.out.println("Can I do something else for you? (add) (get) (quit)");
option = input.nextLine();
break;
case "get":
System.out.println("You have selected get.");
System.out.println("Enter the contact's first name:");
String tempName;
tempName = input.nextLine();
for(int i=0; i<499; i++){
System.out.println(":"+i);
if(Contacts[i].getFirstName().equals(tempName)){
System.out.println("Contact Found:");
Contacts[i].print();}
}
System.out.println("Can I do something else for you? (add) (get) (quit)");
option = input.nextLine();
break;
These are add and get segments for a contact app I am working on. My Contact class contains methods for setting and getting name, address etc of contacts. I receive no compiler errors but while running the program I get a nullpointerexception error at the for loop. additionally the output will only print 1 number from the System.out.println(":"+i); line (which I added to find out how many loop iterations were actually happening), unless it finds a contact with that first name, in which case it returns the full contact information for each contact and then errors out. I just want it to complete the loop, print ever contact with that first name, and then go back to the main outer loop. Help?
If you run get() before manually adding 500 contacts, ghis line will throw when i exceeds the number of contacts you've added, since we go to 499 regardless of the number you have added.
if(Contacts[i].getFirstName().equals(tempName)){
Even if it finds the one you're looking for, it will continue on through 499. There are a few ways to fix it.
If it's expected that you'll always find it, stop when you find it.
Change the loop to:
for (i = 0; i < index; i++)
Use an ArrayList or other collection class, which manages size for you. Then your search can become:
for (Contact contact : Contacts) {

Categories

Resources