creating a new string from a char array [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm seeing some weird occurrence that if I don't use my original input string to be converted back into a string from a char array, the changes don't occur in the new string?
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("Type in String:");
String theString = scan.nextLine();
theString = theString.replaceAll("\\s+", " ");
char [] convert = theString.toCharArray();
convert[0] = Character.toUpperCase(convert[0]);
for(int i = 0; i < convert.length; i++){
if(Character.isWhitespace(convert[i])){
convert[i+1] = Character.toUpperCase(convert[i+1]);
}
}
theString = String.valueOf(convert);
System.out.println(theString);
If line theString on the 2nd the to last line was changed to lets say:
String newString = String.valueOf(convert);
or
String newString = String(convert);
My output does not change the input! This program in summary capitalizes the first character of every word in a string. Can someone explain why occurrence is happening?

Its works. I tested it. I think you forget to change
System.out.println(theString);
to
System.out.println(newString);
Full code:
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Type in String:");
String theString = scan.nextLine();
theString = theString.replaceAll("\\s+", " ");
char [] convert = theString.trim().toCharArray();
convert[0] = Character.toUpperCase(convert[0]);
for(int i = 0; i < convert.length; i++){
if(Character.isWhitespace(convert[i])){
convert[i+1] = Character.toUpperCase(convert[i+1]);
}
}
String newString = String.valueOf(convert);
System.out.println(newString);
}
input: hello world
output: Hello World
Thats what you expected :) And i fixed the ArrayIndexOutOfBounds Exception when the String ends with a whitespace.
char [] convert = theString.trim().toCharArray();

It works fine, but what you want to consider is after scanning in the String to use
theString.trim();
This will remove whitspaces from the end, because right now if I enter "hello hello " (notice the space at the end) it will throw an OutOfBOundsException because of your i+1 in the loop.
Or just check inside your loop if the index i+1 exists.

Related

Code Help - Used scanner to initialize string array. When displaying, array values are all blank

I'm currently taking a beginning Computer Science course and for one of our assignments we basically have to create a magic eight ball using an array where the user inputs the amount of values in the array and also inputs the values themselves in the array using a loop. After writing the code, I tested it and found that for some reason it wasn't setting the input into the array like it was supposed to it and after hours tweaking and trying to figure out what's wrong with it I still have no clue. Any help would be much appreciated.
Scanner input = new Scanner(System.in);
String answer = "a";
String question = " ";
int currentResponse = 0;
out.println("How many responses would you like there to be?");
int numResponses = input.nextInt();
String[] responses = new String[numResponses];
//This is the loop that's the problem:
for (int i = 0; i < numResponses; i++)
{
out.println("Enter an answer: ");
answer = input.nextLine();
responses[i] = answer; //Should set the array value to the input
input.next(); //It kept skipping the input part the first time
//so I added this
}
//This is where I tried two different ways of printing out the array to
//test it just in case that was the problem:
out.println(Arrays.toString(responses));
for (int i = 0; i < responses.length; i++)
{
System.out.print(responses[i] + " ");
}
while (!question.equalsIgnoreCase("stop"))
{
out.println("What is your question?");
question = input.nextLine();
input.next();
currentResponse = (int)(Math.random()*numResponses);
out.println(currentResponse);
out.println(responses[currentResponse]); //It also doesn't appear to
//actually print this out but I think that that's because the values are //blank
spaces
}
out.println("Thank you for using the Magic Eight Ball");
The output should be something like
How many responses would you like there to be?
4 //The input
Enter an answer:
s
Enter an answer:
d
Enter an answer:
f
Enter an answer:
g
[s,d,f,g]
What is your question?
s
0 //The randomized array index number
s //The value of that index
What is your question?
d
2
f
What is your question?
g
1
g
instead it's currently
4
Enter an answer:
s
Enter an answer:
d
Enter an answer:
f
Enter an answer:
g
[, , , ]
What is your question?
s
0 //the randomized array index number
What is your question?
d
2
What is your question?
g
1
input.nextInt(); only consumes the integer entered, it doesn't consume the newline character entered after it. To get around this you can use input.nextLine(); to consume the newline char after it. Then you should be able to remove the input.next(); from the end of the for loop when taking in the responses.
You can also remove the input.next(); within the question loop later on as that's not needed as well -- the input.nextLine(); consumes the whole line.
Here's the adjusted code:
Scanner input = new Scanner(System.in);
String answer = "a";
String question = " ";
int currentResponse = 0;
System.out.println("How many responses would you like there to be?");
int numResponses = input.nextInt();
input.nextLine();
String[] responses = new String[numResponses];
//This is the loop that's the problem:
for (int i = 0; i < numResponses; i++)
{
System.out.println("Enter an answer: ");
answer = input.nextLine();
responses[i] = answer; //Should set the array value to the input
}
//This is where I tried two different ways of printing out the array to
//test it just in case that was the problem:
System.out.println(Arrays.toString(responses));
for (int i = 0; i < responses.length; i++)
{
System.out.print(responses[i] + " ");
}
while (!question.equalsIgnoreCase("stop"))
{
System.out.println("What is your question?");
question = input.nextLine();
currentResponse = (int)(Math.random() * numResponses);
System.out.println(currentResponse);
System.out.println(responses[currentResponse]); //It also doesn't appear to
//actually print this out but I think that that's because the values are //blank spaces
}
System.out.println("Thank you for using the Magic Eight Ball");
}
Some additional documentation: https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html

