Accumulate Strings in Loop and Print Out all of them - java

I am trying to figure out how to accumulate user inputs in for loop and then to print them out with one system.out.print. This is my test code for the problem.
So for example if a user type : Mike for his name and Joe,Jack,Dave for other names, how to print them all just having one variable because amount of variables are not known since a user has that decision. Also is it possible to do that without stringbuilder and without arrays?
import java.util.Scanner;
public class Accumulate {
public static void main(String[] args) {
String othernames = " ",name;
int count,n;
Scanner kybrd = new Scanner(System.in);
System.out.println("Enter your name ");
name = kybrd.nextLine();
System.out.println("How many other names would you like to add ? ");
count = kybrd.nextInt();
kybrd.nextLine();
for(n=0;n<count;++n){
System.out.println("Enter other names ");
othernames = kybrd.nextLine();
}
System.out.println("Other names are "+othernames + " And your name is "+ name);
}
}

You can call it recursively, for instance:
Scanner sc = new Scanner(System.in);
String s;
while(condition) {
s = s + sc.nextLine();
}
this will always concat the lines you enter, you can also add commas, or spaces, or whatever you want to add.

as for your question about using Objects other than StringBuilder you can use List<String> and build a string for it at the final step.
you can use Map<String, String> if you need more complex data structure.

Related

How to check if String contains values from an array

I am fairly new to Java and was trying to make a username check for profanities.
I have made an Array with 4 profanities and now I wanted to check the user's input for the bad words, however, I don't know how to form the if statement to check all items from the array.
public static void main(String[] args) {
Scanner character = new Scanner(System.in);
String[] profanities = {"asshole", "ass", "idiot", "stupid"};
System.out.println("What is your name");
String userName = character.next();
if (userName.contains(profanities[])) { //This Part is what i dont understand
System.out.println("Invalid name");
}
else {
System.out.println("Valid Name!");
}
}
Use a Set instead of an ArrayList and then profanities.contains(userName). Mind you, the user should have inputted the exact profanity as in the profanities Set, in order for the if statement to evaluate to true. If the user inputs something like 'userjackass', it will not be classed as profanity.
Without the need of creating further Collections, just your original array. As the set of invalid names would be previously set/known, the sort operation could only be performed once, when the program is started.
Once sorted, just call binarySearch on it for every input:
Arrays.sort(profanities); //--> if profanities is a static set, call this just once.
if (Arrays.binarySearch(profanities,username)>=0)
System.out.println("Invalid name");
else
System.out.println("Valid Name!");
//binarySearch will return >=0 if the value is found
This avoids the creation of sets, lists, or the implementation of loops.
If the set of invalid names may change (adding new ones, for example), this would require a second sort operation. In this scenario, the other answers provided would be a better approach. Use this method if the invalid names set is known and won't be altered during your program's execution.
I would do it like this..
import java.util.Scanner;
public class Profanities {
public static void main(String[] args) {
boolean allow = false;
Scanner scan = new Scanner(System.in);
String[] profanity_list = {"asshole", "ass", "idiot", "stupid"};
String test_input = "";
// do while until allow equals true..
while (!allow) {
System.out.println("What is your name?");
test_input = scan.nextLine();
byte memory = 0;
// compare the input with the elements of the array..
for (int pos = 0; pos < profanity_list.length; pos++) {
if (test_input.contains(profanity_list[pos]) == true) {
System.out.println("Invalid name. Let's start again..");
memory = 1;
break;
}
}
// if memory equals 1, it means that a profanity was found..
if(memory == 0){allow = true;}
}
String name = test_input;
System.out.println("That is a valid name. Thanks.");
}
}
Instead of using Array of String, use List of String from which you can easily use contains method. I modified you're code with List, refer below
public static void main(String[] args) {
Scanner character = new Scanner(System.in);
//String[] profanities = {"asshole", "ass", "idiot", "stupid"};
ArrayList<String> profanities = new ArrayList<String>();
profanities.add("asshole");
profanities.add("ass");
System.out.println("What is your name");
String userName = character.next();
if (profanities.contains(userName)) { //This Part is what i dont understand
System.out.println("Invalid name");
}
else {
System.out.println("Valid Name!");
}
}
One more advantage of using List is, it's dynamic, you can add elements to it in future without any issues
Try:
for(String string : profanities)
if(userName.contains(string))System.out.println("invalid name");
else System.out.println("valid name");
Note: the for loop iterates through every entry in the array and checks to see if the entry is contained within userName

How to make java scanner accept more than one string input?

