Adding a space inbetween a user inputed string - java

I want a user to enter a String and then add a space in between a character at a chosen interval.
example: user enters: hello
then asks for a space every 2 letters.
output = he_ll_o_
import java.util.Scanner;
public class stackOverflow {
public static void main(String[] args) {
System.out.println("enter a string");
Scanner input = new Scanner(System.in);
String getInput = input.nextLine();
System.out.println("how many spaces would you like?");
Scanner space = new Scanner(System.in);
int getSpace = space.nextInt();
String toInput2 = new String();
for(int i = 0; getInput.length() > i; i++){
if(getSpace == 0) {
toInput2 = toInput2 + getInput.charAt(i);
}
else if(i % getSpace == 0) {
toInput2 = toInput2 + getInput.charAt(i) + "_"; //this line im having trouble with.
}
}
System.out.println(toInput2);
}
}
Thats my code so far, it might be the completely wrong way of solving it, so correct me if im wrong. thanks in advance :)

I think you would want to formulate your loop body as follows:
for(int i = 0; getInput.length() > i; i++) {
if (i != 0 && i % getSpace == 0)
toInput2 = toInput2 + "_";
toInput2 = toInput2 + getInput.charAt(i);
}
But, there's a simpler way, using regular expressions:
"helloworld".replaceAll(".{3}", "$0_") // "hel_low_orl_d"

You can simplify your case distinction to:
toInput2 += getInput.charAt(i);
if(i != 0 && i % getSpace == 0) {
toInput2 += "_";
}
You should also think about renaming your variables.

Related

For loop is printing out multiple print statements

I'm making a program for class which prints out the number of vowels in a word and any help would be appreciated. Currently, the program prints out the correct number of vowels but also prints out the print statement, "vowels:" multiple times before. I've tried moving the print statement and the braces around but it says "error: 'else if' without 'if'". I'm completely new to Java so sorry if the solution is in plain sight. Thank you in advance :)
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels= 0;
int l;
l= text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i,i+1);
if (wordPRT.compareToIgnoreCase("a")==0 || wordPRT.compareToIgnoreCase("e")==0||
wordPRT.compareToIgnoreCase("i")==0
|| wordPRT.compareToIgnoreCase("o")==0
|| wordPRT.compareToIgnoreCase("u")==0){
vowels++;
System.out.println("vowels: " + vowels);
}
else if(vowels<1){
System.out.print("no vowels");
}
}
}
}
You are printing everything in a for loop instead of count vowels and print at the end.
try something like:
int vowelsCounter = 0;
for(...) {
... logic to count the vowels
if(isvowel(string.charAt(i)){
vowelsCountr++;
}
}
if(vowelsCounter > 0 ) {
printSomething
}
else {
print something else
}
Also You should not use subString for this kind of a loop but string.charAt(i)
Move the print statements out of the for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels = 0;
int l;
l = text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i, i + 1);
if (wordPRT.compareToIgnoreCase("a") == 0 || wordPRT.compareToIgnoreCase("e") == 0
|| wordPRT.compareToIgnoreCase("i") == 0 || wordPRT.compareToIgnoreCase("o") == 0
|| wordPRT.compareToIgnoreCase("u") == 0) {
vowels++;
}
}
if (vowels >= 1) {
System.out.println("vowels: " + vowels);
} else {
System.out.print("no vowels");
}
}
}
A sample run:
Enter text: Hello
vowels: 2

Using if statement to print whether a String is odd or even in java

