I'm looking for a way to basically give back to the user some console output that looks identical to what they type and then prompt again for more input. The problem is I have a method that modifies each String discovered that does not consist of white space.
At the end of each sentence given by the user, I am trying to figure out a way to get a newline to occur and then for the prompt to output to the console again saying "Please type in a sentence: ". Here is what I have so far...
System.out.print("Please type in a sentence: ");
while(in.hasNext()) {
strInput = in.next();
System.out.print(scramble(strInput) + " ");
if(strInput.equals("q")) {
System.out.println("Exiting program... ");
break;
}
}
Here is what is displaying as console output:
Please type in a sentence: Hello this is a test
Hello tihs is a tset
And the cursor stops on the same line as "tset" in the above example.
What I want to happen is:
Please type in a sentence: Hello this is a test
Hello tihs is a tset
Please type in a sentence:
With the cursor appearing on the same line as and directly after "sentence:"
Hopefully that helps clear up my question.
Try this, I didn't test it but it should do what you want. Comments in the code explain each line I added:
while (true) {
System.out.print("Please type in a sentence: ");
String input = in.nextLine(); //get the input
if (input.equals("quit")) {
System.out.println("Exiting program... ");
break;
}
String[] inputLineWords = input.split(" "); //split the string into an array of words
for (String word : inputLineWords) { //for each word
System.out.print(scramble(word) + " "); //print the scramble followed by a space
}
System.out.println(); //after printing the whole line, go to a new line
}
How about the following?
while (true) {
System.out.print("Please type in a sentence: ");
while (in.hasNext()) {
strInput = in.next();
if (strInput.equals("q")) {
System.out.println("Exiting program... ");
break;
}
System.out.println(scramble(strInput) + " ");
}
break;
}
The changes are:
You should be printing "Please type in a sentence: " inside a loop to have it print again.
I think you want to check if the strInput is "q" and exit BEFORE printing it, i.e. no need to print the "q", or is there?
Use println to print the scrambled strInput so that the next "Please type in a sentence: " appears in the next line, and the cursor appears on the same line as " ... sentence: " because that is output by System.out.print (no ln)
Related
I'm trying to separate the input from the console using the split method, and then putting each of these values into separate containers, and I keep on getting this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1. I assume the issue is that it ignores the input after the first space, but I am clueless as to why and how to solve that.
Could someone tell me what I'm doing wrong and advise what I should do so that the text after the space is stored in my container? Thank you in advance.
Scanner s = new Scanner(System.in);
System.out.println("Input the name and phone no: ");
String text = s.next();
String[] temp = text.split(" ");
String name = temp[0];
String phoneNoTemp = temp[1];
System.out.println(name + ": name");
System.out.println(phoneNoTemp + ": phoneNoTemp");
The input I tried it with was:
Input the name and phone no:
kate 99912222
Sidenote: Yes, I did import the scanner
Try to use s.nextLine() instead of s.next() because the next() method only consumes until the next delimiter, which defaults to any whitespace.
I am working through a piece of self study, Essentially I am to ask the User for a string input such as "John, Doe" IF the string doesnt have a comma, I am to display an error, and prompt the user until the string does indeed have a comma (Fixed.). Once this is achieved I need to parse the string from the comma, and any combination of comma that can occur (i.e. John, doe or John , doe or John ,doe) then using the Scanner class I need to grab John doe, and split them up to be separately printed later.
So far I know how to use the scanner class to grab certain amounts of string up to a whitespace, however what I want is to grab the "," but I haven't found a way to do this yet, I figured using the .next(pattern) of the scanner class would be what I need, as the way it was written should do exactly that. however im getting an exception InputMismatchException doing so.
Here is the code im working with:
while (!userInput.contains(",")) {
System.out.print("Enter a string seperated by a comma: ");
userInput = scnr.nextLine();
if (!userInput.contains(",")) {
System.out.println("Error, no comma present");
}
else {
String string1;
String string2;
Scanner inSS = new Scanner(userInput);
String commaHold;
commaHold = inSS. //FIXME this is where the problem is
string1 = inSS.next();
string2 = inSS.next();
System.out.println(string1 + " " + string2);
}
}
This can be achieved simply by splitting and checking that the result is an array of two Strings
String input = scnr.nextLine();
String [] names = input.split (",");
while (names.length != 2) {
System.out.println ("Enter with one comma");
input = scnr.nextLine();
names = input.split (",");
}
// now you can use names[0] and names[1]
edit
As you can see the code for inputting the data is duplicated and so could be refactored
I am using the scanner in java and am trying to enter a space in my input for option 2 (removing a user from my hashmap) but when I add a space in my answer I get an InputMismatchException. while researching I came across this thread Scanner Class InputMismatchException and Warnings that says to use this line of code to solve the issue: .useDelimiter(System.getProperty("line.separator")); i have added this and now my option 2 goes into a never-ending loop of me inputting data. Here is my code:
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
AddressBook ad1 = new AddressBook();
String firstName="";
String lastName="";
String key="";
int choice=0;
do{
System.out.println("********************************************************************************");
System.out.println("Welcome to the Address book. Please pick from the options below.\n");
System.out.println("1.Add user \n2.Remove user \n3.Edit user \n4.List Contact \n5.Sort contacts \n6.Exit");
System.out.print("Please enter a choice: ");
choice = scan.nextInt();
if(choice==1){
//Add user
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
Address address = new Address();
key = lastName.concat(firstName);
Person person = new Person(firstName,lastName);
ad1.addContact(key,person);
System.out.println("key: " + key);
}
else if(choice==2){
//Remove user
System.out.println("Please enter name of user to remove: ");
scan.useDelimiter(System.getProperty("line.separator"));
key=scan.next();
System.out.println("name:" + key);
ad1.removeContact(key);
}
else if(choice==3){
//Edit user
}
else if(choice==4){
//List contact
ad1.listAllContacts();
}
else if(choice==5){
//Sort contacts
}
}while(choice!=6);
}
}
The reason why I need to use a space is to remove a user from my hashmap I need to enter their full name as the key is a concatenation of their last and firstname, any help will be appreciated
nextInt() behaves similar to next() that is when it read a line it places the cursor behind it.
Example:
You give 6 as input
6
^(scanner's cursor)
So next time when you call nextLine(). It will return the whole line after that cursor which is empty in this case.
To fix this issue you need to call an extra nextLine() so that the Scanner closes the previous line it was reading and move on to the next line.
You could do this
System.out.print("Please enter a choice: ");
choice = scan.nextInt(); // Reads the int
scan.nextLine(); // Discards the line
And in choice 2 since you want full name of user you could just use nextLine() to get whole line along with space.
//Remove user
System.out.println("Please enter full name of user to remove: ");
key=scan.nextLine();
System.out.println("name:" + key);
ad1.removeContact(key);
Or you could do something similar to what you did in choice 1
System.out.print("Please enter firstname: ");
firstName=scan.next();
System.out.print("Please enter lastname: ");
lastName=scan.next();
key = lastName.concat(firstName);
System.out.println("name:" + key);
ad1.removeContact(key);
scan.nextLine(); // This is will make sure that in you next loop `nextInt()` won't give an input mismatch exception
So I am trying to make the program ask the user the following and get the following answer:
For example:
Type a 2nd Sentence Below:
This is a book (user inputs this)
Choose what string of characters do you want to replace:
book (user inputs this)
Choose what new string will be used in the replacement:
car (user inputs this)
The text after the replacement is: This is a car.
import java.util.*;
import java.util.Scanner;
public class StringManipulation {
public static void main(String[]args) {
/*This is where the user can type a second sentence*/
System.out.println("Type a 2nd Sentence Below:");
Scanner sd = new Scanner(System.in);
String typingtwo = sd.nextLine();
String sending;
/*Here the program will tell the user a message*/
System.out.println("This is your sentence in capital letters:");
sending = typingtwo.toUpperCase();
System.out.println(sending);
/*Here the program will tell the user another message*/
System.out.println("This is your sentence in lower letters:");
sending = typingtwo.toLowerCase();
System.out.println(sending);
System.out.print("Your Token Count:");
int FrequencyTwo = new StringTokenizer(sending, " ").countTokens();
System.out.println(FrequencyTwo);
String charactertwo = new String(typingtwo);
System.out.print("Your Character Length:");
System.out.println(charactertwo.length());
String repWords;
String newWord;
String nwords;
String twords;
System.out.println("Choose what string of characters do you want to
replace");
repWords = sd.next();
System.out.println("Choose what new string will be used in the replacement");
nwords = sc.next();
twords = typingtwo.replace(repWords,nwords);
System.out.printf("The text after the replacement is: %s \n",nwords);
}
}
I have tried everything but for some reason I keep getting the word that they chose at the end only. Pleas help!
try using Scanner.nextLine instead of Scanner.next
refer to the Java API documentation to understand the difference between the two
Here is another problem:
twords = typingtwo.replace(repWords,nwords);
System.out.printf("The text after the replacement is: %s \n",nwords);
You are printing nwords instead of twords.
Two errors i could see.
nwords = sc.next(); here it should give compilation error as scanner instance name is sd.
You are trying to print nwords at the end. it should be "twords".
Im having an issue with my Java application. The application is required to do the following:
(1) Prompt the user for a string that contains two strings separated by a comma. (1 pt)
Examples of strings that can be accepted:
Jill, Allen
Jill , Allen
Jill,Allen
Ex:
Enter input string: Jill, Allen
(2) Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings. (2 pts)
Ex:
Enter input string: Jill Allen
Error: No comma in string
Enter input string: Jill, Allen
(3) Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings. (2 pts)
Ex:
Enter input string: Jill, Allen
First word: Jill
Second word: Allen
(4) Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit. (2 pts)
Ex:
Enter input string: Jill, Allen
First word: Jill
Second word: Allen
Enter input string: Golden , Monkey
First word: Golden
Second word: Monkey
Enter input string: Washington,DC
First word: Washington
Second word: DC
Enter input string: q
My Code:
package parsestrings;
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Input stream for standard input
Scanner inSS = null; // Input string stream
String lineString = ""; // Holds line of text
String firstWord = ""; // First name
String secondWord = ""; // Last name
boolean inputDone = false; // Flag to indicate next iteration
// Prompt user for input
System.out.println("Enter input string: ");
// Grab data as long as "Exit" is not entered
while (!inputDone) {
// Entire line into lineString
lineString = scnr.next();
// Create new input string stream
inSS = new Scanner(lineString);
// Now process the line
firstWord = inSS.next();
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Exiting.");
inputDone = true;
if (firstWord.matches("[a-zA-Z]+,[a-zA-Z]+")) {
System.out.print("Input not two comma separated words");
}
} else {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
}
}
return;
}
}
The error Im getting returned:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at parsestrings.ParseStrings.main(ParseStrings.java:53)
Java Result: 1
Scanner.next doc says:
Throws: NoSuchElementException - if no more tokens are available
Reason for your exception:
lineString = scnr.next(); // this is reading just one word (token)
//...
inSS = new Scanner(lineString); // this creates a new scanner with a string consisting in just one word
firstWord = inSS.next(); // this reads the word loaded in the inSS scanner
//...
secondWord = inSS.next(); // here is the problem. There are no more words left in this scanner (tokens) and throws the exception.
So It would work if you change this line:
lineString = scnr.next();
with this:
lineString = scnr.nextLine();
Scanner.nextLine will read the entire line as you are expecting. Anyway the user can input one word. So it would be nice to validate the input before proceding. You can do it like this:
lineString = scnr.nextLine();
if(lineString == null || lineString.length() == 0 || lineString.split("\\s+").length < 2){
System.out.println("2 words required. Try again:");
continue;
}
Here I'm using a regular expression to validate that there is more than one word in the input.