Hello i'm currently a beginner in Java. The code below is a while loop that will keep executing until the user inputs something other than "yes". Is there a way to make the scanner accept more than one answer? E.g. yes,y,sure,test1,test2 etc.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ans = "yes";
while (ans.equals("yes"))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}
Use the or operator in your expression
while (ans.equals("yes") || ans.equals("sure") || ans.equals("test1"))
{
System.out.print("Test ");
ans = in.nextLine();
}
But if you are going to include many more options, it's better to provide a method that takes the input as argument, evaluates and returns True if the input is accepted.
Don't compare the user input against a value as loop condition?!
Respectively: change that loop condition to something like
while(! ans.trim().isEmpty()) {
In other words: keep looping while the user enters anything (so the loop stops when the user just hits enter).
You are looking for a method to check whether a given string is included in a List of string values. There are different ways to achieve this, one would be the use of the ArrayList contains() method to check whether your userinput in appears in a List of i.e. 'positive' answers you've defined.
Using ArrayList, your code could look like this:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<String> positiveAnswers = new ArrayList<String>();
positiveAnswers.add("yes");
positiveAnswers.add("sure");
positiveAnswers.add("y");
Scanner in = new Scanner(System.in);
String ans = "yes";
while (positiveAnswers.contains(ans))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}

How to split each input by a new line in Java?

I'm trying get 5 string inputs from the user and those inputs are going to be stored in an array. When I enter something like "Hello World" and hit a new line I can only enter 3 more words. So I want each user input to be a sentence and hitting enter should ask the user for another input on a new line.
Here is my code so far:
Scanner user_input = new Scanner(System.in);
String ask1 = user_input.next()+"\n";
String ask2 = user_input.next()+"\n";
String ask3 = user_input.next()+"\n";
String ask4 = user_input.next()+"\n";
String ask5 = user_input.next();
String[] cars = {ask1, ask2, ask3, ask4, ask5};
According to the documentation, Scanner.next():
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
As the default delimiter used by Scanner is whitespace, calling next() will get you individual words from user input. When you want to capture multiple words that end with a newline, you should use Scanner.nextLine() instead.
Additionally, you can remove code duplication (which you always should do, keeping things DRY) by creating the array beforehand and allocating the user input entries within a loop:
final int numberOfCars = 5;
Scanner userInput = new Scanner(System.in);
String[] cars = new String[numberOfCars];
for (int i = 0; i < numberOfCars; i++) {
cars[i] = userInput.nextLine();
}
I recommend that you have a certain keyword or phrase that the user can type which stops the program. Here, I made a simple program that uses the java.util.Scanner object to receive keyboard input. Each value is stored in a java.util.ArrayList called "inputs." When the user is done entering input, he/she will type "stop" and the program will stop.
import java.util.*; //you need this for ArrayList and Scanner
public class Input{
public static void main(String[] args){
Scanner user_input = new Scanner(System.in); //create a scanner object
ArrayList<String> inputs = new ArrayList<String>(); //I used a java.util.ArrayList simply because it is more flexible than an array
String temp = ""; //create a temporary string which will represent the current input string
while(!((temp = user_input.next()).equals("stop"))){ //set temp equal to the new input each iteration
inputs.add(temp); //add the temp string to the arraylist
}
}
}
If you want to convert the ArrayList to a normal String[], use this code:
String[] inputArray = new String[inputs.size];
for(int i = 0; i < inputs.size(); i++){
inputArray[i] = inputs.get(i);
}
You can make this more generic by storing your question on an array and looping through a for loop prompting for input until you have question. This why when you have more questions you can add them to list without changing anything else on the code.
Then, to answer your original question regarding creating a String array, you could use following method String[] a = answers.toArray(new String[answers.size()]);
import java.util.ArrayList;
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
ArrayList<String> questions = new ArrayList<String>(5){{
add("What is your name?");
add("What is school you went to?");
add("Do you like dogs?");
add("What is pats name?");
add("Are you batman?");
}};
ArrayList<String> answers = new ArrayList<String>(questions.size()); // initialize answers with the same size as question array
String input = ""; // Stores user input here
Scanner scanner = new Scanner(System.in);
for(String question : questions){
System.out.println(question); // Here we adding a new line and the user type his answer on a new line
input = scanner.nextLine();
answers.add(input); // Store the answer on answers array
}
System.out.println("Thank you.");
String[] a = answers.toArray(new String[answers.size()]); // THis converts ArrayList to String[]
System.out.println("You entered: " + a.toString());
}
}
You want this instead:
Scanner user_input = new Scanner(System.in);
String ask1 = user_input.nextLine()+"\n";
String ask2 = user_input.nextLine()+"\n";
String ask3 = user_input.nextLine()+"\n";
String ask4 = user_input.nextLine()+"\n";
String ask5 = user_input.nextLine();
String[] cars = {ask1, ask2, ask3, ask4, ask5};

How to match user input with arraylist