public static void main(String[] args) {
Scanner String = new Scanner(System.in);
System.out.print("Enter a String: ");
String Str1 =String.nextLine();
String input;
input = Str1;
char[] inputArray = input.toCharArray();
String[] lines = new String[input.length() / 2 + 1];
int i, u;
for (i = 0; i < input.length() / 2; i++) {
char begChar = inputArray[i];
char endChar = inputArray[input.length() - i - 1];
int spacesBefore = i;
int spacesAfter = i;
int spacesInBetween = input.length() - 2 - 2 * i;
String line = "";
for (u = 0; u< spacesBefore; u++) {
line += " ";
}
line += begChar;
for (u = 0; u < spacesInBetween; u++) {
line += " ";
}
line += endChar;
lines[i] = line;
}
if (input.length() % 2 != 0) {
String lastLine = "";
for (u = 0; u < input.length() / 2; u++) {
lastLine += " ";
}
lastLine += inputArray[input.length() / 2];
lines[input.length() / 2] = lastLine;
}
for (i = 0; i < lines.length && lines[i] != null; i++) {
System.out.println(lines[i]);
}
System.out.print("String Length: ");
System.out.println(Str1.length());}
This is where I am having the issue with my code.
I am trying to get this to print whether the user entered String is odd or even. Using Netbeans IDE it keeps telling me that I have a bad operand type int for unary operator '!'. Everything else in the code is working like it should just can't get this to work.
if ( !(Str1.length( ) %0x2))
System.out.println("The String is odd");
else
System.out.println("The String is even");
! is an unary negation operator that expects a single boolean operand. Therefore it can't be applied on an int
You should change
if ( !(Str1.length( ) %0x2))
System.out.println("The String is odd");
else
System.out.println("The String is even");
To this
if (Str1.length() %2 != 0){
System.out.println("The String is odd");
}
else{
System.out.println("The String is even");
}
!= is the operator that checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
Basically you do this:
if (Str1.length() %2 != 0)
Currently you are attempting to call the ! operator on a integer result from using the % operator which is producing the error you are seeing currently
if (!(Str1.length( ) % 0x2))
System.out.println("The String is odd");
else
System.out.println("The String is even");
What you can do is what was suggested by others. This works because you are comparing your result of using the % operator with 2 which produces a boolean result. Therefore the if statement can evaluate it and determine it to be true or false. With the added ! operator you reverse the result of whatever the expression is inside the parentheses.
if (!(Str1.length( ) % 2 != 0))
System.out.println("The String is odd");
else
System.out.println("The String is even");

Java - Looping Number Strings