I want to get the last letter in a string and print true or false depending on the letter [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am new to programming, currently my first year in trying this.
Just like the title, i am having a hard time completing this code of mine.
I already searched high and low and couldn't find something.
The code is incomplete and I know i need to change some things.
What can i do to complete this? I am already worn down.
import java.util.*;
public class Ihateyou {
public static void main (String []args) {
Scanner fkc = new Scanner (System.in);
System.out.println("Enter an Element or something: ");
char ch=fkc.next( ).charAt(0);
String unknown = fkc.nextLine();
if (ch=='H' + unknown.substring(unknown.length() - 1))
{
System.out.println("False "+ch+" ends with h");
}
else if ((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
System.out.println("True "+ch+" ends with no H");
}
}
Scanner fkc = new Scanner (System.in);
System.out.println("Enter an Element or something: ");
String unknown = fkc.nextLine();
char [] arr = unknown.toCharArray();
int lastLetterIndex = arr.length - 1;
if(arr[lastLetterIndex]=='h') {
System.out.println("ends with H");
}
else {
System.out.println("ends with no H");
}
It's nore pretty clear what you want to do, but last letter of the string you can get with str.charAt(str.length() - 1):
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Enter an Element or something: ");
String str = scan.nextLine();
char lastChar = str.charAt(str.length() - 1);
if (lastChar != 'h')
System.out.println("False " + str + " ends with h");
else if (Character.isLetter(lastChar))
System.out.println("True " + str + " ends with no H");
}
I'm not 100% sure what you want to do, but I've tried to go thru what your code seems to be doing since you seem a little bit unsure of that, and then propose how I would solve the problem I think you have.
public class Ihateyou {
public static void main (String []args) {
Scanner fkc = new Scanner (System.in); // This creates a new scanner, which lets us read from System
System.out.println("Enter an Element or something: ");
char ch=fkc.next( ).charAt(0); // This reads the next sequence terminated by the enter key. Then it stores the single first character of that in a char, ch
String unknown = fkc.nextLine(); // This basically does the same thing, storing it in unknown
if (ch=='H' + unknown.substring(unknown.length() - 1)) // This checks if ch equals H + most of the unknown string. This doesn't make sense for two reasons.
// One problem is that 'H' + unknown is a string, not a char: it doesn't make sense to compare a String with a char.
// The other is that unless unknown is an empty string (""), and char is 'H', even if we could compare they wouldn't be the same
{
System.out.println("False "+ch+" ends with h");
}
else if ((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
System.out.println("True "+ch+" ends with no H");
}
}
What I think you might be trying to do is to determine whether the thing the user inputs ends with an H. To do this, I would try the following:
public static void main (String []args) {
Scanner fkc = new Scanner (System.in); // This creates a new scanner, which lets us read from System
System.out.println("Enter an Element or something: ");
String userInput = fkc.nextString(); // Store the next String the user inputs in userInput
if(userInput.charAt(userInput.length() - 1)) == 'H'){ // userInput.charAt() gets us the character at a given index in the string. We want the last one, so we get
// the one at userInput.length() - 1. Then we check to see if it is H
{
System.out.println("False "+ch+" ends with h");
}
else{
System.out.println("True "+ch+" ends with no H");
}
}

Creation of Acroynm with Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am currently attempting to make a program that takes any string input and splits by the spaces to create an acronym. Currently the program only prints out the first letter of the first word input. I believe that the problem is with my for loop. Could someone care to take a look?
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class WordSplitter {
public static void main(String[] args) {
String phraseToChange;
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
phraseToChange = input.next();
String[] phraseChanger = phraseToChange.split(" ");
for (int i = 0; i <= phraseChanger.length; i++) {
String s = phraseChanger[i];
System.out.println(s.charAt(0));
}
}
}
You never actually build the acronym using the first letter from each word. Try this code instead:
String [] phraseChanger = phraseToChange.split(" ");
StringBuilder sb = new StringBuilder();
for (int i=0; i < phraseChanger.length ; i++) {
sb.append(phraseChanger[i].charAt(0));
}
System.out.println(sb.toString());
instead of this phraseToChange = input.next(); you have to put phraseToChange = input.nextLine(); it will work

I am trying to input sentences in string arrays and display them in reverse order [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
So far I have set it up so that the user can enter the number of sentences and input into each position of the String array using a for loop.
public class Test5 {
public static String inputline;
public static void main(String[] args) {
System.out.print("Enter the number of lines:");
Scanner kb=new Scanner(System.in);
int number=kb.nextInt();
String []line=new String[number];
for(int i=0;i<line.length+1;i++){
line[i]=kb.next();
}
}
}
First and foremost your code is going to read in 1 more time than you want which will cause an array out of bounds exception. Next you will want to do nextLine() to account for the new line character being entered by the user. Try this:
System.out.print("Enter the number of lines:");
Scanner kb=new Scanner(System.in);
int number=Integer.parseInt(kb.nextLine());
String []line=new String[number];
//loop through only the size of the array
for(int i=0; i < line.length; i++){
line[i]=kb.nextLine();
}
//now to output the array in reverse order you need to start from the
//other end of the array
for(int i = line.length - 1; i >= 0; i--){
System.out.println(line[i]);
}
//always close the Scanner when done
kb.close();
Some useful resources about Scanners - https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Caesar Shift Cipher, input exception error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I was having some issues with this originally, but found some different help on here. now I seem to be having an issue with an input exception error. I believe I have the correct formatting for the input.
import java.util.Scanner;
public class CaesarShift
{
//initialize private string for the alphabet
private final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
//public encryption code
public String encryptionMethod(String normText, int caesarShift)
{
normText = normText.toLowerCase();
String cipherText = "";
for (int a = 0; a < normText.length(); a++)
{
int charP = ALPHABET.indexOf(normText.charAt(a));
int shiftValue = (caesarShift + charP) % 26;
char replaceValue = this.ALPHABET.charAt(shiftValue);
cipherText += replaceValue;
}
return cipherText;
}
public String decryptionMethod(String cipherText,int caesarShift)
{
cipherText = cipherText.toLowerCase();
String normText = "";
for (int a = 0; a < cipherText.length(); a++)
{
int charP = this.ALPHABET.indexOf(cipherText.charAt(a));
int keyValue = (charP - caesarShift) % 26;
if(keyValue < 0)
{
keyValue = this.ALPHABET.length() + keyValue;
}
char replaceValue = this.ALPHABET.charAt(keyValue);
normText += replaceValue;
}
return normText;
}
}
Then I have the tester method it where i am having the actual issue of the input exception error
import java.util.Scanner;
public class CaesarShiftTester
{
public static void main(String args[])
{
//import of the scanner method to ask the user for the input they would like
Scanner in = new Scanner(System.in);
System.out.println("What is the text you would like to do something with?");
String normText = in.next();
System.out.println("What is the Caesar Shift Value?");
int caesarShift = in.nextInt();
//new declaration of the CaesarShift class to report back to easily
CaesarShift shift = new CaesarShift();
//decalre the need properties for the encryption
String cipherText = shift.encryptionMethod(normText, caesarShift);
System.out.println("Your normal text is: " + normText);
System.out.println("Your text after encryption is: " + cipherText);
String cnormText = shift.decryptionMethod(cipherText, caesarShift);
System.out.println("Your encrypted text is: " + cipherText);
System.out.println("Your decrypte text is: " + cnormText);
}
}
Sorry for the somewhat messy code, I typically do clean up when a program is done and working.
Your program should work OK if you input only 1 word. If you include spaces, exception appears. The problem is on line
String normText = in.next();
It should be
String normText = in.nextLine();
to get the whole line as input text. next() doesn't work as you expected because
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace.
So it matched only the first word and tried to parse the next word as an int (because of your next line int caesarShift = in.nextInt();)
Some other points:
in your encryption/decryption methods, you should check if the input char is a letter (e.g. using Character.isLetter()) and shift only those chars (currently, it won't find space in ALPHABET so indexOf returns -1)
using StringBuilder when concatenating Strings in a loop, it's faster

Categories

Resources