Trouble Using Input and Arraylists - java

I am having trouble. I am trying to allow a user to input a parameter for a method in another file. However it is giving me two errors. Can anyone help me please
public int countItem(Item purchase)
{
int quantity = 0;
if(cart.indexOf(purchase) == -1)
quantity = 0;
else
quantity = purchase.getQuantity() ;
return quantity;
}
This is from my second file.
System.out.println ("What item do you want to find?");
purchase = input.nextline(); //ERROR ERROR
System.out.println("You have " + basket.countItem() + purchase + "soup in your cart."); // ERROR
These are the errors am I getting.
--------------------Configuration: <Default>--------------------
F:\School\CS I AP\Chapter 7\Shopping Cart Lab\Shop.java:71: error: cannot find symbol
purchase = input.nextline();
^
symbol: variable purchase
location: class Shop
F:\School\CS I AP\Chapter 7\Shopping Cart Lab\Shop.java:71: error: cannot find symbol
purchase = input.nextline();
I also realized I got a third error.
error: method countItem in class ShoppingCart cannot be applied to given types;

It appears that the Java compiler cannot find the variable purchase. There are a few scenarios for this:
The Item class is in another folder and has not been imported. (very common error)
The variable purchase has not been declared.
Typo errors in the variable name, variable declaration, or method name.
From your error, it seems that you have not declared the variable purchase. It should be:String purchase = input.nextLine();
Also, you made a typo. It should be nextLine() instead of nextline().
Bear in mind that you need to convert your purchase object from a String into an Item object, since your countItem() method only accepts an Item object. The nextLine() method from the Scanner class only returns a String object, you cannot force it directly into a Item object or you will get another compiler error. For example, if you had a constructor for a new Item object that takes in a String:
Item item = new Item(purchase);
int count = itemCount(item);
As for your third error, you had declared your countItem() method to take in one parameter of type Item, but in your code you are calling it without any parameters, hence the compiler complains about it.

The error that you are getting is because the program doesn't know what the variable purchase is. Basically, there is not an object by the name of purchase in scope at the time that it is being called.
If you could post some more of the code to show the full scope of your Main method, that would help us show you where to define purchase so that it is in scope when it is called.
the last error is fixed with (), ie:
System.out.println("You have " + (basket.countItem() + purchase) + "soup in your cart.");
or like this:
int temp = basket.countItem() + purchase;
System.out.println("You have " + temp + "soup in your cart.");
That is of course, assuming that purchase is an int. More context is needed to be sure

you should declare purchase.
String purchase

Related

Having trouble calling a method to edit a string from another class in java

