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
Related
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.
So I'm very new to java and I'm trying to write a program that will print a correct fine for overdue books. I've read multiple questions like this and most of them involve misplacement of curly brackets, but I cannot find a bracket error anywhere. I keep getting multiple errors in my program, but most of the read "illegal start of type" or "illegal start of expression" Could someone help me with my code/give me some tips on bracket placement?
Here is my code:
public class BookFine
{
public static void main(String[] args)
{
int daysLate = 0;
int bookCost = 0;
int result = 0;
System.out.print("Enter how many days your book is overdue: ");
int daysLate = IO.readInt();
System.out.println("Days Late = " + daysLate);
System.out.print("How much does your book cost(enter in cents): ");
int bookCost = IO.readInt();
System.out.println("Book Cost = " + bookCost);
if (daysLate=<7)
{
result=daysLate*10;
}
else
if(daysLate>7)
{
result=(daysLate-7)*20+70;
}
if(daysLate>90)
{
result= bookCost+1000;
}
IO.outputStringAnswer(result);
}
}
There is an issue regarding declaring variable twice in the program. I have corrected the code. Please refer below code.
public class BookFine {
public static void main(String[] args)
{ int daysLate = 0;
int bookCost = 0;
int result = 0;
System.out.print("Enter how many days your book is overdue: ");
daysLate = IO.readInt();
System.out.println("Days Late = " + daysLate);
System.out.print("How much does your book cost(enter in cents): ");
bookCost = IO.readInt();
System.out.println("Book Cost = " + bookCost);
if (daysLate<=7)
{
result=daysLate*10;
}
else
if(daysLate>7)
{
result=(daysLate-7)*20+70;
}
if(daysLate>90)
{
result= bookCost+1000;
}
IO.outputStringAnswer(result);
}
}
You appear to have no brackets for your else branch
else
if(daysLate>7)
{
result=(daysLate-7)*20+70;
}
if(daysLate>90)
{
result= bookCost+1000;
}
Should be
else
{
if(daysLate>7)
{
result=(daysLate-7)*20+70;
}
if(daysLate>90)
{
result= bookCost+1000;
}
}
There were several errors in the code I was able to identify.
first the expression:
if(daysLate=<7)
is backwards. It should read
if(daysLate<=7)
Next, at the start of the code just under main you are declaring your variables "daysLate, bookCost". Then, after your line:
System.out.print("Enter how many days your book is overdue: ");
you are redeclaring the variables as:
int DaysLate
Remove the "int" portion on both daysLate and bookCost and it should run fine assuming you have an IO class defined somewhere.
There's a few problems here.
daysLate=<7; I assume that you mean to use the <= operator. Fixing this will resolve the specific error you're asking about
int daysLate = IO.readInt();; The problem with this line is that you've already declared a variable named 'daysLate'. This can be fixed in one of two ways: either remove the 'int' at the start of this line, or remove the original declaration on line 4. (I prefer the former.)
IO.readInt(); there is no class named IO, at least not in terms of what's imported by your code. There are a number of different ways that you can read input from the keyboard, however. If this is your intent (and it appears like it is), you might want to look up the documentation and examples for the java.util.Scanner class. I repeat, there are more than one ways to accomplish this, even if you don't want to use Scanner, so pick your poison :)
IO.outputStringAnswer(result); Same as #3, except that this time it looks like you're trying to output the result somewhere. Perhaps System.out.println() is in order here.
int bookCost = IO.readInt(); Same as #2 and #3. 'bookCost' is already defined in this scope, so you don't need to declare it again (remove 'int'). And again, you will need to write working keyboard input.
Finally--and this isn't an error per se--you should work on your Indent Style. It will greatly help your code readability, which will in turn help you write better code. Code that you and your colleagues enjoy reading is good (and hopefully healthy) code. Most developers these days use the 1TBF style, from my experience.
Oh, and Welcome to Java!
I am building a hangman game but I need help trying to check whether the user input was used before (like they guess a then b and than a again):
String input = console.next();
if(input.length()>1){
System.out.println("One letter at a time");
}
//to insert data into arrays
letter[a]=input;
if (!input.equalsIgnoreCase(input)) {
System.out.println("You have aready enter " + input);
} else {
continue;
}
This will add the method you want to use to the String class:
String.prototype.equalsIgnoreCase = function(other_string) {
return this.toLowerCase() === other_string.toLowerCase();
}
Make sure you're not trying to compare a String to itself, though, like you're doing with input in your question. Also, use JavaScript syntax for web-served files instead of C++ syntax.
newbie here
Is this the way to populate an ArrayList with objects(code below)? In the code below I've managed to read the information in the file of my choice and populate it with words. It appears in this format:
App name: Barcode Scanner
Developer name: WizardTech
Function: Scans bar-codes.
Type: Utility
Cost: 7.0
Popularity: 0
========================================================
I want to be able to get the attributes of the objects and use them like any other variable in the code. Is it possible to do this with the code I have right now?
For example, I've got an attribute named 'Cost' which belongs to the object and I want to get that attribute from the object in the ArrayList and use it for a calculation.
Here's the code:
public class c {
public static void wholeSystem3() {
boolean choice = true;
int input6 = 0;
Shop customerConfig = new Shop(new ArrayList<Customer>());
while (choice == true) {
System.out.println("Proceed to Customer creation by entering 1");
Scanner myScan1 = new Scanner(System.in);
input6 = myScan1.nextInt();
if (input6 == 1) {
System.out.println("Enter your information:");
Scanner myScan0 = new Scanner(System.in);
Customer myCustomer = new Customer();
System.out.println("Please enter your name:");
myCustomer.setCustomerName(myScan0.nextLine());
System.out.println("Please enter your address:");
myCustomer.setAddress(myScan0.nextLine());
System.out.println("Please enter your profession:");
myCustomer.setProfession(myScan0.nextLine());
System.out.println(myCustomer.getCustomerName() + " " + myCustomer.getAddress());
customerConfig.addCustomers(myCustomer);
File CustomerList = new File("CustomerList");
try {
BufferedWriter out;
out = new BufferedWriter(new FileWriter(CustomerList, true));
out.write("Customer name:" + myCustomer.getCustomerName());
out.newLine();
out.write("Customer Address:" + myCustomer.getAddress());
out.newLine();
out.write("Customer Profession:" + myCustomer.getProfession());
out.newLine();
//Close the output
out.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
System.out.println("Would you like to immediately purchase an app?");
input6 = myScan0.nextInt();
if (input6 == 1) {
String appStoreFile = "AppStore"; //"AppStore" Name of file I wish to take objects from to populate ArrayList
String line;
ArrayList testList = new ArrayList();
try {
BufferedReader input = new BufferedReader(new FileReader(appStoreFile));
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
testList.add(line);
}
input.close();
} catch (IOException b) {
System.out.println(b);
}
}
}
}
}
}
When you read the file line by line, you should parse it.
That means to turn it into a number.
Here's a link on how that works:
Convert string to float?
Pass the characters that come after "Cost:" to that method.
It should return a number that you can do calculations with.
Here's a simple program operating on one of your lines:
public class TextParser
{
public static void main(String[] args)
{
String line = "Cost: 7.0";
// this will not work, it tries to parse the whole line
//float number1 = Float.valueOf(line);
// this works and returns 7 as a number
float number2 = Float.valueOf(line.substring(6));
System.out.println("the number is: " + number2);
// you can now do calculations with it:
System.out.println(number2 + 5);
System.out.println(number2 * 12.345);
}
}
In the example, I hard coded the portion of the line that is representing a number. A better way to do this is to use regular expressions to filter out the parts of the String that could be a number. This is a lot more flexible but also a little complex and maybe a bit over the top for the beginning. But definitely look into RegEx, it is very useful.
you havent posted details about shop class but i assume that as there is customerConfig.addCustomers method, similarly there woule be customerConfig.getCustomers which you can use as follows. e.g. for first customer:
customerConfig.getCustomers().get(0).getCost();
As keyser pointed out, you posted too much code. However, from trying to discern from what you are trying to do, you are trying to add objects into your ArrayList, and then retrieve an attribute from a specific object within the ArrayList.
To add an object into the ArrayList, you can add by using the ArrayList's add method:
yourArrayListName.add(Object name);
or
yourArrayListName.add(int index, Object name);
Note that if you use the latter, you will need to keep track of whether the index you are trying to retrieve from is null or not. The former will simply add in order starting from index 0,1,2...
To retrieve the object within the ArrayList, you can use the ArrayList's get method:
yourArrayListName.get(int index).getAttribute(); // getAttribute retrieves the value you want
Note that I used a get method to get the value you wanted. It is bad programming practice to directly retrieve a value from an object. If you really wanted to, however, you can directly use the attribute variable name in place of getAttribute(), assuming it is declared public.
Here is the documentation:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html