How do i make the loop stop repeating in java - java

I'm a beginner in Java and I have to write a program that allows the user to enter in words, then the program returns the word backwards until the user writes "stop". Every time the user enters a word, java outputs it backwards plus the previous word which is outputted and I don't want that.
For example, if I put input pots
it outputs, stop
if I print cat
it outputs potstac
How can I just get java to just output the words backwards without adding it on to the prior words
For example, i want to input in pots
it should output, stop
i want to print cat
it should output, tac
import java.util.*;
public class javapdf2413 {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
String wordEntered = "";
String backWords = "";
do {
System.out.println("Enter in a word");
wordEntered = in.next();
for (int i = wordEntered.length()-1; i>=0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
}while(!wordEntered.equals("stop"));
}
}

You'll need to set backWords back to an empty string at the beginning of the do loop. If you don't it will just concatenate onto the end of the previous string - which is what you said is happening. Setting it back to "" at the beginning of the loop body will essentially "reset" it for the next word.
Like this:
do {
backWords = "";
System.out.println("Enter in a word");
wordEntered = in.next();
for (int i = wordEntered.length()-1; i>=0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
}while(!wordEntered.equals("stop"));

Try to do this with while loop
import java.util.Scanner;
public class TestRun {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String wordEntered = "";
String backWords = "";
while (true) {
System.out.println("Enter in a word");
wordEntered = in.next();
if (wordEntered.equals("stop")) {
break;
} else {
for (int i = wordEntered.length() - 1; i >= 0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
backWords = "" ;
}
}
}
}

Just initialize your variables inside your do loop
String wordEntered;
String backWords;
do {
wordEntered = "";
backWords = "";
System.out.println("Enter in a word");
wordEntered = in.next();
for (int i = wordEntered.length()-1; i>=0; i--) {
backWords = backWords + wordEntered.charAt(i);
}
System.out.println(backWords);
}while(!wordEntered.equals("stop"));

Just beware - Strings are immutable objects. Use it with right use case and approach. Try to use StringBuilder for non concurrent code as much as possible where ever you can.

Related

Java - make sure each letter does not contain a number

Very new to programming, just starting a Java class.
Here is what the assignment says
1.) Input, via a question in the console, the report owner’s first name as a string and build the last name via input, one character at a time.
a. Check, conditionally, to make sure the first name and last name don’t contain any numeric characters, numbers between 0 – 9. If it does you must remove it. The names can not contain any white space either or special characters.
I already did the first part, and here is my code:
package inclassassignment;
import java.util.Scanner;
public class inclassassignment {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println ("Enter your first name");
String temp;
Scanner your_name = new Scanner (System.in);
temp = your_name.nextLine();
System.out.println(temp);
int n = 0;
System.out.println ("Enter your last name");
String temp1;
temp1 = "";
while (n < 6) {
System.out.println("Please print the next letter of your last name");
String nextletter1;
Scanner lastname = new Scanner (System.in);
nextletter1 = lastname.nextLine();
char nextletter = nextletter1.charAt(0);
temp1 = temp1 + nextletter;
n++;
}
System.out.println(temp1);
{
}
}
}
// I now need to do the part that says to check each ASCII value and make sure none of the letters contain a number. I'm pretty sure this requires an "if else" statement but I've never written one to success.
edit: I should point out I am not allowed to have any static variables or methods in any class except for the class with the main method.
According to your task, you can do it in this way:
int n = 0;
System.out.println("Enter your last name");
String lastName = "";
while (n < 6) {
System.out.print("Please print the next letter of your last name: ");
String tmp = your_name.nextLine();
char c = tmp.charAt(0);
if (Character.isAlphabetic(c)) {
lastName += c;
n++;
} else {
System.out.println("You can use only letters! Try again!");
}
}
System.out.println(lastName);
You can use regular expressions
Scanner sc=new Scanner(System.in);
String s= sc.nextLine(); //read the string
String regex1 = "\\d+" // the regular expression for numbers
if(s.matches(regex1)) // check if the string contains numbers
System.out.println("contains numbers");
I would start with a utility method to normalize names based on your required rules, Character.isUpperCase(char) or Character.isLowerCase(char) and a for-each loop over String.toCharArray() like,
static String normalizeName(String name) {
StringBuilder sb = new StringBuilder();
for (char ch : name.toCharArray()) {
if (Character.isUpperCase(ch) || Character.isLowerCase(ch)) {
sb.append(ch);
}
}
return sb.toString();
}
Then you can call it (and I would use it for both firstName and lastName, for consistency). Like,
public static void main(String[] args) {
System.out.println("Enter your first name");
Scanner scan = new Scanner(System.in);
String firstName = normalizeName(scan.nextLine());
System.out.println("Enter your last name");
String lastName = normalizeName(scan.nextLine());
System.out.printf("Hello %s %s%n", firstName, lastName);
}
Pretty sure this is posted elsewhere
str.matches(".*\\d+.*")// To check if string contains numbers
Try this function:
public String removeNum(String in){
String[] input= in.split("");
String num= "0123456789";
String[] numbers= num.split("");
List<String> numbersToDelete = Arrays.asList(numbers);
for(int i=0;i<input.length;i++){
if(numbersToDelete.contains(input[i])){
input[i]="";
}
}
//Converting from Array back to String
String out = "";
for(int j=0;j<input.length;j++){
out=out+input[j];
}
return out;
}

