Java: How do I make my program print without two extra dots? - java

This program needs to print a.b.c. but it prints a.b.c...
How do I eliminate the last dot in output.
The program has to work with user ending loop with "."
import java.util.Scanner;
public class dots1 {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String input;
String output = "";
System.out.println("Hello! I print out an acronym. ");
do {
System.out.println("Please Enter a Character");
input = s.nextLine();
output = output+input+".";
} while (!input.equals("."));
System.out.println(output);
}
}

Because your exit condition is "." and you add it to output and add another dot. Try following:
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String input = "";
String output = "";
System.out.println("Hello! I print out an acronym. ");
while (true) {
System.out.println("Please Enter a Character");
input = s.nextLine();
if(input.equals("."))
break;
output = output + input + ".";
} ;
System.out.println(output);
}

I use a little trick using a simple check to see if its not the first read.
boolean isFirst=true;
do{
System.out.println("Please Enter a Character");
input = s.nextLine();
if(!isFirst) output="."+output;
isFirst=false;
output = output+input;
}while(!input.equals("."));

Instead of the do... while, you should use the the while function.
while (!input.equals(".") {
}

You have to use substring function in java and remove the last character of the String.
your loop end while you enter a dot in input.
Example given below.
Try this
import java.util.Scanner;
public class dots1 {
Scanner s = new Scanner(System.in);
String input;
String output = "";
System.out.println("Hello! I print out an acronym. ");
do{
System.out.println("Please Enter a Character");
input = s.nextLine();
output = output+input+".";
}while(!input.contains("."));
System.out.println(output.substring(0, output.length() - 2));
}
}
Output of Single Input
output of Multiple Inputs

Related

homework parsing strings: removing comma from string (java zybooks)

I am trying to get the strings to separate, and WITHOUT the comma.
We haven't learned anything like arrays, this is an intro class.
Everything I find on here just keeps giving me errors or does nothing to my code in zybooks.
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.nextLine();
inSS = new Scanner(lineString);
firstWord = inSS.next();
lineString.split(",");
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Enter input string: ");
inputDone = true;
}
//This may be where I am messing up??
else if (lineString.contains(",")) {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
} else {
System.out.println("Error: No comma in string");
System.out.println("Enter input string: ");
}
}
return;
}
}
I am messing up somewhere and keep getting different error codes as I keep messing with it...
"Enter input string:
First word: Jill,
Second word: Allen"
When it should be
"Enter input string:
First word: Jill
Second word: Allen"
And then also as the computer enters more data I start getting this message:
"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.main(ParseStrings.java:44)"
One of the possibilities (if you didn't learn about arrays) is to use StringBuilder and remove commas or simply loop over input string and if character at let's say index 8 is comma, you do yourString.substring(0,8);, and then print the second word as yourString.substring(10, yourstring.length); I put starting index of 10 in the second substring because you want to skip comma and a space that's separating first and last name. Here is code sample for using nothing but String class, it's methods and for loop:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String str = in.nextLine();
int indexOfComma = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',')
indexOfComma = i;
}
System.out.println("First name is: " + (str.substring(0, indexOfComma)));
System.out.println("Last name is: " + (str.substring(indexOfComma + 2, str.length())));
}
}
Or as I see you tried using split() (but since you said you didn't learn arrays yet I posted solution above), you can do it with .split() like this:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String[] name = in.nextLine().split(", ");
System.out.println("First name is: " + name[0]);
System.out.println("Last name is: " + name[1]);
}
}
Also, here is an example with StringBuilder class:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
StringBuilder name = new StringBuilder(in.nextLine());
name.deleteCharAt(name.indexOf(","));
System.out.println("Full name is: " + name);
}
}
Your error happens when the Scanner reads all the data, such as calling the nextLine method and there's no line... Or next method when you didn't put a space after the comma
By default, the Scanner uses whitespace as a delimiter. If you want to add a comma delimiter before any whitespace, you can try this
Scanner sc=new Scanner(System.in);
sc.useDelimiter(",?\\s+");
Now, sc.next() will read only Hello from Hello, World, and a second call to it should return World
Or you can use the array you made
String[] words = lineString.split(",");
String first = words[0]:
String second = words[1];

How to accept enter as valid input to Scanner.nextLine()?

