so ive done coding before but for some reason i cant seem to figure this one out and i keep over thinking the solution. so to summarize, the first method is supposed to return 1 oys, the second method should return 3 oys, and the third methods needs to return 5 oys. i've linked an screen shot to the project, it isn't for school or anything like that, just a friend trying to reteach me java, and then eventually full stacks sql. i mainly have dealt with android. project
Based on my understanding, you need to build a string in the loopedOyMethod() and return it. You can do this by using a while loop or a for loop.
while loop:-
String s = "";
while (x>0)
{
s = s + "Oy" + " ";
x = x - 1;
}
return s;
For loop:-
String s = "";
for(int i=0;i<x;i++)
{
s = s + "Oy" + " ";
}
return s;
Related
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'm new to programming in Java.
I have written a method in one class and I'm trying to call it to my other class. I don't know how to call it, because my way gives a compilation error.
Here is my method in one class:
public static String checkWord(String [] input) {
int points = 0;
int words = 0;
String result = null;
for (int i = 0; i < input.length; i++) {
words++;
if (input[i].equalsIgnoreCase(ENGLISH[i])) {
points ++;
result = "Correct " + points + " of " + words + " words";
}
else if (input[i].compareToIgnoreCase(ENGLISH[i]) > (ENGLISH[i].length() / 2)) {
result = "Almost correct rätt. Correct answer was " + ENGLISH;
}
else {
result = "Wrong. " + points + " of " + words + " words";
}
}
return result;
}
And in the other class I'm trying to call it like this:
String input = scanner.next();
Words.checkWord(input);
But it doesn't work to write (input) only. What should i write to call my method?
The compilation error i get is:
'checkWord(java.lang.String[])' in 'wordhandler.Words' cannot be applied to '(java.lang.String)'
Very thankful for your help!
Your checkWord method takes a String array, while you only have a single string. To call that method, you must create a string array:
String[] array=new String[]{input};
and call the method with the new array: checkWord(array);
Alternatively, you could change the signature of checkWord to accept vararg parameters:
public static String checkWord(String... input) {
Vararg parameters are handled like arrays within the method, but you can call the method without wrapping the parameters in an array. In this case, your checkWord(input) call would be valid.
beginner here. I want to be able to ask the user a question. If the user's answer is empty or contains only spaces, it should print out an error, then go back to the unanswered question. Thus creating a loop until the question is answered. Please see code below:
do {
while(true) {
System.out.print("Dog's name: ");
String dogName = scan.nextLine().toLowerCase().trim();
if(dogName.isEmpty()) {
System.out.println("Error: This can't be empty.");
continue;
}
do {
while(true) {
System.out.print("Breed: ");
String breed = scan.nextLine().toLowerCase().trim();
if(breed.isEmpty()) {
System.out.println("Error: Breed can't be empty.");
continue;
}
This code works but it gets very repetitive and long. Is there a shorter and faster way of writing this? Thank you.
This is an ideal use case for a function. A function encapsulates a piece of code that you need multiple times and allows for both input via parameters and output via return types.
I suggest to read beginner tutorials of Java on how to use functions (also called methods in Java if they belong to a certain object, i.e. are not static).
Functions (also called procedures sometimes in other languages) are the basic building block of procedural programming, so I suggest you to learn about that topic as well.
In your specific case, that function could look like this:
String input(String label)
{
System.out.print(label+": ");
String s = scan.nextLine().toLowerCase().trim(); // assuming "scan" is defined in the enclosing class
if(s.isEmpty())
{
System.out.println("Error: "+label+" can't be empty.");
return input(label);
}
return s;
}
This is a recursive function but you can do it iteratively as well.
Create a method for the code which takes the question as a parameter,if the input is wrong you need to ask the same question, call the same method(recursion) with the same question.
pseudo code::
public void test(String s) {
System.out.print(s + ": ");
String input = scan.nextLine().toLowerCase().trim();
if(dogName.isEmpty()) {
System.out.println("Error: This can't be empty.");
test(s);
} else {
return input;
}
To read about recursion.
You can try something like this so you can have many questions but same amount code, this is to illustrate the idea, may not fully work
String questions[] = {"Dog's name: ","Breed: "};
for (int i = 0; i < questions.length; i++) {
System.out.print(questions[i]);
Scanner scan = new Scanner(System.in);
String answer = null;
while(!(answer = scan.nextLine()).isEmpty()) {
System.out.print("You answered: " + answer + "\n");
}
}
You can do this :
while ((dogName = scan.nextLine().toLowerCase().trim()).isEmpty()) {
System.out.println("Error: This can't be empty.");
}
// Use dogName not empty
while ((breed = scan.nextLine().toLowerCase().trim()).isEmpty()) {
System.out.println("Error: Breed can't be empty.");
}
// Use breed not empty
Best
I created an ArrayList of common passwords I retrieved from the internet and initialized an array called commonPasswords. I want to check to see if the user inputted password matches any of the passwords in the array. However, this does not seem to work. I have no idea why. Any help would be greatly appreciated.
I just started learning how to program, so I am quite a novice in the field. Thanks!
int commonpass = 0;
int check = 0;
while (commonpass == 0) {
if (password.equals(commonPasswords.get(check))) {
score = 0;
}
check++;
if (check >= commonPasswords.size()) {
commonpass++;
}
}
Use List#contains instead, like
if(commonPasswords.contains(password)){
System.out.println("Password is not safe");
}
Using Java 8 you can do it as below
List<String> commonPasswords = Arrays.asList("A", "B", "C");
return commonPasswords.stream().anyMatch(str -> str.equals(password));
As Chandler has said, you should use commonPasswords.contains(str) instead of password.equals(commonPasswords.get(check))
if commonPasswords.contains(password)
return true;
Or
return commonPasswords.contains(passwords);
Because you are beginner I wrote the following code for you demonstrating 4 possible very simple ways of doing what you desire.
Using Java 8 Stream API and Lambda expressions is not recommended to beginners.
List<String> commonPasswords = Arrays.asList("touraj", "ttt", "toraj", "123");
String userPassword = "123";
//First Way:
if (commonPasswords. contains(userPassword)) {
System.out.println("Password Found");
} else
{
System.out.println("Password Not Found");
}
//Second Way: foreach :: not suggested for beginners
for (String commonPassword : commonPasswords) {
if (commonPassword.equals(userPassword)) {
System.out.println("Password Found");
// here i use break after finding password to exit loop in order to not wasting cpu
break;
}
}
//Third Way: simple for loop :: suggested for beginners
for (int i = 0; i <commonPasswords.size() ; i++) {
if (commonPasswords.get(i).equals(userPassword)) {
System.out.println("Password Found");
}
}
//Forth way: Using Java 8 Stream Api :: Not Suggested for beginners like you
boolean isPassFound = commonPasswords.stream().anyMatch(pass -> pass.equals(userPassword));
if (isPassFound) {
System.out.println("Password Found.");
}
Note: In order to understand java 8 code I suggested here you firstly need to learn object oriented and interface and then learn anonymous methods then learn lambda expressions then learning Stream API...but I think hopefully java 8 version is self-explanatory and similar to human language somewhat.
The OP said he wants to check to see if the user inputted password matches so I assume they mean is identical to.
If indeed the OP is looking for identical entries the OP should use String.equals and not Array.contains. Because Array.contains could give him a false positive result.
private void checkPasswordExists(){
List<String> passwordList = Arrays.asList("pass1", "pass2", "pass12", "pass123");
int countContains = 0;
String userPassword = "pass1";
for(String password : passwordList){
if(password.contains(userPassword)){
countContains++;
}
}
int countEquals = 0;
for(String password : passwordList){
if(password.equals(userPassword)){
countEquals++;
}
}
System.out.println("Password countContains = " + countContains);
System.out.println("Password countEquals = " + countEquals);
}
The above code writes to the console:
Password countContains = 3
Password countEquals = 1
System.out.println("How many teams are in this tournament?");
no_of_teams=kb.nextInt();
for(int x=1; x<=no_of_teams; x+=1)
{
System.out.println("Please enter the name of team " + x);
team=kb.next();
}
I would like to have team contain all the user inputs, so I can then use String.split later on in the program to output the team names once again.
I asked my original question on Reddit but to no avail, it went like this:
We have been asked to create a program which runs to collect data
based on a round robin soccer tournament for 'n' no. of teams. My
issue is when I must ask for all the team names at the beginning
(which I must) based on what no. of teams the user inputs of course, I
can do this with a for loop and the output is perfect:
input the code from up above here
However, as I am sure you are aware, this
basically means that team will now just be stored as whichever team
name was entered last as the for loop caused it to be overwritten.
This is a problem because later down in the program you are meant to
then output all the different team names for when they are playing
against each other but team is only storing one team name. Using
team1, team2, team3, etc. is impractical because the user can enter an
infinite amount for the number of teams. We are not allowed to use
arrays because we have not covered them yet, and by all accounts the
way I am to get around this is to use String concatenation and while
loops, but I am unsure how this would apply. Any help would be
gratefully appreciated! Thanks.
You can just append names to a String with an attached delimiter:
StringBuilder team = new StringBuilder();
for(int x=1; x<=no_of_teams; x+=1)
{
System.out.println("Please enter the name of team " + x);
//this will add a - after each name, and then you could split on the - character
team.append(kb.next()).append("-");
}
However, this is really not the best options. I would use an array to store names. The answer I gave t would return one big string, that you would have to split on the '-'.
After you got your string, you could split it by doing:
team.toString().split("-");
If you wanted to output all the team names you would do something like:
for(String aTeam : team.toString().split("-")){
System.out.println("Team Name: " + aTeam);
}
Actually, it is possible! You do not have to use arrays or lists provided by java for your convenience, even implicitly like the split method BlackHatSamurai provided in his answer. It's simple - you implement your own ArrayList! Well, ArrayList-like thing anyway.
class MyStringStringList {
private static final char delimeter = '%'; //just a character not in the input
private String internalMemory = "";
public void add(String s) {
internalMemory += s + delimeter;
}
public String getAll() {
return internalMemory;
}
public String get(int index) {
int delimeterCount = 0;
StringBuilder currentWord = new StringBuilder();
for (int j = 0; j < internalMemory.length(); j++) {
if (internalMemory.charAt(j) == delimeter) {
if (delimeterCount == index) {
return currentWord.toString();
} else {
delimeterCount++;
currentWord = new StringBuilder();
}
} else {
currentWord.append(internalMemory.charAt(j));
}
}
throw new ArrayIndexOutOfBoundsException(index);
}
}
I moved this code to a new class for clarity, but you could just paste the insides into your main class and use it from there.
Some usage:
MyStringStringList list = new MyStringStringList();
for (int x = 1; x <= no_of_teams; x += 1) {
System.out.println("Please enter the name of team " + x);
list.add(kb.next());
}
for (int i = 0; i < no_of_teams; i++) {
System.out.println("Team number " + i+1 + ": " + list.get(i));
}
Do note, that only a crazy person would do that. Inefficient, probably buggy, incomplete feature-wise... But if you are not mistaken, and you were in fact prohibited from using the built-in array or collections that could be the "Your rules are stupid" solution your teacher deserves.
I'm trying to make a piece of code that will yell out anything I input.
So the command is 'yell'
I want to be able to type 'yell (whatever i want here)' and it will yell it out. I've managed to get this working with a help of a friend. But for some reason it will only yell the first word that's been output. So I can't type a sentence because it will only say the first word of a sentence.
Here's the piece of code, I hope you can help.
case "npcyell":
for (NPC n : World.getNPCs()) {
if (n != null && Utils.getDistance(player, n) < 9) {
String sentence = "";
for (int i = 1; i < cmd.length; i++) {
sentence = sentence + " " + cmd[i];
}
n.setNextForceTalk(new ForceTalk("[Alert] "
+ Utils.getFormatedMessage(sentence)));
}
}
return true;
Well I did something similar a while ago. You said that you wanted to be able to say "yell(text)" and have it output whatever the text was. I have a different way of implementing it than you do, but the general result is the same, but it can be adapted to however you are using it in this context. This is also assuming that you are running this program as a console project only. if not change the scanner with whatever you are using to input text into and replace the text assignment to text = textInputArea.getText().toString(); and change the output statement to System.out.println(text.getText().toString().substring(6,text.getText().toString().length() - 1));
Scanner s = new Scanner(System.in);
String text = s.nextLine();
if (text.startsWith("yell(") && text.endsWith(")")){
System.out.println(text.substring(6,text.length() - 1));
}
I hope this works for you. And I honestly hope that this is adaptable towards the program you are making.