Java static method can't compile - java

the following messege appears when I compile this code.
ExtractChars(java.lang.String,int) in
Question2 cannot be applied to ()
What should I fix?
Thanks.
import java.util.Scanner;
public class Question2
{
public static void main (String[] args)
{
ExtractChars();
}
public static String ExtractChars(String sOrg, int startPos)
{
Scanner scan = new Scanner (System.in);
String value = "";
System.out.print("Enter a string: ");
sOrg = scan.next();
System.out.print("/nEnter an integer: ");
startPos = scan.nextInt();
if (sOrg.length()<=startPos)
{
value = "";
}
else
{
for (int i=startPos; i<sOrg.length();i=i+2)
{
value = value + sOrg.charAt(i);
}
}
return value;
}
}

This is because the function ExtractChars expects two arguments but you are not passing any.
EDIT:
Looks like you are reading input sOrg and startPos and there is no need to pass them as arguments, you can make them local variables.
So change:
public static String ExtractChars(String sOrg, int startPos)
{
....
to
public static String ExtractChars()
{
String sOrg;
int startPos;
....
Also, you are just discarding the return value of the function ExtractChars in main. You might want to print the extracted characters returned by the function (as a string) as:
System.out.println("Extracted Characters = " + ExtractChars());
in your main in place of
ExtractChars();

You've defined your method to expect two arguments, but you're really using them as though they were local variables, prompting the user to enter values for them.
You should probably rewrite your method something like this
public static String ExtractChars()
{
String sOrg;
int startPos;
Scanner scan = new Scanner (System.in);
String value = "";
System.out.print("Enter a string: ");
sOrg = scan.next();
System.out.print("/nEnter an integer: ");
startPos = scan.nextInt();
if (sOrg.length()<=startPos)
{
value = "";
}
else
{
for (int i=startPos; i<sOrg.length();i=i+2)
{
value = value + sOrg.charAt(i);
}
}
return value;
}
so that sOrg and startPos are local variables in your method instead of arguments to it.
The method call as you have it will then compile.
You're also not doing anything with the return value of this function, so it may seem like nothing is happening. But this might get you on your way.

You have to use arguments when you call ExtractChars. ExtractChars wants a String and an int. When you call it, you're passing nothing.

its the arguments. You're calling a function which expects 2 arguments. The compiler generated message atlest points to that.

Related

How do I convert a String into doubles to compute average in Java?

I need help with an assignment. There are many similar questions on here, but those answers are not working for me so I don't know what I'm doing wrong.
The assignment is "The program prompts the user for five to ten numbers, all on one line, and separated by spaces. Then the program calculates the average of those numbers, and displays the numbers and their average to the user."
We need to call to different methods to do this. The part that's giving me problems is converting the String to doubles and finding the average. We also need to validate that there are between 5-10 numbers in the String (I can validate it once I get it to count properly). I've tried a few things, including answers to similar questions on here (shown in code below), but the only output I get is 0.0.
Here is my code:
public static void main(String[] args) {
String getNumbers = "";
double calcAverage = 0;
getNumbers();
calcAverage(getNumbers);
System.out.println(calcAverage);
}
public static String getNumbers() {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter 5 to 10 numbers separated by spaces: ");
String getNumbers = scnr.next();
return getNumbers;
}
public static double calcAverage(String userNumbers){
double calcAverage = 0.0;
double i = 0;
double count = 0.0;
Scanner str = new Scanner(userNumbers);
while (str.hasNextDouble()){
count++;
i = i + str.nextDouble();
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i/count;
return calcAverage;
}
Thank you so much for any help!
It seems you have an error in your main method and need to set the getNumbers equal to the getNumbers method and the same with the calcaverage double with the calcaverage method.
public static void main(String[] args) {
String getNumbers = "";
double calcAverage = 0;
getNumbers();
calcAverage(getNumbers);
System.out.println(calcAverage);
}
should be
public static void main(String[] args) {
String getNumbers = "";
double calcAverage = 0;
getNumbers =getNumbers();
calcAverage =calcAverage(getNumbers);
System.out.println(calcAverage);
}
You can use streams to make it more readable and avoid and external iterations
import static java.util.Arrays.stream;
import java.util.OptionalDouble;
class Scratch {
public static void main(String[] args) {
OptionalDouble optAvg = calcAverage("2 5 6 7 8 9 0 1");
if (optAvg.isPresent()) {
System.out.println("optAvg.getAsDouble() = " + optAvg.getAsDouble());
}
}
public static OptionalDouble calcAverage(String userNumbers) {
String[] inputArr = userNumbers.split(" ");
int count = inputArr.length;
System.out.println("count = " + count);
if (count < 5 || count > 10) {
throw new IllegalArgumentException("Or do some other this here!");
}
return stream(inputArr)
.mapToDouble(
Double::parseDouble) // throws a NumberFormatException if it can't convert to Double
.average();
}
}
Or even simpler
import static java.util.Arrays.stream;
import java.util.DoubleSummaryStatistics;
class Scratch {
public static void main(String[] args) {
DoubleSummaryStatistics doubleSummaryStatistics = calcAverage("2 5 6 7 8 9 0 1");
System.out.println("count = " + doubleSummaryStatistics.getCount());
System.out.println("average = " + doubleSummaryStatistics.getAverage());
}
public static DoubleSummaryStatistics calcAverage(String userNumbers) {
return stream(userNumbers.split(" "))
.mapToDouble(Double::parseDouble)
.summaryStatistics();
}
}
Here you go:
public static void main(String[] args) {
String numberString = getNumbers();
double averageNum = calcAverage(numberString);
System.out.println(averageNum);
}
public static String getNumbers() {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter 5 to 10 numbers separated by spaces: ");
String getNumbers = scnr.nextLine();
return getNumbers;
}
public static double calcAverage(String userNumbers){
double calcAverage = 0.0;
double i = 0;
double count = 0.0;
Scanner str = new Scanner(userNumbers);
while (str.hasNextDouble()){
count++;
i = i + str.nextDouble();
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i/count;
return calcAverage;
}
A few changes, but you had it right for the most part. Going from the top of the file:
Removed getNumbers and calcAverage
Added numberString and averageNum (when you call functions with return, you need to store the value that it returns into a variable)
changed line:
String getNumbers = scnr.next();
to:
String getNumbers = scnr.nextLine();
Let me know if you have any questions.
Here is one way to do it with supplied values validation :
public static double calcAverage(String userNumbers) {
double calcAverage = 0.0;
double i = 0;
int count = 0;
Scanner str = new Scanner(userNumbers.trim().replaceAll("\\s+", " "));
while (str.hasNext()) {
String val = str.next();
// Is the supplied numerical value valid?
if (!val.matches("-?\\d+(\\.\\d+)?")) {
//No...
System.out.println("Supplied value of " + val +
" is ignored since it is not a valid numerical value!");
continue;
}
count++; // count now that we know the value is indeed valid.
i += Double.parseDouble(val);
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i / count;
return calcAverage;
}
Since you are processing a supplied whitespace delimited string of hopefully numerical values you can merely utilize the the Scanner#hasNext() method in conjunction with the Scanner#next() method.
Preparing the Scanner object:
Scanner str = new Scanner(userNumbers.trim().replaceAll("\\s+", " "));
Here we take the string contained within the supplied userNumbers string variable and trim off any possible leading and trailing white-spaces, we don't want these if there are any. We also replace any portion of the supplied string that may contain more than a single whitespace with just a single whitespace. We want to enforce this format before we proceed so as to help with eliminating any possible type of conflict later on in method code. You can't always rely on the User to provide everything perfectly all the time so if you can help then it's worth it.
Retrieving each supplied value from the supplied String:
while (str.hasNext()) {
String val = str.next();
// ... other code ...
}
The hasNext() method will allow the loop to continue for as long as there is another whitespace delimited string token to process. In this case we're hoping that each token will be a string representation of a numerical value.
Because the hasNext() method has let us get this far into the loop we know there is another String token available. The str.next() call retrieves that available token and in this case, is placing that string token into the string variable named val. This is done upon each iteration of the while loop until there are no more tokens remaining to process.
Validating a retrieved string token:
if (!val.matches("-?\\d+(\\.\\d+)?")) { ... }
Validation of each string token is done here utilizing the String#matches() method along with a specific Regular Expression (regex) of "-?\\d+(\\.\\d+)?". When passed in the matches() method, this regex checks to see if the string it is played against is indeed a string representation of a signed or unsigned integer or floating point numerical value:
-? Optional. Value is prefixed with '-'.
\\d+ One or more digits.
(\\.\\d+)? Optional. Value is post-fixed with a decimal point
and one or more digits.
In this case we're checking to see if the token is invalid and if it is we supply a message to the console window indicating as such and the fact that this token value will be ignored. We ignore it by using the continue keyword which forces the while loop into it's next iteration and bypassing the remaining code within the loop.
Converting a String numerical value to a Double data type:
count++; // count now that we know the value is indeed valid.
i+= Double.parseDouble(val);
We do the count after knowing the value provided is indeed valid. i was previously declared as a double type and sums the token numerical value after it is converted to double with the Double.parseDouble() method. Using i += is the very same as i = i +.
Another shorter way:
public static double calcAverage(String userNumbers) {
double calcAverage = 0.0;
double i = 0;
int count = 0;
Scanner str = new Scanner(userNumbers.trim().replaceAll("\\s+", " "));
while (str.hasNextDouble()) {
double val = str.nextDouble();
count++;
i+= val;
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i / count;
return calcAverage;
}

Reverse and compare String

I have started to learn java and I've run into some trouble. Just wondering why my compare string function is not working and always returning true;
The purpose of the program is to take an input of a string, reverse the string and see if the string is the same as the original input (palindrome).
import java.util.Scanner;
public class palinedromeString {
private static Scanner keyboard;
public static void main(String[] args) {
System.out.println("Please enter a Palindrome");
keyboard = new Scanner(System.in);
String input = keyboard.next();
String original = input;
System.out.println("You entered: " + original);
System.out.println("Your String reversed is:" + " " + stringReverse(input));
System.out.println(checkString(input, original));
}
public static String stringReverse(String a) {
String result = "";
for(int i = a.length()-1; i>=0; i--){
result = result + a.charAt(i);
}
return result;
}
public static boolean checkString(String a, String b){
if(b.equals(a)){
return true;
}
else{
return false;
}
}
}
stringReverse returns the reversed String (it doesn't operate in place). Update input and your code should work as expected. Something like,
input = stringReverse(input);
System.out.println("Your String reversed is:" + " " + input);
Also, checkString is equivalent to
return b.equals(a);
Because you are passing input and original to the checkString() method. those two hold the same values. It's obvious you get true always.
checkString(stringReverse(input), original);
You have to use the above instead.
You have different options.
Assign the
stringReverse(input)
to a variable like
input=stringReverse(input);
before checking
Imesha Sudasingha's answer.
The thing is you are reversing the string into a different variable and it doesnot get reflected in the String you pass unless you explicitly assign it.
Here in checkString(input, original) method, both the parameter has same value, Hence it always returns true.
You have to pass original and reversed string like this:
String reversedStr = stringReverse(input);
checkString(reversedStr , original);

how to add an additional method to get word count and first word of a string

I'm still fairly new to Java and understanding the basics of everything, we just started talking about methods.
I'm having a hard time implementing this new method.. without using arrays or vectors or anything in the sort..
Any help would be greatly appreciated!
public class ClosedLab07{
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
String str = getInputString(keyboard);
int count = getWordCount(str);
System.out.println("Your string has " + (count+1) + " words in it.");
// Fill in the body with your code
}
// Given a Scanner, prompt the user for a String. If the user enters an empty
// String, report an error message and ask for a non-empty String. Return the
// String to the calling program.
private static String getInputString(Scanner inScanner) {
String str = "";
while (str.equals("")){
System.out.print("Enter a string: ");
str = inScanner.nextLine();
if (str.equals("")){
System.out.println("ERROR - string must not be empty.");
System.out.println();
}
}
return str;
// Fill in the body
// NOTE: Do not declare a Scanner in the body of this method.
}
// Given a String return the number of words in the String. A word is a sequence of
// characters with no spaces. Write this method so that the function call:
// int count = getWordCount("The quick brown fox jumped");
// results in count having a value of 5. You will call this method from the main method.
// For this assignment you may assume that
// words will be separated by exactly one space.
private static int getWordCount(String input) {
int i = 0;
int wordCount = 0;
while (i < input.length()){
char pos = input.charAt(i);
if (pos == ' '){
wordCount++;
}
i++;
}
return wordCount;
// Fill in the body
}
private static String getFirstWord(String input)
// THIS IS THE METHOD I'M WORKING ON
}
Add this line to your new method
return input.split("\\s")[0]; // split returns an array of all the words. you need just the first word

How to make my code accepts an input

I would just like to ask on how can I make my code to just get the input instead of declaring it? Here's my program. I want to input different atomic numbers and not just "37" like what's in my code. Don't mind my comments, it's in my native language. Thanks!
public class ElectConfi {
public static void main(String s[]) {
int atomicNumber = 37;
String electronConfiguration = getElectronConfiguration(atomicNumber);
System.out.println(electronConfiguration);
}
public static String getElectronConfiguration(int atomicNumber) {
int[] config = new int[20]; //dito nag store ng number of elec. in each of the 20
orbitals.
String[] orbitals = {"1s^", "2s^", "2p^", "3s^", "3p^", "4s^", "3d^", "4p^", "5s^",
"4d^", "5p^", "6s^", "4f^", "5d^", "6p^", "7s^", "5f^", "6d^", "7p^", "8s^"};
//Names of the orbitals
String result="";
for(int i=0;i<20;i++) //dito ung i represents the orbital and tapos ung j
represents ng electrons
{
for(int j=0;(getMax(i)>j)&&(atomicNumber>0);j++,atomicNumber--) //if atomic
number > 0 and ung orbital ay kaya pa magsupport ng more electrons, add
electron to orbital ie increment configuration by 1
{
config[i]+=1;
}
if(config[i]!=0) //d2 nagche-check to prevent it printing empty
orbitals
result+=orbitals[i]+config[i]+" "; //orbital name and configuration
correspond to each other
}
return result;
}
public static int getMax(int x) //returns the number of max. supported electrons by each
orbital. for eg. x=0 ie 1s supports 2 electrons
{
if(x==0||x==1||x==3||x==5||x==8||x==11||x==15||x==19)
return 2;
else if(x==2||x==4||x==7||x==10||x==14||x==18)
return 6;
else if(x==6||x==9||x==13||x==17)
return 10;
else
return 14;
}
}
You can use either a Scanner or BufferedReader and get the user input
Using Scanner
Scanner scanner = new Scanner(System.in);
System.out.println("Please input atomic number");
int atomicNumber = scanner.nextInt();
Using BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int atomicNumber = Integer.parseInt(reader.readLine());
public static String getElectronConfiguration(int atomicNumber) {}
This method accepting any int value and will return String result. so you only need to provide different number as input. There is no change required in this method.
How to provide different inputs?
You can use Scanner to do that.
Scanner scanner = new Scanner(System.in);
System.out.println("Please input atomic number");
int atomicNumber = scanner.nextInt();
Now call your method
String electronConfiguration = getElectronConfiguration(atomicNumber);
What are the other ways?
You can define set of values for atomicNumber in your code and you can run those in a loop
You can get input from command line arguments by doing below :
Scanner scanner = new Scanner(System.in);
String inputLine = scanner.nextLine(); //get entire line
//or
int inputInt= scanner.nextInt();//get an integer
Check java.util.Scaner api for more info - http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Hope this helps!
You can get the user input from a command line argument:
public static void main(String s[]) {
if (s.length == 0) {
// Print usage instructions
} else {
int atomicNumber = Integer.parseInt(s[0]);
// rest of program
}
}

ChatBot return bug

I'm working on a Chat Bot project, and I'm almost done, other than the fact that whenever I enter an input, it returns multiple outputs depending on the length of the input X.
Here is the source code:
import java.util.*;
public class ChatBot
{
public static String getResponse(String value)
{
Scanner input = new Scanner (System.in);
String X = longestWord(value);
if (value.contains("you"))
{
return "I'm not important. Let's talk about you instead.";
}
else if (X.length() <= 3)
{
return "Maybe we should move on. Is there anything else you would like to talk about?";
}
else if (X.length() == 4)
{
return "Tell me more about " + X;
}
else if (X.length() == 5)
{
return "Why do you think " + X + " is important?";
}
return "Now we are getting somewhere. How does " + X + " affect you the most?";
}
private static String longestWord(String value){
Scanner input = new Scanner (value);
String longest = new String();
"".equals(longest);
while (input.hasNext())
{
String temp = input.next();
if(temp.length() > longest.length())
{
longest = temp;
}
}
return longest;
}
}
This is for testing the Chat Bot:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.next();
}
}
}
I am also trying to modify the Bot so it counts the number of times it has responded; and also modify it so it randomly returns a random response depending on the length of the input. Any help will be much appreciated. Thank You!
You are using the Scanner.next method which only returns the next word in the string. So if you input a string with multiple words, your bot will respond to each of them.
You can use Scanner.nextLine() to get the entire input string, instead of only 1 word.
To count the number of times your bot has responded, you can create a field in the bot class:
private int responseCount = 0;
Then if you change yout getResponse method from a static method to an instance method, you can update this value from this method:
public String getResponse(String value)
{
String X = longestWord(value); //Your longestWord should also not be static.
this.responseCount++;
if (value.contains("you"))
{
...
Regarding counting the responses, just modify your main method:
import java.util.Scanner;
public class Test {
public static void main (String [ ] args)
{
int numberOfResponses = 1;
Scanner input = new Scanner (System.in);
ChatBot e = new ChatBot();
String prompt = "What would you like to talk about?";
System.out.println(prompt);
String userInput;
userInput = input.next();
while (!userInput.equals("Goodbye"))
{
System.out.println(e.getResponse(userInput));
userInput = input.nextLine();
numberOfResponses++;
}
input.close();
System.out.println(numberOfResponses);
}
}
If I have the time I will edit my post in a few minutes to check your problem regarding the double appearences of a response. You also forgot to close the Scanner.
EDIT: It actually happens because scanner has as a default the delimiter set to be on whitespace. so if you input a text with a whitespace, the while loop runs twice for one user input. Just use the nextLine() command.
Why is this code:
Scanner input = new Scanner (System.in);
In your getResponse method? Its not used at all. Take a closer look at your methods as they are holding some strange code.

Categories