I just want the scanner to read new line as empty string then continue to next process if the user press enter. So valid input must be y,n,enter. Any idea how to do this?
This is my code:
String gender = "", employed = "";
Scanner in = new Scanner(System.in);
System.out.print("Gender M/F, press enter to skip... ");
while(!in.hasNext("[mfMF]$")){
System.out.print("Invalid, please choose m/f only... ");
in.nextLine();
}
if(in.hasNextLine()){
gender = in.nextLine();
}
System.out.print("Employed? y/n, press enter to skip... ");
while(!in.hasNext("[ynYN]$|")){
System.out.print("Invalid, please choose y/n only... ");
in.nextLine();
}
if(in.hasNextLine()){
employed = in.nextLine();
}
System.out.println(gender + " : " + employed);
Try This :
import java.util.*;
class Scanner1
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s;
do
{
s=sc.nextLine();
if(!(s.equalsIgnoreCase("y")||s.equalsIgnoreCase("n")||s.equalsIgnoreCase("")))
{
System.out.println("Please Enter valid input");
}
}while(!(s.equalsIgnoreCase("y")||s.equalsIgnoreCase("n")||s.equalsIgnoreCase("")));
}
}
So, to check if the user has pressed enter, you would have to make use of the isEmpty() method. The way to do that is shown below:
String enter = in.nextLine();
if (enter.isEmpty()) {
// do what is needed
}

ReplaceAll with string builder with user input

I have a question regarding StringBuilder. I'm trying to write a program that takes the user input : for example "DOG DOG CAT DOG DOGCAT", then asks the user to input a word they would like to change and what they would like to change it to. It should then replace all occurrences and print the result.
I have a code:
public class ChangeSentence
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
String text = sc.nextLine();
StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String rep = sc.nextLine();
System.out.println("For what do you want to change it: ");
String change = sc.nextLine();
System.out.println(Pattern.compile(x.toString()).matcher(rep).replaceAll(change));
}
}
How should I change it to achieve the result?
Thanks!
**Forgot to mention, I need to use the StringBuilder (without it i know how to write it).
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
original = sc.nextLine();
//StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String replacableWord = sc.nextLine();
System.out.println("For what do you want to change it: ");
String newWord = sc.nextLine();
String output = original.replace(replacableWord ,newWord);
System.out.println(output);
}
You just use the function replace on the original String and the
first parameter is the target String
the
second parameter is the replacement String
Last line should be replaced by following:
System.out.println(text.replaceAll(rep, change));
It's simple. You have to excercise a little

Remove comma from end of String, using While loop

I get an extra comma on the end of my string after the user inputs their text. How do I get rid of the last comma? The good old fence post problem, but I'm stuck on the fence.
import java.util.Scanner;
public class fencepost {
public static void main(String[] args) {
System.out.print("Enter a line of text: ");
Scanner console = new Scanner(System.in);
String input = console.nextLine();
System.out.print("You entered the words: ");
Scanner linescanner = new Scanner(input);
while (linescanner.hasNext()) {
System.out.print(linescanner.next());
System.out.print(", ");
}
}
}
I get as output "hello, there," with an extra comma after there.
Add an if statement inside your loop to determine if there's still a next line, if so, then add a comma, otherwise, don't add one:
while (linescanner.hasNext()) {
System.out.print(linescanner.next());
if (linescanner.hasNext()) {
System.out.print(", ");
}
}

Concatenate User Input JAVA

This is what I have so far. I want the program to print out the words the user inputs as a sentence. But
I don't know how I get that to happen with the code I have written so far.
ex: if you entered
Hello
World
done
The program should say: "Hello World"
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+word);
}
}
What you need it to store it in a variable which is declared outside the loop.
StringBuilder sentence=new StringBuilder();
do {
word = in.nextLine();
count++;
System.out.print(" "+word);
sentence.append(" "+word);
}
while (!word.equals(SENTINEL));
Then for printing use
System.out.println(sentence.toString());
You will need to create an additional string to "collect" all of the words that the user enters. The problem with your original is that you replace 'word' with the word entered. This should do the trick:
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
String sentence = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
sentence += " " + word;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+sentence);
}
}
You can read it by pieces and put them together using a StringBuffer - http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
StringBuffer sb = new StringBuffer();
do {
sb.append( in.next() );
count++;
}
while (!word.equals(SENTINEL));

Categories

Resources