In my java code the line String st = sc.nextLine(); is not taking input when the code is running and when instead I use sc.next(); the code works properly can you please tell me why sc.nextLine(); is not working
import java.lang.*;
import java.util.*;
/**?Chef wrote some text on a piece of paper and now he wants to know how
many holes are in the text. What is a hole? If you think of the paper as
the plane and a letter as a curve on the plane, then each letter divides
the plane into regions.For example letters "A", "D", "O", "P","R" divide
the plane into two regions so we say these letters each have one hole.
Similarly, letter "B" has 2 holes and letters such as "C", "E", "F","K"
have no holes. We say that the number of holes in the text is equal to
the total number of holes in the letters of the text.
Help Chef to determine how many holes are in the text.
Input
First line contains a single integer T <= 40, the number of test cases.
T test cases follow. The only line of each test case contains a non-empty
text composed only of uppercase letters of English alphabet. The length
of the text is less then 100. There are no any spaces in the input.
Output
For each test case,output a single line containing number of holes in the corresponding txt
Example
Input:
2
CODECHEF
DRINKEATCODE
Output:
2
5
*/
class Holes {
public static void main(String[] args) {
int i, Testcase;
int holes, space = 0, j;
Scanner sc = new Scanner(System.in);
Testcase = sc.nextInt();
for (i = 0; i < Testcase; i++) {
holes = 0;
space = 0;
String st = sc.nextLine();
if (st.length() < 100) {
char[] letter = st.toCharArray();
for (j = 0; j < st.length(); j++) {
if (letter[j] == ' ') {
space++;
}
}
for (j = 0; j < st.length(); j++) {
if (space == 0) {
if (letter[j] == 'A' || letter[j] == 'D'
|| letter[j] == 'O' || letter[j] == 'P'
|| letter[j] == 'R') {
holes = holes + 1;
}
if (letter[j] == 'B') {
holes = holes + 2;
}
}
}
}
if (st == st.toUpperCase() && space == 0) {
System.out.println(holes);
}
}
}
}
As Nighthacks mentioned, Scanner.nextInt will not advance to the next input (Read https://stackoverflow.com/a/13102066/643500)
Try it this way:
public class Holes {
public static void main(String[] args) {
int holes;
Scanner sc = new Scanner(System.in);
int numberOfCases = sc.nextInt(); // Get input as int - not going to
// advance
String[] testCases = new String[numberOfCases];
String line = sc.nextLine(); // Move to next
for (int i = 0; i < numberOfCases; i++) {
line = sc.nextLine();// Read input as line
testCases[i] = line;
}
sc.close();
for (String aCase : testCases) {
holes = 0;
if (aCase.length() < 100 && !aCase.contains(" ")) {
for (int j = 0; j < aCase.length(); j++) {
char letter = aCase.charAt(j);
if (letter == 'A' || letter == 'D' || letter == 'O'
|| letter == 'P' || letter == 'R') {
holes++;
}
if (letter == 'B') {
holes = holes + 2;
}
}
System.out.println(holes);
}
}
}
}
That's because the [Scanner#nextInt] method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine
Workaround:
Either fire a blank Scanner#nextLine call after Scanner#nextInt to consume rest of that line including newline
Check this out.
Related
Write a program that will read a line of text String and display all the letters that occur in the text, one per line and in alphabetical order, along with the number of times each letter occurs in the text.
For this purpose, you must use an array of type int of length 26, so that the element at index 0 contains the number of a’s, the element at index 1 contains the number of b’s, and so forth.
Allow both uppercase and lowercase letters as input, but treat uppercase and lowercase versions of the same letter as being equal.
Hint: Use the method chatAt(int index) in the String class to get the individual character in a string at the specified index.
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] letters = new int[26];
char choice;
while (true) {
// taking user input
System.out.println("Please enter text ending with period:");
String text = sc.nextLine();
// converting it lowercase
text = getActualText(text).toLowerCase();
char c = 'a';
for (int i = 0; i < letters.length; i++)
// increasing character by 1
letters[i] = countLetters(text, c++);
System.out.println("\nThe frequency of the letters");
c = 'a';
for (int i = 0; i < letters.length; i++) {
// showing only those letters whose frequnecy is greater than 0
if (letters[i] != 0)
System.out.println(c + ": " + letters[i]);
c++;
}
System.out.print("Would you like to try another text?(Y/N) ");
choice = sc.nextLine().charAt(0);
if (choice == 'n' || choice == 'N')
break;
}
}
private static int countLetters(String text, char c) {
int count = 0;
for (int i = 0; i < text.length(); i++)
// counting the frequency
if (text.charAt(i) == c)
count++;
return count;
}
/**
* This method will extract the first sentence from a text ending with full stop(.)
*/
private static String getActualText(String text) {
String newText = "";
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '.')
// breaking out of the loop if the full stop is found
break;
// adding it to the text
newText += text.charAt(i) + "";
}
return newText;
}
}
Try to change existing condition to below new condition:
Existing Condition: (Allowing frequencies which are not equal to 0):
if(letters[i] != 0) {//showing only those letters whose frequency is greater than 0
New Condition: (Allowing frequencies which are greater than or equal to 0):
if(letters[i] >= 0) {
It's enough to go through the text one time and count the occurrence of each letter. And then just show only letters with count >0.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
do {
System.out.print("\nEnter the text: ");
String str = scan.nextLine();
print(histogram(str));
} while (shouldContinue(scan));
}
private static int[] histogram(String str) {
int[] letters = new int[26];
for (int i = 0; i < str.length(); i++)
if (Character.isLetter(str.charAt(i)))
letters[Character.toLowerCase(str.charAt(i)) - 'a']++;
return letters;
}
private static void print(int[] letters) {
System.out.println("The frequency of the letters:");
for (int i = 0; i < letters.length; i++)
if (letters[i] > 0)
System.out.println((char)('a' + i) + ": " + letters[i]);
}
private static boolean shouldContinue(Scanner scan) {
while (true) {
System.out.print("Would you like to try another text (Y/N)? ");
String str = scan.nextLine();
if (str.length() != 1)
continue;
if ("Y".equalsIgnoreCase(str))
return true;
if ("N".equalsIgnoreCase(str))
return false;
}
}
My code works except I have to make it pass some Junit test. It passes all but one. It passes when the character enters nothing, enters upper case, lower case, or a mix of the two, and it works when the enter Hello World!
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] textArray = new int[26];
System.out.print("Enter text: ");
readText(input, textArray);
}
public static void readText(Scanner input, int[]text){
char letter = 0;
if (input.hasNext() == false) {
System.out.println();
}
else {
while (input.hasNext()) {
String a = input.nextLine();
for (int i = 0; i < a.length(); i++) {
letter = a.charAt(i);
if (letter >= 'A' && letter <= 'Z') {
text[letter-65] = (text[letter-65]) + 1;
}
else if (letter >= 'a' && letter <= 'z') {
text[(letter - 32) - 65] = (text[(letter - 32) - 65]) + 1;
}
else if (letter == ' ') {
System.out.print("");
}
else {
System.out.print("");
}
}
}
}
String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for (int y = 0; y < text.length; y++) {
if (text[y] > 0) {
System.out.println(alphabet[y] + ": " + text[y]);
}
}
}
The Junit tests this input: 1 2 3%n! ? >%n:) !!%n
The expected output is
Enter text:
//empty line here
But instead the output from my code is
Enter text: //with no line after
I'm not sure how to get the extra line after without ruining my other junit tests. I tried one way and it worked but then my Hello World didn't work properly.
And example of when its working:
When I hit run the console will say
Enter text:
I have a Scanner input so the user will enter some words and it will look like this in console
Enter text: sOme wordS
Then it will count the number of times each letter was used and print that to console like this
Enter text: sOme wordS
D: 1
E: 1
M: 1
O: 2
R: 1
S: 2
W: 1
If I don't enter anything when asked and just hit the enter key the output is
Enter text:
//empty line here
But when I enter
Enter text: 1 2 3
? ! >
:) !!
The output doesn't add an extra line at the end.
Try using System.out.println("Enter text: "); instead of System.out.print("Enter text: ");
Update: After getting clarified your requirement I propose to use the following code.
public static void readText(Scanner input, int[]text){
char letter = 0;
while (input.hasNext()) {
String a = input.nextLine();
for (int i = 0; i < a.length(); i++) {
letter = a.charAt(i);
if (letter >= 'A' && letter <= 'Z') {
text[letter-65] = (text[letter-65]) + 1;
}
else if (letter >= 'a' && letter <= 'z') {
text[(letter - 32) - 65] = (text[(letter - 32) - 65]) + 1;
}
else if (letter == ' ') {
System.out.print("");
}
else {
System.out.print("");
}
}
}
String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
boolean emptyOutput = true;
for (int y = 0; y < text.length; y++) {
if (text[y] > 0) {
System.out.println(alphabet[y] + ": " + text[y]);
emptyOutput = false;
}
}
if (emptyOutput) {
System.out.println();
}
}
I am learning Java on my own and practicing using online exercises. I have only learned up until methods thus far so using an array for this exercise is beyond my scope, even though several solutions online use arrays to do what I want.
The exercise is this: Have the user enter a string with vowels. Wherever there is a vowel letter, display that vowel as a capital letter.
Example: If the user enters "apples", the correct output is ApplEs
I have this code so far:
import java.util.Scanner;
public class CapitalizeVowels {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string ~ ");
String string = keyboard.nextLine();
for (int i = 0; i < string.length(); i++) {
System.out.print(string.charAt(i));
if (string.charAt(i) == 'a' ||
string.charAt(i) == 'e' ||
string.charAt(i) == 'i' ||
string.charAt(i) == 'o' ||
string.charAt(i) == 'u') {
char upperCaseVowel = Character.toUpperCase(string.charAt(i));
System.out.print(upperCaseVowel);
// need to replace string.charAt(i) with upperCaseVowel
// find something to replace characters
}
}
}
}
When I run my code as it is, with the input string "apples", for example, I get "aAppleEs" as my output. Both the lower case vowels and the upper case vowels are being printed. I am thinking that I should replace string.charAt(i) which is the lower case vowel with upperCaseVowel but I can't find any replace() method or something to that effect for characters. I tried other things like StringBuilder, etc. but I haven't come across a solution that is simple enough to avoid arrays as I didn't learn them yet. Any help on how I can get to the proper output is highly appreciated. Thanks!
Your mistake is printing every character before testing if it's a vowel.
Instead, print each char after you've figured out what it should be. The body of your loop should be:
char next = string.charAt(i);
if (next == 'a' ||
next == 'e' ||
next == 'i' ||
next == 'o' ||
next == 'u') {
next = Character.toUpperCase(next);
}
System.out.print(next);
You may consider adding:
else {
next = Character.toLowerCase(next);
}
To enforce non vowels being lower case.
You just need to move the Sysout prior to if statement to else, to avoid printing same character twice, e.g.:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string ~ ");
String string = keyboard.nextLine();
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == 'a' || string.charAt(i) == 'e' || string.charAt(i) == 'i' || string.charAt(i) == 'o'
|| string.charAt(i) == 'u') {
char upperCaseVowel = Character.toUpperCase(string.charAt(i));
System.out.print(upperCaseVowel);
// need to replace string.charAt(i) with upperCaseVowel
// find something to replace characters
}else{
System.out.print(string.charAt(i));
}
}
}
Try this, it works for me.
class ReplaceVowel {
public static void main(String[] args) {
String words = "apples";
char converted = 0;
String w = null;
for (int i = 0; i < words.length(); i++) {
if (words.charAt(i) =='a'|| words.charAt(i)=='e'||words.charAt(i)=='i'||words.charAt(i)=='o'||words.charAt(i)=='u') {
converted = Character.toUpperCase(words.charAt(i));
w = words.replace(words.charAt(i), converted);
words = w;
} else {
converted = Character.toUpperCase(words.charAt(i));
w = words.replace(words.charAt(i), converted);
words = w;
}
}
System.out.println(words);
}
}
I have written the code for the first part, but it counts the number of vowels with repetitions included, but I also want to know how to count the number of vowels without repetitions.
Also I am struggling to write the second part of the code, that is, report the sum of vowels.
Here's what I have written so far:
import java.io.*;
public class CountVowel {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string:");
String s = br.readLine();
int l = s.length();
char ch;
int i;
int count = 0;
for(i = 0; i < l; i++)
{
ch = s.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
count=count+1;
}
}
System.out.println("The number of vowels are:"+count);
}
}
Simply, you try with Set interface that not stores any duplicates, use following code,
public static void main(String[] args) throws IOException {
Set<Character> set = new HashSet<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string:");
String s = br.readLine();
int l = s.length();
char ch;
int i;
int count = 0;
for (i = 0; i < l; i++) {
ch = s.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
set.add(ch);
}
}
System.out.println("The number of vowels are:" + set.size());
}
There is a neater way to do this:
Set<Character> vowels = new HashSet<Character>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
for(i=0;i<l;i++) {
ch=s.charAt(i);
vowels.remove(ch);
}
System.out.println("The number of vowels are:" + 5-vowels.size());
I suggest to do it like this. This will output the number of vowels as you want without repetition:
int count = 0;
boolean[] vowel = {false, false, false, false, false};
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
for(int i=0;i<l;i++) { //This will traverse every letter for the string
ch=s.charAt(i);
for(int j=0; j<5; j++) { //This will search through vowels
//Ff any vowels are matched the count will increase,
//But if they are already matched, count will not increase
if(ch==vowels[j] && !vowel[j]) {
count++;
vowel[j] = true;
}
}
}
System.out.println("The number of vowels are:" + count);
Here is a alternate approach using two arraylists. One contains vowels and other one is empty say charsInString. We can add into the other one if we encounter an vowel which is not present in the charsInString. We can find whether an vowel has been added by using indexOf
List<Character> chars = new ArrayList<Character>(Arrays.asList('a','e','i','o','u'));
List<Character> charsInString = new ArrayList<Character>();
String test = "this is a test string";
for (char a: test.toCharArray()) {
if (chars.indexOf(a) > -1) {
if (charsInString.indexOf(a) == -1) {
charsInString.add(a);
}
}
}
System.out.println(charsInString.size()); //answer is 3
Demo
Im trying to turn a string taken from the user into Pig Latin. I cannot use any special classes, methods, or arrays. I can only use a Scanner to create a object to take the string from the user and .length and .charAt, in addition to any type of looping. (Also cannot use switch statements or the break keyword)
Here is an example of what my output is suppose to be:
Enter a line of text: this is a test.
Input : this is a line of text.
Output: his-tay is-way a-way ine-lay of-way ext-tay.
Here is my code, I can only get my code to work with one word and it must have a space at the end. Only one loop works at a time depending on the loop. Im not sure what to do if I get an entire String.
I know that when the user enters a space that signals a new word, and when they enter a period, that signals the ending.
I had a hard time understanding your code. (It looks like you are trying to do it two ways at once?) Regardless, I believe I was able to understand your question. Here is a compilable and runnable example:
import java.util.Scanner;
public class PigLatin
{
public static void main(String[] args)
{
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
if (text != null && text.length() > 0)
{
int i = 0;
// this iterates through the whole string, stopping at a period or
// the end of the string, whichever is closer
while (i < text.length() && text.charAt(i) != '.')
{
// these three variables only exist in this code block,
// so they will be re-initialized to these values
// each time this while loop is executed
char first = '\0'; // don't worry about this, I just use this value as a default initializer
boolean isFirst = true;
boolean firstIsVowel = false;
// each iteration of this while loop should be a word, since it
// stops iterating when a space is encountered
while (i < text.length()
&& text.charAt(i) != ' '
&& text.charAt(i) != '.')
{
// this is the first letter in this word
if (isFirst)
{
first = text.charAt(i);
// deal with words starting in vowels
if (first == 'a' || first == 'A' || first == 'e' || first == 'E'
|| first == 'i' || first == 'I' || first == 'o' || first == 'O'
|| first == 'u' || first == 'U')
{
System.out.print(first);
firstIsVowel = true;
}
// make sure we don't read another character as the first
// character in this word
isFirst = false;
}
else
{
System.out.print(text.charAt(i));
}
i++;
}
if (firstIsVowel)
{
System.out.print("-tay ");
}
else if (first != '\0')
{
System.out.print("-" + first + "ay ");
}
i++;
}
System.out.print('\n'); //for clean otuput
}
}
}
There are a few comments in there that might help guide you through my logic. This is almost definitely not the most efficient way to do this (even with your limitations), as I only whipped it up as a example of the type of logic you could use.
You could break it up into words, then process the current word when you hit a space or period:
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
String curWord = "";
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ' || text.charAt(i) == '.') {
if (curWord.charAt(0) == 'a' || curWord.charAt(0) == 'e' ||
curWord.charAt(0) == 'i' || curWord.charAt(0) == 'o' ||
curWord.charAt(0) == 'u') {
System.out.print(curWord + "-way ");
} else {
for (int j = 1; j < curWord.length(); j++) {
System.out.print(curWord.charAt(j);
}
System.out.print("-" + curWord.charAt(0) + "ay ");
//System.out.print(curWord.substring(1)+"-"+curWord.charAt(0)+"ay ");
}
curWord = "";
} else {
curWord += text.charAt(i);
}
}