How do you check if a string is a palindrome in java?

I am trying to write a program that checks if a string is a palindrome and so far I know I am on the right path but when I enter my code it keeps on running for ever. I don't know what the problem is and would like help finding out the solution. In my program I want the user to enter word or words in the method Printpalindrome and then the program should know if the string is a palindrome or not.
Here is my code:
...
Scanner console = new Scanner (System.in);
String str = console.next();
Printpalindrome(console, str);
}
public static void Printpalindrome(Scanner console, String str) {
Scanner in = new Scanner(System.in);
String original, reverse = "";
str = in.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- ) {
reverse = reverse + str.charAt(i);
}
if (str.equals(reverse))
System.out.println("Entered string is a palindrome.");
}
}
Because of this line:
n = in.nextLine();
your program is waiting for a second input, but you already got one before entering the function.
Remove this line and it works.
Here's your program, cleaned (and tested) :
public static void main(String[] args){
Scanner console = new Scanner (System.in);
String n = console.next();
Printpalindrome(n);
}
public static void Printpalindrome(String n){
String reverse = "";
for ( int i = n.length() - 1; i >= 0; i-- ) {
reverse = reverse + n.charAt(i);
System.out.println("re:"+reverse);
}
if (n.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is NOT a palindrome.");
}
Of course, this isn't the best algorithm, but you already know there are many QA on SO with faster solutions (hint: don't build a string, just compare chars).
Remove
Scanner in = new Scanner(System.in);
and
n = in.nextLine();
from Printpalindrome function
and it should work.
This can be implemented in a far more efficient manner:
boolean isPalindrom(String s){
if (s == null /* || s.length == 0 ?*/) {
return false;
}
int i = 0, j = s.length() - 1;
while(i < j) {
if(s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
The argument for PrintPalindrom is ignored. You read another value with `in.nextLine()'. Which is the reason for your issues.
Ur code with some correction:-
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
I tried your code and what i observed was that :
first of all you are making a string to enter on the line 2 of your code:
String n=console.next();
next the the program again goes to waiting when this line gets executed:
n = in.nextLine();
actually this particular line is also expecting an input so that is why the program halt at this point of time.
If you enter your String to be checked for palindrome at this point of time you would get the desired result .
But I would rather prefer you to delete the line
n = in.nextLine();
because, with this, you would have to enter two words which are ambiguous.

Reversing string stack java

So I'm attempting to create a object that essentially reverses a string someone inputs. I was able to get it to reverse the word order but I need to get it to reverse the words themselves using a stack so this is my code to input the letters into the stack.
public class Reverser
{
private Stack<String> stack;
public Reverser()
{
stack = new Stack<String>();
}
public String evaluate(String expr)
{
Scanner in = new Scanner(expr);
char letter;
String sentence="";
String rSent="";
String word="";
while(in.hasNext())
{
sentence = in.next();
for (int i = 1; i <= sentence.length(); i++)
{
while (i <= sentence.length())
{
letter = sentence.charAt(i);
word += letter;
}
stack.push(word);
}
}
while (!stack.isEmpty())
{
word = stack.pop();
rSent += word;
}
return rSent;
}
}
It compiles fine without issue, but when I run my driver
public class StringReversing
{
public static void main(String[] args)
{
String sentence, result, again;
Scanner in = new Scanner(System.in);
do
{
Reverser evaluator = new Reverser();
System.out.println("Please enter a sentence");
sentence = in.nextLine();
result = evaluator.evaluate(sentence);
System.out.println();
System.out.println("Your sentence reversed is:");
System.out.println(result);
System.out.println("Would you like to reverse another sentence [Y/N]?");
again = in.nextLine();
System.out.println();
}
while (again.equalsIgnoreCase("y"));
}
}
Now I enter a sentence and I get nothing. Am I missing something?
You get an endless loop:
for (int i = 1; i <= sentence.length(); i++)
{
while (i <= sentence.length())
{
letter = sentence.charAt(i);
word += letter;
}
stack.push(word);
}
The inner while loop is an endless loop because i will be ever the same and lower then sentence.length().
And arrays in java are zero based. You for loop shoud start at zero.
Wouldn't this already solve your requirement?
String input = "I like this CAFEBABE.";
System.out.println("reversed: " + new StringBuilder(input).reverse());

Trying to Convert a string to another string from array in a file on only the first space

Disclaimer, I've been at java for about a month. I'm completely lost on this. I'm trying to have a user input a phrase and if any strings in that phrase is found on the array, it returns the corresponding string in one line. if the string isn't found, it would just skip it.
so if someone typed in "dog eat my fish"
and the array holds:
dog perro
eat munched
fish yellow trout
it would return:
perro munched yellow trout
I haven't written the code to print out what I've got yet, but I know this code isn't working.
any help would be greatly appreciated.
import java.io.*;
import java.util.*;
public class ArrayTest2 {
public static void main(String[] args)
throws java.io.IOException {
Scanner input = new Scanner(System.in);
String userString = " ";
userString = englishString();
String[][] wordList = new String[10][2];
loadEnglishString(wordList);
}
public static String englishString() {
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a phrase to translate: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadEnglishString(String[][] wordList)
throws java.io.IOException {
String filName = " ";
filName = ("/home/chrism/ArrayTest2.txt");
Scanner input = new Scanner(new File(filName));
while(input.hasNextLine()) {
String line = input.nextLine();
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
boolean stop = false;
for(int i = 0; i < wordList.length; i++) {
if(stop)
break;
for(int j = 0; j < wordList[i].length; j++)
if(input.hasNextLine())
wordList[i][j] = input.nextLine();
else {
stop = true;
}
break;
}
}
}
input.close();
}
}
You'll definitely want to change your for loop. Brackets are your friend.
for(int i = 0; i < wordList.length; i++) {
if(stop)
break;
for(int j = 0; j < wordList[i].length; j++) {
if(input.hasNextLine())
wordList[i][j] = input.nextLine();
else {
stop = true;
}
}
}
The way you had it, both increments were registering as dead code because your second break would always called the first time through the loop, and your else was registering as coupled with the first if(stop).
Edit: don't know for sure about how the else would couple, but the break is definitely called after the first run through.
//package com.myjava.stokenizerr;
import java.util.StringTokenizer;
public class MyStringTokenizer {
public static void main(String a[]){
/* your code for user input string */
/* assume input as dog eat my fish */
String input = "dog eat my fish";
String msg = "dog perro eat munched fish yellow trout";
StringTokenizer st1 = new StringTokenizer(msg," ");
StringTokenizer st2 = new StringTokenizer(input," ");
while(st1.hasMoreTokens()){
System.out.println(st1.nextToken()); // Store this one(first) string array
}
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken()); // Store in another(second) array
}
/* Now Compare both the arrays */
/* If the strings are equal then remove string from second array */\
/* If equal just skip it */
}
}
See the above code st1.nextToken() and st2.Tokens() will give you the values
For comparing take two loops
for(i==0;i<array1length();i++) {
for(j==0;j<array2length();j++) {
// Your code for comparsion
}
}

Java: how to print a dataset of strings as entered except in reverse order?

This program should input a dataset of names followed by the name "END". The program should print out the list of names in the dataset in reverse order from which they were entered. What I have works, but if I entered "Bob Joe Sally Sue" it prints "euS yllaS eoJ boB" insead of "Sue Sally Joe Bob". Help!?
import java.util.Scanner;
public class ReverseString {
public static void main(String args[]) {
String original, reverse = "";
Scanner kb = new Scanner(System.in);
System.out.println("Enter a list of names, followed by END:");
original = kb.nextLine();
int length = original.length();
while (!original.equalsIgnoreCase("END") ) {
for ( int i = length - 1; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
original = kb.next();
}
System.out.println("Reverse of entered string is: "+reverse);
}
}
I think that you need to use this simple algorithm. Actually you're not using the proper approach.
Take the whole string which contains all the names separated by spaces;
Split it using as a delimiter the space (use the method split)
After the split operation you will get back an array. Loop through it from the end (index:array.length-1) to the starter element (1) and save those elements in another string
public String reverseLine(String currLine) {
String[] splittedLine = currLine.split(" ");
StringBuilder builder = new StringBuilder("");
for(int i = splittedLine.length-1; i >= 1; i--) {
builder.append(splittedLine[i]).append(" ");
}
return builder.toString();
}
I've supposed that each lines contains all the names separated by spaces and at the end there is a string which is "END"
A quick way, storing the result in the StringBuilder:
StringBuilber reverse = new StringBuilder();
while (!original.equalsIgnoreCase("END")) {
reverse.append(new StringBuilder(original).reverse()).append(" ");
original = kb.next();
}
System.out.println("Reverse: " + reverse.reverse().toString());
Using the approach suggested in the comments above is very simple, and would look something like:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> names = new ArrayList<>();
while (sc.hasNext())
{
String name = sc.next();
if (name.equals("END"))
{
break;
}
names.add(name);
}
Collections.reverse(names);
for (String name: names)
{
System.out.println(name);
}
System.out.println("END");
}
Let the Scanner extract the tokens for you, no need to do it yourself.

Categories