I've got a simple java program that is supposed to take the specified characters in a string and print them back out to the user by doing everything within a secondary method in a secondary class while taking input from the user in the first class.
The problem that I'm having is that when I try to invoke the secondary method in my main method, I get an error that says "The method copy(String) is unidentified for my main method.
My code for the main method is:
System.out.println("Copying - Enter a string");
String currentString = input.next();
System.out.println("The current string is: " + currentString);
System.out.println("Enter the starting position");
int startPosition = input.nextInt();
System.out.println("Enter one past the ending position");
int onePastLastPosition = input.nextInt();
System.out.println("The new string is: " + copy(currentString));
And for the copy method is:
public static String copy(String currentString, int startPosition, int onePastLastPosition) {
currentString = currentString.substring(startPosition, onePastLastPosition);
return currentString;
}
So for example, what the code is supposed to do, is if I input a string "abcd", it returns back to me "bc", but the system gets hung up on the last line in the first method.
Any help with understanding where I went wrong, and how to fix it in the future would be much appreciated.
You didn't provide the method the necessary parameters for it to execute properly.
Method copy is accepting three parameters: currentString, startPosition, onePastLastPosition as per the parameters specified:
public static String copy(String currentString, int startPosition, int onePastLastPosition) {
So you should be calling the method like so:
System.out.println("The new string is: " + copy(currentString, startPosition, onePastLastPosition));
Test Run
Copying - Enter a string
spectric
The current string is: spectric
Enter the starting position
1
Enter one past the ending position
2
The new string is: p
Your copy method is in different class.You have to create the second class instance in first class to call the second class function.
First class
System.out.println("Copying - Enter a string");
....
System.out.println("The new string is: " +
SecondClass.copy(currentString));
P/S : Make sure the number of the parameters are correct.
Your copy method is static, so you should call the method with class prefix, and pass additional arguments (startPosition, onePastLastPosition) you declared.
System.out.println("The new string is: " + YourClassName::copy(currentString, startPosition, onePastLastPosition))
Two things.
your parameters to copy are different than the method signature shows.
you should be calling Copy as a static by prefixing the name of the containing class.
The copy method requires 3 parameters, but you have only provided 1. Add the other two:
copy(currentString, startPosition, onePastLastPosition)
Add an import statement for the copy method:
import static SecondClass.copy;
Or qualify the method:
SecondClass.copy(currentString, startPosition, onePastLastPosition)

Can't get the scanner class to work in Java

I'm trying to get a program together that reads integers that a user inputs. I've been reading about the scanner class which seems to be the most common way to do this in java. However when I copy+paste the examples given on sites like this one I get some kind of error that I have no idea how to fix. Which is frustrating because all the stuff posted is supposed to be completed code that shouldn't have problems!
An example of some code that's supposed to work:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] arguments){
Scanner input = new Scanner(System.in);
String username;
double age;
String gender;
String marital_status;
int telephone_number;
// Allows a person to enter his/her name
Scanner one = new Scanner(System.in);
System.out.println("Enter Name:" );
username = one.next();
System.out.println("Name accepted " + username);
// Allows a person to enter his/her age
Scanner two = new Scanner(System.in);
System.out.println("Enter Age:" );
age = two.nextDouble();
System.out.println("Age accepted " + age);
// Allows a person to enter his/her gender
Scanner three = new Scanner(System.in);
System.out.println("Enter Gender:" );
gender = three.next();
System.out.println("Gender accepted " + gender);
// Allows a person to enter his/her marital status
Scanner four = new Scanner(System.in);
System.out.println("Enter Marital status:" );
marital_status = four.next();
System.out.println("Marital status accepted " + marital_status);
// Allows a person to enter his/her telephone number
Scanner five = new Scanner(System.in);
System.out.println("Enter Telephone number:" );
telephone_number = five.nextInt();
System.out.println("Telephone number accepted " + telephone_number);
}
}
Instead of the program running, it gives me two errors.
On the the line public class ScannerDemo { it gives me this error:
Illegal modifier for the local class ScannerDemo; only abstract or final is permitted
On the next line public static void main(String[] arguments){ I get this error:
The method main can not be declared static; static methods can only be declared in a static or top level type.
I have tried this with many different forms of scanners that are supposed to be all ready to go and get errors every time. What am I doing wrong? How can I fix it?
I am using Processing 3.
Please understand the difference between Java and Processing. Processing is its own language and editor with its own syntax rules, and you can't just copy-paste random Java code and expect it to work. You have to understand how Processing works, and then add code in a way that works in Processing.
Assuming you're using the Processing editor, then your main sketch file should not contain just a class, and it definitely shouldn't contain a main() method. It should contain a setup() and draw() function instead.
If you really want to use a class, then get rid of your main() method, encapsulate your logic in a function inside your class, and then add a setup() or draw() function that uses the class.
Or better yet, stop using a class and just use Scanner in your Processing code.
If you still can't get it working, please post a MCVE in a new question post, and we'll go from there. Good luck.
I believe as #Hovercraft has mentioned you just need this code in a file called ScannerDemo.java, Were guessing you have it in different file name.
Your class name and file name must be same. This is decision to first error.
public static void main(String[] arguments){
isn`t working because first error.

Changing an object's value according to user Input

I am trying to figure a way in how to change an object's value. I've made a class in which it contains set and get for the object and 3 sorts of values being PRICE, QUANTITY and NAME.
The price and name are already set in the test class
System.out.println("How many would you like?");
String quantity = s1.nextLine();
quantity = food1.setQuantity();
quantity = food1.setQuantity(); is wrong. How do I change it according to how much quantity the user wants?
You may try with:
quantity = food1.setQuantity(Integer.parseInt(quantity));
instead of:
quantity = food1.setQuantity();
I don't mean to sound harsh, but programming isn't magic. Look at what you're doing:
String quantity = s1.nextLine();
quantity = food1.setQuantity();
You're overwriting the string with what one would hope to be a void set method. Instead, the method should be a void set method, which accepts an integer, so you would do the following (assuming proper function implementation):
String quantity = s1.nextLine();
food1.setQuantity(Integer.parseInt(quantity));
Not sure if you learned Exception handling yet, but you should wrap this in a try/catch if you have. If not, you can use regular expressions to see if it's an integer, if that is necessary. Odds are this is a class assignment, and you're probably assuming that the input is valid or using exception handling. Good luck.
Assuming, that the quantity is supposed to be an integer, you could write this:
String quanity = s1. nextLine();
//check that quanitity is a valid number before trying to parse it as a number
if(quantity.matches("\\d+"))
{
food1.setQuantity(Integer.parseInt(quantity));
}else
{
System.out.println("The quantity you entered is not a valid number.");
}

Generating reverse words

i am a beginner in java and i am doing practiceit questions off the internet.I tried attempting the question but i dont understand the error.
Write a method called processName that accepts a Scanner for the console as a parameter and that prompts the user to enter his or her full name, then prints the name in reverse order (i.e., last name, first name). You may assume that only a first and last name will be given. You should read the entire line of input at once with the Scanner and then break it apart as necessary. Here is a sample dialogue with the user:
Please enter your full name: Sammy Jankis
Your name in reverse order is Jankis, Sammy
public static void processName(Scanner console) {
System.out.print("Please enter your full name: ");
String full=console.nextLine();
String first=full.substring(0," ");
String second=full.substring(" ");
System.out.print("Your name in reverse order is: "+ second + "," + first);
}
Maybe i will go about explaining my code.So i try to break the two words apart.So i use substring to find the both words and then i hardcode to reverse them.I think the logic is right but i still get these errors.
Line 6
You are referring to an identifer (a name of a variable, class, method, etc.) that is not recognized. Perhaps you misspelled it, mis-capitalized it, or forgot to declare it?
cannot find symbol
symbol : method substring(int,java.lang.String)
location: class java.lang.String
String first=full.substring(0," ");
^
Line 7
You are referring to an identifer (a name of a variable, class, method, etc.) that is not recognized. Perhaps you misspelled it, mis-capitalized it, or forgot to declare it?
cannot find symbol
symbol : method substring(java.lang.String)
location: class java.lang.String
String second=full.substring(" ");
^
2 errors
33 warnings
public static void processName(Scanner console) {
System.out.print("Please enter your full name: ");
String[] name = console.nextLine().split("\\s");
System.out.print("Your name in reverse order is: "+ name[1] + "," + name[0]);
}
Of course it only works if the name has 2 words. For longer names you should write a method which would reverse an array
Take a look at the documentation for the substring() method. It does not take a string as its second parameter.
String first=full.substring(0," ");
String second=full.substring(" ");
What you may want instead is the indexOf() method. First find the index of the space character. Then find the substring up to that point.
int n = full.indexOf(" ");
String first=full.substring(o, n); //gives the first name
As per Java API, substring() accepts either one int argument like substring(int beginIndex) and two int arguments like substring(int startIndex, int endIndex) but you are calling with String arguments. So you're getting those errors. More info can be found here
String API.
go to here http://docs.oracle.com/javase/6/docs/api/java/lang/String.html and read to understand.
public class ex3_11_padString {
public static void main(String[] args) {
System.out.print("Please enter your full name: ");
String f_l_Name = console.nextLine();
String sss[] = f_l_Name.split(" ", 2);
System.out.print("Your name in reverse order is " + sss[1] + ", " + sss[0]);
}
}

need advice with making a name generator in java

Hi, I'm trying to make a Star Wars name Generator and I am stuck. I am suppose to make the program follow these guidelines:
I should make a method called promptstring.
The user's Star Wars name is composed of a first and last name:
For the first name, use the first 3 characters of the user's real first name, concatenated with the first 2 characters of the user's real last name.
For the last name, use the first 2 characters of the user's mother's maiden name, concatenated with the first 3 characters of the user's city of birth.
For the user's Star Wars planet, use the last 2 characters of the user's last name, concatenated with the user's car.
Example:
Enter your first name: Thom
Enter your last name: Yorke
Enter your mother's maiden name: Selway
Enter the city where you were born: Wellingborough
Enter the first car your drove: Audi
You are THOYO SEWEL of KEAUDI
Right now I'm just having compiler errors which are
8 errors found: File: J:\CS Projects\NameGenerator.java [line: 15]
Error: input cannot be resolved
File: J:\CS Projects\NameGenerator.java [line: 18] Error: The method
nextLine() in the type java.util.Scanner is not applicable for the
arguments (int, int)
File: J:\CS Projects\NameGenerator.java [line: 19] Error: last1
cannot be resolved to a variable
File: J:\CS Projects\NameGenerator.java [line: 19] Error: end cannot
be resolved to a variable
File: J:\CS Projects\NameGenerator.java [line: 22] Error: The method
nextLine() in the type java.util.Scanner is not applicable for the
arguments (int, int)
File: J:\CS Projects\NameGenerator.java [line: 25] Error: The method
nextLine() in the type java.util.Scanner is not applicable for the
arguments (int, int)
File: J:\CS Projects\NameGenerator.java [line: 31] Error:
Starwarsname cannot be resolved to a variable
File: J:\CS Projects\NameGenerator.java [line: 34] Error:
Starwarsname cannot be resolved to a variable
I have reworked this program over and over again and I am stuck. Can anyone point me in the right direction or tell me what I am doing wrong. Thank you in advance.
import java.util.*;
public class NameGenerator {
static Scanner wars = new Scanner(System.in);
public static void main(String[] args) {
//Prompt for User's Name
String first,last,mother,city,car;
System.out.printf("Please state your First Name");
first= wars.Line(0,2);
System.out.printf("Please state your Last name");
last=wars.nextLine(0,1);
last1=wars.nextLine(-1,end);
System.out.printf("Please state your mothers maiden name");
mother=wars.nextLine(0,1);
System.out.printf("Please state the city you were born in ");
city=wars.nextLine(0,2);
System.out.printf("Please state your first car");
car=wars.nextLine();
Starwarsname=first+last + mother + city + "of" + last + car ;
System.out.println("In a galaxy far, far away you are known as " + Starwarsname + " MAY THE FORCE be with you!");
}
}
You're using the scanner incorrectly. It should be like this:
first = wars.nextLine();
If you want only the first two characters of first, then:
first = first.substring(0,2);
Same with the rest of your strings. You can't get a substring from using the scanner class. Scanner class only scans your input. Use the String.substring method (show above) to get the substring.
Edit: Also, you're trying to use a few variables that are undeclared. Make sure you declare the variable "Starwarsname" as String first before assigning it to something.
The change the statements having
wars.nextLine(0,1);
to
wars.nextLine();
Later use
str.substring(beginIndex, endIndex)
method of String to get whatever part of the entered string you want,concatenate and print them.
Error: end cannot be resolved to a variable
Indicates that you never declared the variable end. Make sure to have a line that is something like String end; before you use every variable.
Error: The method nextLine() in the type java.util.Scanner is not applicable for the arguments (int, int)
Indicates that nextLine() cannot take any parameters (see the javadocs). If you want to get a substring from the input, do something like wars.nextLine().substring(0,2). Additionally, both numbers must be positive (the -1 in your code will cause an ArrayOutOfBoundsException).
Use the below code and test it...
i did the testing also.
points of concern:
You did not declare some variables
you did not check method names in the Scanner API. please check java
doc for that.
please check and tell
import java.util.*;
public class NameGenerator {
static Scanner wars = new Scanner(System.in);
public static void main(String[] args) {
//Prompt for User's Name
String first, last, mother, city, car,Starwarsname,last1;
int end=0;
System.out.printf("Please state your First Name");
first = wars.nextLine();//wars.Line(0, 2);
System.out.printf("Please state your Last name");
last = wars.nextLine();
// last1 = wars.nextLine();
System.out.printf("Please state your mothers maiden name");
mother = wars.nextLine();
System.out.printf("Please state the city you were born in ");
city = wars.nextLine();
System.out.printf("Please state your first car");
car = wars.nextLine();
Starwarsname = first +" "+ last +" "+ mother +" "+ city + " of " + last +" "+ car;
System.out.println("In a galaxy far, far away you are known as " + Starwarsname +
" MAY THE FORCE be with you!");
}
}

Categories