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 months ago.
Improve this question
I'm starting to code and trying to do a challenge of turning a sentence into camelCase. After some experimenting on my own, got to the following code:
package teste;
import java.util.Scanner;
public class Teste {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Insert the sentence to be turned into camelCase: ");
String entry = keyboard.nextLine();
System.out.print("Insert the character that is used as space: ");
String space = keyboard.nextLine();
char current;
char next;
String output = null;
for (int i=0; i<=entry.length(); i++){
current = entry.charAt(i);
next = entry.charAt(i+1);
if (i == entry.length()){
output += Character.toLowerCase(current);
} else if (entry.substring(i, i+1).equals(space)){
output += Character.toUpperCase(next);
i++;
} else {
output += Character.toLowerCase(current);
}
}
System.out.println("This sentence in camelCase is: " + output);
}
}
There is an error I can't seem to avoid with the last index of the input, even with the first if structure made especially for it, and I can't find out why. Could anyone explain to me what I did wrong?
you should avoid StringIndexOutOfBoundsException exception in line 15 "entry.charAt(i+1)",
This code will fix your error.
import java.util.Scanner;
public class Teste {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Insert the sentence to be turned into
camelCase: ");
String entry = keyboard.nextLine();
System.out.print("Insert the character that is used as
space: ");
String space = keyboard.nextLine();
char current;
char next;
String output = "";
for (int i=0; i<entry.length()-1; i++){
current = entry.charAt(i);
next = entry.charAt(i+1);
if (i == entry.length()-2){
output += Character.toLowerCase(current);
} else if (entry.substring(i, i+1).equals(space)){
output += Character.toUpperCase(next);
i++;
} else {
output += Character.toLowerCase(current);
}
}
//here we test the last character
int len=entry.length();
current = entry.charAt(len-1);
if(!entry.substring(len-1, len).equals(space)){
output += Character.toLowerCase(current);
}
System.out.println("This sentence in camelCase is: " +
output);
}
}
Related
So I've tried adding count ++ in multiple places in my code along with researching some way to allow multiple inputs to no avail. Am I missing something on placement or would I need to rewrite the code entirely for what I am wanting to accomplish? Is this not a boolean match situation? Very lost and sorry if this is a noob question. Appreciate the input.
Scanner scanner = new Scanner(System.in);
System.out.println("Insert any State Capital");
String currentInput = scanner.nextLine();
boolean match = false;
String [] capitals = stateCapitals[1];
for (String capital:capitals) {
if (capital.equalsIgnoreCase(currentInput)) {
match = true;
break;
}
}
if (match) {
System.out.println ("Correct");
}
else
System.out.println ("incorrect");
}
}
Problem and what I've tried is above. Also, apologies on formatting if it's messed up. First time using stack overflow.
Please see the below code and let me know if this solves your issue.
import java.util.Scanner;
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
ArrayList<String> inputList = new ArrayList<>();
ArrayList<String> capitalList = new ArrayList<>(List.of("Delhi","Kabul","Dhaka"));
for (int i = 0; i < 5; i++)
{
String currentInput = scanner.nextLine();
inputList.add(currentInput);
}
int correct_response_count = 0;
int wrong_response_count = 0;
for (int i = 0; i < inputList.size(); i++)
{
if (capitalList.contains(inputList.get(i)))
{
correct_response_count++;
}
else
{
wrong_response_count++;
}
}
System.out.println("The correct count of answers is: " + correct_response_count);
System.out.println("The wrong count of answers is: " + wrong_response_count);
}
}
Input
India
Delhi
Australia
Kabul
Bangladesh
Output
The correct count of answers is: 2
The wrong count of answers is: 3
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 taking an Java Introduction class and we have a project that deals with a hangman game. I have most of the all code worked out but there is a way to simplify the code.
In my code below, the program will output a message for every round (max 3 round) then using game.nextRound() it set will a word using variable named word1, word2, word3. This variable will be called in sequence in descending order.
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
String word1 = "ruby";
String word2 = "python";
String word3 = "swift";
Scanner kb = new Scanner(System.in);
Hangman game = new Hangman();
System.out.println("Let's play a round of hangman.");
System.out.println("We are playing hangman");
game.nextRound(word1);
while (true) {
System.out.println("");
System.out.println("The disguised word is " + game.disguised());
System.out.println("Guess a letter:");
char guess = kb.next().charAt(0);
boolean isFound = game.guessLetter(guess);
if (isFound) {
game.result();
if (game.disguised().equals(game.secret())) {
game.found();
break;
}
} else {
game.result();
}
}
System.out.println("");
System.out.println("Let's play a second round of hangman.");
System.out.println("We are playing hangman");
game.nextRound(word2);
....
....
....
Hangman.java
public String disguised() {
return disguisedWord;
}
You can do the following :
-Put the Strings word1, word2, and word3 in an array of type String.
Let's say
String[] words = {"ruby", "python", "swift"};
-Initialize an int counter set to 0.
int c = 0;
-Add game.nextRound(words[c++]); inside your if and else statements in the while loop.
You can use ArrayList, and also use counter to indicate the number of the game.
public class Game {
public static void main(String[] args) {
int count = 1;
List<String> words = new ArrayList<>();
words.add("ruby");
words.add("python");
words.add("swift");
for (String word : words) {
System.out.println("Let's play a round of " + count + "hangman.");
System.out.println("We are playing hangman");
Hangman game = new Hangman();
game.nextRound(word);
while (true) {
System.out.println("");
System.out.println("The disguised word is " + game.disguised());
System.out.println("Guess a letter:");
char guess = kb.next().charAt(0);
boolean isFound = game.guessLetter(guess);
if (isFound) {
game.result();
if (game.disguised().equals(game.secret())) {
game.found();
break;
}
} else {
game.result();
}
}
count++;
}
}
}
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 5 years ago.
Improve this question
I'm having a hard time learning java and I was hoping to get some type of help on doing this. I'm trying to get the user to input a word and have the system check to see if its a palindrome. I've taken some code from others to get some help but I'm getting stuck.
import java.util.Scanner;
class PalidromeTester
{
public static boolean isPalindrome (String[] word) {
for (int i=0; i< word.length; i++) {
if (!word[i].equals( word[word.length-1-i])){
return false;
}
}
return true;
// read word
public static String readWord(Scanner input){
String word = input.nextLine();
word = word.toLowerCase();
return word;
}
// display results to the screen
public static void displayResults(boolean result){
// display the results
String msg = "\nThat string ";
msg += (result == true) ? " IS " : " is NOT ";
msg += " a palindrome.\n";
System.out.println(msg);
}
// main function
public static void main(String[] args){
// input scanner
System.out.print('\u000C');
System.out.println("Enter the word: ");
Scanner input = new Scanner(System.in);
PalidromeTester.readWord(input);
}
}
Assuming your need, I think this is what you need. I have commented the changes done in the code itself to point out to you why the changes were done in the first place. Also remember there are multiple ways to approach a problem, this is merely just one of those possibilities. Feel free to innovate and add your own technique for solving this.
import java.util.Scanner;
public class Palindrome { //<-- added public to the class otherwise main method won't be called
public static boolean isPalindrome(String word) { //<--changed the String[] to String
for (int i = 0; i < word.length(); i++) {
if (!(word.charAt(i) == word.charAt(word.length() - 1 - i))) { //Since [] will not work on Strings, using charAt() to do the same thing
return false;
}
}
return true;
}
// read word
public static String readWord(Scanner input) {
String word = input.nextLine();
word = word.toLowerCase();
return word;
}
// display results to the screen
public static void displayResults(boolean result) {
// display the results
String msg = "\nThat string ";
msg += (result == true) ? " IS " : " is NOT ";
msg += " a palindrome.\n";
System.out.println(msg);
}
// main function
public static void main(String[] args) {
// input scanner
System.out.print('\u000C');
System.out.println("Enter the word: ");
String s = readWord(new Scanner(System.in)); //Added a call to the readWord method and also passed a Scanner reference to the method and
//storing the read word in String s
boolean result = isPalindrome(s); //Added a call to the palindrome method and also passing the read string s to the method to find whether
//it is palindrome or not and storing the method return value in boolean result variable
displayResults(result); //Finally calling the displayResults with the result we got from isPalindrome() to display the appropriate message
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
public class decisionMaker {
public static void main(String args[]) {
String option[] = new String[10];
// Output
for (int i = 0; i <= 9; i++) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the next option:");
option[i] = input.next();
System.out.println(" ");
}
for (int i = 0; i <= 9; i++) {
System.out.println("option: ");
System.out.println("option[i]+" ");
}
// Output
}
I'm trying to figure out how to add a count to the options, exit and end the program after entering a certain letter or number, and how to create a random output from the user input. I want it to give me one option that I had input at random. Can anyone help me with one or a few of these things. I'm trying to learn to code on my own, and I'm stuck on these.
Randomness
You can generate random numbers using java.util.Random;:
import java.util.Random;
public class SomeClass{
static Random rand = new Random();
public static void main(String args[]){
System.out.println(rand.nextInt());
}
}
About some broken code:
If you want to print out the value of a variable with System.out.println() then you need only type the variable without any quotation marks. The code you've written below will not compile:
System.out.println("option: ");
System.out.println("option[i]+" ");
Assuming that's what you want to do, it should instead be written as:
System.out.println("option: ");
System.out.println(option[i]);
Or even System.out.println("option: \n"+option[i]);
(The escape sequence \n when placed inside of quotation marks just indicates to the console to add a new line.)
Scanner:
Additionally, as nick zoum pointed out, your Scanner object should be initialized outside of the for loop, such as right underneath of the main() method.
Please comment below if you need clarification or if I misunderstood what you were looking for. It was very hard to understand your question.
You could try something like this:
public class DecisionMaker {
public static void main(String[] args) {
// output
Scanner scanner = new Scanner(System.in);
int size = getInt(scanner);
String option[] = new String[size];
for (int index = 0; index < size; index++) {
System.out.print("Enter the next option:");
option[index] = scanner.next();
}
int index = (int) (Math.random() * size);
System.out.println(option[index]);
scanner.close();
// output
}
public static int getInt(Scanner scanner) {
int size = 0;
while (size <= 0) {
if (scanner.hasNext()) {
if (scanner.hasNextInt()) {
size = scanner.nextInt();
}
}
if (size <= 0) {
System.out.println("The input: " + scanner.next() + " is not a valid value.");
}
}
return size;
}
}
How the program works:
The Scanner is initialized in the beginning and there is only
one instance of it.
Then the program will wait until the user inserts a valid number for
the size of options.
The next 5 lines were essentially copied from your code.
Finally we get a random Integer in the range of 0 - (size - 1) and print
the String of the array with that index.
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 8 years ago.
Improve this question
I have two approach to determine number of words in String, But the result is 1 forever!
public static void main(String[] args) {
System.out.println("Enter your String:");
String string = in.next();
System.out.println("Number of Words are:" + countWords(string));
System.out.println("Number of Words are:" + countWords2(string));
}
public static int countWords(String str) {
String[] splited2 = str.split(" ");
return splited2.length;
}
public static int countWords2(String str) {
String trimed = str.trim();
return trimed.split("\\s+").length;
}
Why?
Scanner#next() method, which is what I assume you are using, reads the next token, and by default it doesn't consider whitespaces as a part of token. So, it really reads the input till it finds the first whitespace.
So, your input contains just a single word, and hence the result. Try using Scanner#nextLine() method, and you will get the expected result.
Replace in.next() by scanner.nextLine() because next() will give you the next token not all the line
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:");
String sentence = scanner.nextLine();
System.out.println("Number of Words are:" + countWords(sentence));
Or you can use BufferedReader as it is faster in reading whole line
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String sentence = br.readLine();
System.out.println("Number of Words are:" + countWords(sentence));
I would suggest building a function like this:
public static int getWordCount(String string){
int counter = 0;
boolean wordFound = false;
int endOfLineIndex = s.length() - 1;
for (int i = 0; i < endOfLineIndex; i++) {
if (Character.isLetter(s.charAt(i)) == true)) {
wordFound = true;
} else if (Character.isLetter(string.charAt(i)) == false && wordFound == true) {
counter++;
wordFound = false;
} else if (Character.isLetter(string.charAt(i))) {
counter++;
}
}
return counter;
}
Hope I helped!