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've been writing a program that is supposed to count the occurrence of a letter in a String array. In order to do so I've made every input lower case, so that when the search for the specified letter is being done it is all done in lower case. The program works when the letter being searched for is inputted in lower case, but wont work when in upper case. I'm confused about this because I've used the toLowerCase() method to make the inputted letter lower case despite what is inputted. Any help would be greatly appreciated.
import java.util.Scanner;
public class RunStringArray
{
public static void main (String [] args){
int arrayLength;
int count = 0;
String word;
String letter;
int letterCount = 0;
int x = 0;
//Asks user for length of array
Scanner kbInput = new Scanner(System.in);
System.out.println("Enter a positive integer");
arrayLength = kbInput.nextInt();
//Makes sure array length is a valid number
while (arrayLength <= 0){
System.out.println("Invalid input (not positive)");
System.out.println("Enter a positive integer");
arrayLength = kbInput.nextInt();
}
//Creates array of the user specified length
String words [] = new String [arrayLength];
//Asks user to input all strings in the array and makes them lower case.
kbInput.nextLine();
while (count < words.length){
System.out.println("Enter a string");
word = kbInput.nextLine();
word = word.toLowerCase();
words[count] = word;
count++;
}
//Asks user what letter he/she wants to count in the array
System.out.println("What letter do you want to count?");
letter = kbInput.nextLine();
letter.toLowerCase();
//Error trap making sure the user inputs a letter.
while (letter.length() > 1){
System.out.println("Invalid input (not a letter)");
System.out.println("What latter do you want to count?");
letter=kbInput.nextLine();
letter.toLowerCase();
}
char c = letter.charAt(0);
//While loop which will count the occurrence of the letter in each
//string in the array, and then adds all of the occurrences together
//in order to find the total occurrences of the letter.
while (count > 0){
letterCount = RunStringArray.count(words[count-1], c);
x += letterCount;
count--;
}
System.out.println(x);
} //End of main
private static int count (String str, char searchLetter){
int occurrences = 0;
for (int k = 0; k < str.length(); k++){
if (str.charAt(k) == searchLetter)
{
occurrences++;
} //End of if
} //End of for loop
return occurrences;
} //End of method
} //End of class
You are not storing the output of letter.toLowerCase().
Change
letter.toLowerCase();
to
letter = letter.toLowerCase();
Methods that are executed on Strings, Integers, Long etc will produce new objects. Thats why you need to assign those values. The reason: Strings and all those types are immutable, you cannot change its value, when you do java creates new object.
letter = kbInput.nextLine().toLowerCase();
Related
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 10 months ago.
Improve this question
EDIT: instead of any loops, i know this kind of statement needs a while loop but I was required to use only the If-else statement.
Im trying to find the largest digit in an inputted number and all examples i can see are using while and im a bit troubled in coding it using if else. this is my sample JAVA code:
Scanner cs1 = new Scanner (System.in);
System.out.println ("Input three digit number : ");
int num = cs1.nextInt ();
int reminder, Largest_number= 0;
while (num > 0)
{
reminder = num % 10;
if (Largest_number< reminder)
{
Largest_number= reminder;
}
num = num / 10;
}
System.out.println("\nOutput : "+Largest_number);
cs1.close();
}
}
You can loop through that number without loop.
public static void main(String[] args) {
Scanner cs1 = new Scanner(System.in);
System.out.println("Input three digit number : ");
int num = cs1.nextInt();
int largestNumber = 0;
System.out.println("\nOutput : " + getLargestNumber(Math.abs(num), largestNumber));
cs1.close();
}
static int getLargestNumber(int num, int largestNumber){
if (num>0){
int reminder = num % 10;
if (largestNumber < reminder) {
largestNumber= reminder;
}
num = num/10;
largestNumber = getLargestNumber(num, largestNumber);
}
return largestNumber;
}
What I am doing here is basically I am mimicing standard for or while loops with a thing called recursion.
From GeeksforGeeks:
What is Recursion? The process in which a function calls itself
directly or indirectly is called recursion and the corresponding
function is called as recursive function.
So I'm recursively calling static method getLargestNumber(int num, int largest_number) until I reach the moment when I do not enter if (num>0) statement.
And since calling of getLargestNumber is happening inside of that if statement, then the recursion stops, and I get the final result back.
UPDATE
You algorithm is wrong. You need to pass Absolute value of entered integer. Otherwise you algorithm will give wrong answer if you pass negative value as input.
Changed num to Math.abs(num).
This is a solution without any kind of loop but only if there is guaranteed to have as input 3-digit numbers.
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner cs1 = new Scanner (System.in);
System.out.print("Input three digit number: ");
String threeDigitNum = cs1.next();
int largestNum, tmpNum;
// assuming 1st digit is the largest
largestNum = threeDigitNum.charAt(0) - '0';
// checking if 2nd digit is greater than 1st
tmpNum = threeDigitNum.charAt(1) - '0';
if( tmpNum > largestNum )
largestNum = tmpNum;
// checking if 3nd digit is greater than 1st or 2nd
tmpNum = threeDigitNum.charAt(2) - '0';
if( tmpNum > largestNum )
largestNum = tmpNum;
System.out.println("\nOutput : "+largestNum);
cs1.close();
}
}
Note:
Any char is reprsented as an integer value, and that is what charAt() method returns. So from it subtracting the chrachter '0' (represented by it's integer value) it gives as a result the integer equivalent of that value. In case of digits, for example '8' - '0' will result in integer value 8.
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 2 years ago.
Improve this question
package com.jetbrains;
import java.util.Objects;
import java.util.Scanner;
public class SA {
public static void main(String[] args) {
//scanner object
Scanner input = new Scanner(System.in);
//comment
System.out.println("Please enter a line of text below:");
String letters = input.nextLine(); //User's string input
if (letters.length() < 7) {
System.out.println("The input is too short.");
}
//variables
int l = letters.length()-5; //where the last 5 characters are located in user's input string
String answer = letters.substring(l) + letters.substring(2,l) + letters.substring(0, 2); // first 2 & last 5 swapped
if (letters.length() > 7) {
System.out.println("Convert to upper cases:");
System.out.println(letters.toUpperCase());
System.out.println("Swap the first 2 characters with the last 5 characters:"); // Swap
System.out.println(answer);
System.out.println("Is it a palindrome?");
for (int i = (letters.length() - 1); i >= 0; i--) {
char backwards = (letters.charAt(i));
for (int n = letters.indexOf(0); n >= 0; n++) {
char forwards = (letters.charAt(n));
if (Objects.equals(forwards, backwards)) {
System.out.println("True");
else
System.out.println("False");
}
}
}
}
}
}
I've tried comparing my user's input by making the for-loop outputs into char variables but it always returns false. I'm not sure how to fix this last bit, I've tried doing other things but I am completely stumped. My class hasn't learned StringBuilder or StringBuffer so I cannot use them in my code. Any tips or hints would be very helpful, thank you.
I have modified your code little bit to get the correct result -
import java.util.Scanner;
public class StringAnalysis {
public static void main(String[] args) {
//Create scanner object
Scanner input = new Scanner(System.in);
//Comment to the user
System.out.println("Please enter a line of text below:");
String letters = input.nextLine(); //User's string input
if (letters.length() < 7) {
System.out.println("The input is too short. No analysis to be performed.");
}
//variables
int l = letters.length() - 5; //States the index number of where the last 5 characters are located in user's input string
String answer = letters.substring(l) + letters.substring(2, l) + letters.substring(0, 2); // first 2 & last 5 swapped
if (letters.length() > 7) {
System.out.println("Analysis #1: Convert to upper cases:"); // Upper case
System.out.println(letters.toUpperCase());
System.out.println("Analysis #2: Swap the first 2 characters with the last 5 characters:"); // Swapping
System.out.println(answer);
System.out.println("Analysis #3: Is it a palindrome?");
String backwards = "";
for (int i = (letters.length() - 1); i >= 0; i--) {
backwards = backwards + letters.charAt(i);
}
if(letters.equalsIgnoreCase(backwards)) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
}
You have a problem on the second loop for checking palindrome , i tried to solve it , but eventhough , it compares every backward letters to all forwards which is logically wrong , here is something better you can do :
System.out.println("Analysis #3: Is it a palindrome?");
boolean response = true;
for (int i = 0 ; i < letters.length() ; i++) {
String backwards = String.valueOf(letters.charAt(i));
String forwards = String.valueOf(letters.charAt(letters.length()-i-1));
if(!backwards.equals(forwards)) {
response = false;
}
}
System.out.println(response);
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 2 years ago.
Improve this question
How would you output the word between the characters that the user inputs, for example, the input is 4(option #), dog *is* sleeping (phrase), *(character)
The output should be is. This task has to be done only using the substring method and no loops or anything else.
Here's my code:
else if (option == 4){
String x = keyboard.next();
int counter = 0;
sub = phrase.substring(0, phrase.length());
if (sub == x)
counter++;
else if (counter == 1)
System.out.print(sub);
}
I achieved this task using the for loop but now I only want to use substring method, I will show u the code using for loop so u get a better idea:
else if (option == 4){
char x = keyboard.next().charAt(0);
int z = 0;
for (int y = 0; y < phrase.length(); y++){
char n = phrase.charAt(y);
if (n == x)
z++;
else if (z == 1)
System.out.print(n);
}
}
There are two versions of substring. The first one requires one index and the second one requires two indices. I've used the one which requires two indices, the first index (inclusive) is for start and the second index (exclusive) is for end.
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 4) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
System.out.print("Enter character: ");
String letter = keyboard.nextLine();
int index1 = phrase.indexOf(letter);
int index2 = phrase.indexOf(letter, index1 + 1);
System.out.println("The required word is '" + phrase.substring(index1 + 1, index2) + "'");
}
}
}
A sample run:
Enter option: 4
Enter phrase: dog *is* sleeping
Enter character: *
The required word is 'is'
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 3 years ago.
Improve this question
I was going through a Palindrome( Specifically String Palindrome) Problem and was checking whether the string is palindrome or not. But a problem struck in the program
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int n,flag=0;
n=sc.nextInt();
char a[]=new char[n];
int l=0;
int h=n-1;
while(l<h)
{
if(a[l++]!=a[h--])
{
flag=1;
}
}
if(flag==1)
{
System.out.println("String is not Palindrome");
}
else{
System.out.println("String is Palindrome");
}
}
So above is the code which I wrote but the problem is, I have created a character array instead of the string.
The main point of the argument is the above code correct in terms of code standards.
is the above code correct in terms of code standards
Not really:
Don't name a local variable l (lowercase L). It is too easy to confuse with 1 (one).
Since I don't know what h is supposed to be a shorthand for, I changed l and h to i and j below, as those are very common integer iterator variable names.
Don't declare a local variable before it's needed. Use int n = sc.nextInt();
Don't put array declaration on the variable name. Put it on the type, since it defines the type.
Don't use 0 / 1 for false / true values. Change flag to a boolean, and name it better, e.g. describe its value. notPalindrome seems appropriate here. It helps document the code.
The while loop should be a for loop. It helps keeping loop logic together, and isolated from other logic, and it helps limit the scope of the loop variable(s).
Those were my comments related to coding standards.
However, your code doesn't work, because you never get a string from the user. Your choice of using char[] is fine, but you need to change the logic for getting it. See code below for how to use toCharArray() to do that.
Also, once a difference is found, you should exit the loop, either by also checking the boolean variable in the loop condition, or by using break. Personally, I prefer break.
Scanner sc = new Scanner(System.in);
String sentence = sc.nextLine();
char[] a = sentence.toCharArray();
boolean notPalindrome = false;
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
if (a[i] != a[j]) {
notPalindrome = true;
break;
}
}
if (notPalindrome) {
System.out.println("String is not Palindrome");
} else {
System.out.println("String is Palindrome");
}
please use below code to check given String/number Palindrome or Not
public static void main(String args[]) {
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter String ");
original = in.nextLine();
int n = original.length();
for ( int index = n - 1; index >= 0; index-- ) {
reverse = reverse + original.charAt(index);
}
if (original.equals(reverse)) {
System.out.println("String is Palindrome");
} else {
System.out.println("String is not Palindrome");
}
}
So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.