package BankingSystem;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Bank {
public static void main(String [] args){
List<String> AccountList = new ArrayList<String>();
AccountList.add("45678690");
Scanner AccountInput = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
AccountInput.nextLine();
for (int counter = 0; counter < AccountList.size(); counter++){
if (AccountInput.equals(AccountList.get(counter))){ //If Input = ArrayList number then display "hi"
System.out.println("Hi");
}
else { //If not = to ArrayList then display "Incorrect"
System.out.println("Incorrect");
}
}
}
}
Hi, in here I am trying to match the userInput to arrayList, if its correct then display "hi" if not display "Incorrect", for the incorrect part do I to use exception handling? and how can I get it to match the ArrayList number - 45678690?
.nextLine() returns a string which needs to be assigned to a variable ....
And then compare the variable with elements in the arraylist using .contains() method ...
If you also want the index position use .indexOf() method ...
String input = AccountInput.nextLine();
if(AccountList.contains(input))
// do something
else
// do something else
First things first you need to store your user's input into some string as you currently aren't doing that.
Instead of using a counter and iterating through your list you can instead just use
AccountList.contains(the string variable assigned to AccountInput)
If it's false then the entry isn't there, otherwise it's in there. The exception handling you might want to use in this scenario would be to handle a user inputting letters instead of numbers.
You have to store the input value in a string to check the number :
String value = AccountInput.nextLine();
if (value.equals(AccountList.get(counter))) ...
Start variables with lower case. Names that start with upper case is for Classes only in java. So use List<String> accountList , and not List<String> AccountList .
The main problem in your code is that you are comparing the elements in list with the Scanner-object. And that will always be false.
You also never store the input from the Scanner any place.
You need to place the return value somewhere, like
String input = scanner.nextLine();
and compare the strings in the list to this string, not the Scanner-object.
I've added a flag so that it works correctly with multiple items in the accountList.
List<String> accountList = new ArrayList<String>();
accountList.add("45678690");
accountList.add("1");
accountList.add("0");
Scanner scanner = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
String accountInput = scanner.nextLine();
boolean listContainsInput = false;
for (int counter = 0; counter < accountList.size(); counter++){
if (accountInput.equals(accountList.get(counter))){
listContainsInput = true;
break;
}
}
if(listContainsInput) {
System.out.println("Hi");
} else {
System.out.println("Incorrect");
}
You are comparing the instance of the Class Scanner
Scanner AccountInput = new Scanner(System.in);
To a String:
AccountInput.equals(AccountList.get(counter))
(ArrayList.get(int) returns a String or fires an Exception)
You need to start with comparing String to String first:
AccountInput.nextLine().equals(AccountList.get(counter))
If you need additional debbuging see how both strings look like(e.q. print 'em)
Here is documentation on Scanner:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Read it, scanner is important thing in programming languages.

InputMismatchException while reading two lines correctly?

I'm reading in two lines of a .txt file (ui.UIAuxiliaryMethods; is used for this) to calculate the BodyMassIndex(BMI) of patients, but I get a inputmismatchexception when the patientLenght is reached. These are my two lines of input, seperated by a \t:
Daan Jansen M 1.78 83
Sophie Mulder V 1.69 60
It's sorted in Name - Sex - Length - Weight. This is my code to save all elements in strings, doubles and integers:
package practicum5;
import java.util.Scanner;
import java.io.PrintStream;
import ui.UIAuxiliaryMethods;
public class BodyMassIndex {
PrintStream out;
BodyMassIndex() {
out = new PrintStream(System.out);
UIAuxiliaryMethods.askUserForInput();
}
void start() {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
String lineDevider = in.nextLine(); //Saves each line in a string
Scanner lineScanner = new Scanner(lineDevider);
lineScanner.useDelimiter("\t");
while(lineScanner.hasNext()) {
String patientNames = lineScanner.next();
String patientSex = lineScanner.next();
double patientLength = lineScanner.nextDouble();
int patientWeight = lineScanner.nextInt();
}
}
in.close();
}
public static void main(String[] args) {
new BodyMassIndex().start();
}
}
Somebody got a solution for this?
Your name has two tokens not one, so lineScanner.next() will only get the token for the first name.
Since a name can have more than 2 tokens theoretically, consider using String.split(...) instead and then parsing the last two tokens as numbers, double and int respectively, the third from last token for sex, and the remaining tokens for the name.
One other problem is that you're not closing your lineScanner object when you're done using it, and so if you continue to use this object, don't forget to release its resource when done.
Your name field has two token. and you are trying to treat them as one. that;s creating the problem.
You may use a " (double quote) to separate the name value from others. String tokenizer may do your work.
I changed the dots to commas in the input file. Hooray.

Categories

Resources