You all were so helpful yesterday in getting over my first hump in this problem that I wanted to see if there's a way I can modify my final product (Apologies if my formatting is off - Still trying to get indentations correct in my IDE.
import javax.swing.JOptionPane;
public class NumberLoops {
public static void main(String[] args) {
String strNum1;
String strNum2;
int intNum;
boolean isValid = true;
boolean isError = false;
strNum1 = JOptionPane.showInputDialog ("Enter Number String");
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c == '-'){
JOptionPane.showMessageDialog(null, "Negative Digit Found - Enter Positive Numbers Only", "Error", JOptionPane.INFORMATION_MESSAGE);
isValid = false;
break;
}
}
if (isValid){
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
intNum = Character.getNumericValue(c);{
if (intNum > 0 && intNum <= 9){
isError = true;
break;
}
}
}
}
if (isError){
int aDigit,totalNum=0;
char chDigit;
strNum2 = String.valueOf(strNum1);
for (int count=0; count<strNum1.length();count++){
chDigit = strNum2.charAt(count);
aDigit = Character.getNumericValue(chDigit);
totalNum += aDigit;
if (aDigit > 0 && aDigit <= 9){
System.out.print(aDigit + " ");
}
}
System.out.print(" " + "The sum is: " + totalNum);
}
}
}
My question concerns the last loop. It functions as desired by printing to the console if I enter say 123123 into the message prompt, it lists that string as 1 2 3 1 2 3 and then the total of 12.
But that is in the console itself. What I'm trying to wrap my mind around is getting it to display in a message box instead of the console.
I'm guessing I need to create a new string like (incoming pseudocode):
if (aDigit > 0 && aDigit <= 9){
strNum3 = everycharinStr2 + " "
Which is the part I guess I'm not grasping.
FYI, this is a homework assignment so I don't necessarily want an outright answer, but I feel I am so close that I need some extra eyes on it to see if there's anything I can do. (I have read up on arrays and such but we aren't at that point yet so I don't think I'll go down that road quite yet.)
You only have to make a little change in your code:
strNum2 = String.valueOf(strNum1);
String resultString = "";
for (int count=0; count<strNum1.length();count++){
chDigit = strNum2.charAt(count);
aDigit = Character.getNumericValue(chDigit);
totalNum += aDigit;
if (aDigit > 0 && aDigit <= 9){
System.out.print(aDigit + " ");
resultString += aDigit + " ";
}
}
JOptionPane.showMessageDialog(null, resultString);
Create a new String and in each iteration append the number to this String, then show it in a dialog.
The errors are commented out.
//if (intNum > 0 && intNum <= 9){
if (intNum < 0 || intNum > 9){
isError = true;
break;
}
//if (aDigit > 0 && aDigit <= 9){
if (aDigit >= 0 && aDigit <= 9){
System.out.print(aDigit + " ");
//resultString+ = aDigit + " ";
resultString += "" + aDigit;
}
//if (isError) {
if (!isError) {
Just use a JLabel!
Since your already using swing, this would be your best choice. But then you'd need a frame and panel, so if you don't already have that, don't do this.
JLabel label = new JLabel()
label.setText("Random Text!")
You can also do this, with a pop up:
JOptionPane.showMessageDialog(null, "My String!");

How to return a string?

import java.util.*;
public class HangManP5
{
public static void main(String[] args)
{
int attempts = 10;
int wordLength;
boolean solved;
Scanner k = new Scanner(System.in);
System.out.println("Hey, what's your name?");
String name = k.nextLine();
System.out.println(name+ ", hey! This is a hangman game!\n");
RandomWord(word);
int len = word.length();
char[] temp = new char[len];
for(int i = 0; i < temp.length; i++)
{
temp[i] = '*';
}
System.out.print("\n");
System.out.print("Word to date: ");
while (attempts <= 10 && attempts > 0)
{
System.out.println("\nAttempts left: " + attempts);
System.out.print("Enter letter: ");
String test = k.next();
if(test.length() != 1)
{
System.out.println("Please enter 1 character");
continue;
}
char testChar = test.charAt(0);
int foundPos = -2;
int foundCount = 0;
while((foundPos = word.indexOf(testChar, foundPos + 1)) != -1)
{
temp[foundPos] = testChar;
foundCount++;
len--;
}
if(foundCount == 0)
{
System.out.println("Sorry, didn't find any matches for " + test);
}
else
{
System.out.println("Found " + foundCount + " matches for " + test);
}
for(int i = 0; i < temp.length; i++)
{
System.out.print(temp[i]);
}
System.out.println();
if(len == 0)
{
break; //Solved!
}
attempts--;
}
if(len == 0)
{
System.out.println("\n---------------------------");
System.out.println("Solved!");
}
else
{
System.out.println("\n---------------------------");
System.out.println("Sorry you didn't find the mystery word!");
System.out.println("It was \"" + word + "\"");
}
}
public static String RandomWord(String word)
{
//List of words
Random r = new Random();
int a = 1 + r.nextInt(5);
if(a == 1)
{
word=("Peace");
}
if(a == 2)
{
word=("Nuts");
}
if(a == 3)
{
word=("Cool");
}
if(a == 4)
{
word=("Fizz");
}
if(a == 5)
{
word=("Awesome");
}
return (word);
}
}
Ok, so this is my code for a hangman game, the only thing I have left to do is to get my program to randomize one of the words, which it should do in the method successfully. But the only problem I'm having is getting the String variable "word" to go back to the main class (there are errors underlining all the "word" variables in the main class).
If I could get help with either this or another way to produce a random word from a list, that would be amazing.
In java, parameters are passed by value and not by reference. Therefore, you cannot change the reference of a parameter.
In your case, you need to do:
public static String getRandomWord() {
switch(new Random().nextInt(5)) {
case 0:
return "Peace";
case 1:
return "Nuts";
// ...
default:
throw new IllegalStateException("Something went wrong!");
}
}
And in main:
// ...
String word = getRandomWord();
int len = word.length();
// ...
You can't modify the caller's reference.
RandomWord(word);
needs to be something like
word = RandomWord(word);
Also, by convention, Java methods start with a lower case letter. And, you could return the word without passing one in as an argument and I suggest you save your Random reference and use an array like
private static Random rand = new Random();
public static String randomWord() {
String[] words = { "Peace", "Nuts", "Cool", "Fizz", "Awesome" };
return words[rand.nextInt(words.length)];
}
And then call it like
word = randomWord();

How to manually shuffle letters in a String

I am Writing a game/java program that needs to take a word from a .txt file, then jumble the letters up and ask the user to guess what word it is. I am having two problems:
First is that I receive this error message when I run it:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Proj4.main(Proj4.java:20)
The second problem I am having is jumbling the word. I cannot figure out how to do that without using the shuffle command (which I cannot use).
Here is my code:
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Proj4 {
public static void main(String[] args) throws IOException {
Scanner inFile = new Scanner(new File ("words.txt"));
int counter = 0;
while (inFile.hasNext()) {
inFile.nextLine();
counter++;
}
String[] word = new String[counter];
for (int j = 0; j < counter; j++) {
word[j] = inFile.nextLine();
}
int lengthList = Integer.parseInt(word[0]);
Scanner s = new Scanner(System.in);
Random randomNumber = new Random();
int i = randomNumber.nextInt(lengthList); //picks a word at random. assigns to "word"
String currentWord = word[i];//picks a word at random. assigns to "currentWord"
int turnScore = 10, finalScore = 0;
char input;
String guess ="a";
do { //do loop for whole program looping
turnScore = 10;
do { //do loop for guessing correct
do{
System.out.println("Current Puzzle: " + currentWord);
System.out.println("Current points for this word: " + turnScore);
System.out.println("Enter (g)uess, (n)ew word, (h)int, or (q)uit: ");
input = s.nextLine().charAt(0); //assigns input to first letter entered by user
Character.toLowerCase(input); //puts input to lower case
if(input != 'g' && input != 'G' && input != 'h' &&
input != 'H' && input != 'n' && input != 'N' &&
input != 'Q' && input != 'q'){
System.out.println("Invalid Entry. Please input g, n, q or h only! \n ");
}
} while (input != 'g' && input != 'G' && input != 'h' && input != 'H' &&
input != 'n' && input != 'N' && input != 'Q' && input != 'q'); //end do while loop (ask for input)
if (input == 'g') {
System.out.println("Enter Your guess: ");
guess = s.nextLine();
System.out.println("your guess is: " + guess + "\n\nThe word is: " + currentWord);
if (guess.equalsIgnoreCase(currentWord)) {
System.out.println("You Guessed Correct");
System.out.println("Your Score for this word is: " +turnScore );
finalScore = finalScore + turnScore;
}//end if guess = currentWord
else
{
if (turnScore <= 0)
{
turnScore = 0;
}//end if turn score >=0
else
{
turnScore -= 1;
}//end else turn score minus 1.
System.out.println("Nope, Sorry \n\n");
}//end else guess not = to currentWord.
}//end if user input = G.
else if (input == 'n')
{
i = randomNumber.nextInt();
currentWord = word[i];
turnScore = 10;
}//end new word if
else if (input =='h')
{
turnScore = turnScore/2;
Random ranNum = new Random();
int randomLetter = ranNum.nextInt(5);
char hint = currentWord.charAt(randomLetter);
System.out.println("the Letter at spot " + (randomLetter +1) + " is " + hint);
}//end of if input = h
else if (input == 'q')
{
finalScore = finalScore + turnScore;
System.out.println("Goodbye!");
System.out.println("Final Score: " + finalScore);
System.exit(0);
}//end else if for input = Q.
}while (!guess.equalsIgnoreCase(currentWord));
}while (input != 'q');
System.out.println("Your Final Score is: " + finalScore);
System.out.println("Goodbye!");
inFile.close();
}//End main
}//end class
Your exception is caused by these lines of code:
int counter = 0;
while (inFile.hasNext()) {
inFile.nextLine();
counter++;
}
//inFile no longer has next, will break when the for loop is entered
String[] word = new String[counter];
for (int j = 0; j < counter; j++) {
word[j] = inFile.nextLine();
}
The easy way to fix this is to redeclare the inFile and read from beginning again.
The best way to fix this is to use a dynamically sized ArrayList:
int counter = 0;
ArrayList<String> word = new ArrayList<String>();
while (inFile.hasNext()) {
word.add(inFile.nextLine());
counter++;
}
This also makes your randomizing much more easy since you can do something sneaky with it.
Here's the documentation on ArrayList.
The key, not the solution, to your second question lies add(int index, E element)
There is a way to shuffle on the fly as you read. You should figure that out, and if you get stuck, then come back.

Categories