vowel count in codeabbey - java

I'm working on the vowel counting problem at coedabbey, but my solution doesn't seem to be working. Here's what I'm doing:
import java.util.Scanner;
public class Solution {
private static Scanner input;
public static void main(final String[] args){
input = new Scanner(System.in);
int amount = input.nextInt();
for(int i = 0 ; i < amount ; i++){
int sum = 0;
String nowa = input.nextLine();
for(int j = 0; j < nowa.length() ; j++){
char x = nowa.charAt(j);
if(x == 'a' || x == 'o' || x == 'u' || x == 'i' || x == 'e' || x == 'y'){
++sum;
}
}
System.out.println(sum+ " ");
}
}
}
But it does not do the right number of lines, and always outputs 0 for the count for a line after I enter the input. After that it does one fewer line than I expected.
An example run might look as follows:
> java Solution
> 3
0
> hello
2
> george
3
But, I wanted to enter another line because I said "3" at the beginning.

Skip a line after nextInt() as it doesnt consumes whole line it consumes only token
int amount = input.nextInt();
input.nextLine();
Demo

Instead of String nowa = input.nextLine(); try String nowa = input.next();.

Related

Limit number of input lines in Java?

I have a problem where I want to take input from the user, the user can insert 1 and up to 8 lines, and each line represents a case.
What I want is to stop the scanner when the user inserts 8 lines, Or if the user wants less than 8 he can press enter or a specific key to end the loop.
What I have done so far:
public static void doSomthing(){
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) { // here I want to check so that it don't exeed 8 lines
int e;
int m;
i = input.nextInt();
j = input.nextInt();
int num = 0;
while (i != 0 || j != 0) {
num += 1;
e = (e + 1) % 100;
m = (m + 1) % 400;
}
System.out.println(num);
}
}
The input should be two numbers in each line, one for i and one for j.
Input:
0 0
100 300
99 399
0 200
Output should be:
C1: 0
C2: 100
C3: 1
C4: 200
Hope this explains my problem.
Thanks in advance!
As #Abhishek suggested, you can use a counter variable:
public static void doSomthing(){
Scanner input = new Scanner(System.in);
int linesParsed = 0;
while (linesParsed < 8 && input.hasNextLine()) {
// What are you using these variables for? You compute their
// values, but then you do not use them
int e;
int m;
// Where are these variables declared? It seems weird to have
// instance variables be named i and j
i = input.nextInt();
j = input.nextInt();
int num = 0;
// Unless i and j are being modified concurrently somewhere
// else in the code, this will result in an infinite loop
while (i != 0 || j != 0) {
num += 1;
e = (e + 1) % 100;
m = (m + 1) % 400;
}
System.out.println(num);
linesParsed++;
}
}

Java string manipulation x number of lines with y element

Easiest way to explain my problem is to give you an example. Lets say I have 2 values X and Y. I wan't to ask the user to enter X lines with Y elements and they should be only 0s and 1s and then enter that values in array.
Example
x=3 y=3
User input:
101
100
000
And then how to separate string to enter each value in different cell.
EDIT 1:
import java.util.Scanner;
public class RedVsGreen {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int x,y;
String line;
String[] lineVector = new String[3];
while ( lineVector.length !=2 || (Integer.parseInt(lineVector[0]) >= 1000 || Integer.parseInt(lineVector[0]) <= 1)
|| (Integer.parseInt(lineVector[1]) <= 1 || Integer.parseInt(lineVector[1]) >= 1000)){
System.out.print("Please enter x and y, comma separated (more than 1 and less than 1000):");
//read x,y
line = scanner.nextLine();
//separate all values by comma
lineVector = line.split("\\s*,\\s*");
}
//parsing the values to Integer
x = Integer.parseInt(lineVector[0]);
y = Integer.parseInt(lineVector[1]);
for (i = 0 ; i < x; i++){
}
//
// int[][] field = new int[x][y];
// for (int row = 0; row < field.length; row++) {
// System.out.println("");
// for (int col = 0; col < field[row].length; col++) {
// field[row][col] = 9; //dummy value
// System.out.print(field[row][col] + " ");
// }
// }
//
}
}
Receiving x and y
while ( lineVector.length !=2 ...)
Your while condition is too complicated, a do while format matches this problem much better since you are going to get the values at least once, and the code is more readable.
Also you could have used x instead of Integer.parseInt(lineVector[0]) (same for y) instead of repeating the process, this would have shortened the condition.
String line;
String[] lineVector;
int x = -1, y = -1;
do {
System.out.print("Please enter x and y, comma separated (more than 1 and less than 1000):");
line = scanner.nextLine();
lineVector = line.split("\\s*,\\s*");
if(lineVector.length != 2)
continue;
x = Integer.parseInt(lineVector[0]);
y = Integer.parseInt(lineVector[1]);
} while (!((x > 1 && x < 1000 && y > 1 && y < 1000)));
First of all I removed the initial value of lineVector as it is unnecessary to initialize it in this case (you needed to do it because of it being present in your while condition).
I initialized x and y to -1 (Any number not in our range would work) in order to make sure the do-while condition is fulfilled until proper values are offered for both of the numbers.
Function to check binary values
Create a function to check if string values are binary.
public static boolean isBinary(String s) {
for(int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if(c != '0' && c != '1')
return false;
}
return true;
}
Receive binaries
String[] binaries = new String[x];
System.out.println("Enter binaries with length " + y + " :");
//Get binaries
for(int i = 0; i < x; ++i) {
binaries[i] = scanner.nextLine();
while(!isBinary(binaries[i]) || binaries[i].length() != y) {
System.out.println("Invalid binary value. Re-enter new value:");
binaries[i] = scanner.nextLine();
}
}
Receive binary values and continue asking if invalid.
Filling the 2D array
int[][] field = new int[x][y];
for(int i = 0; i < x; ++i) {
System.out.println();
for(int j = 0; j < y; ++j) {
char c = binaries[i].charAt(j);
if(c == '0')
field[i][j] = 0;
else
field[i][j] = 1;
System.out.print(field[i][j] + " ");
}
}
Integer.parseInt is not necessary here as there are only two possible values (0 and 1)

Why I am getting a RUNTIME ERROR when using Scanner in JAVA

Question:
Find the number of D, C, B and A grades for the last test on informatics, where n students from a class have successfully passed the test.
In this task, we use a 5-point grading system and are interested only in passing grades: from 2 to 5. They correspond to the letter grades in the following way: 5 is for A, 4 is for B, 3 is for C and 2 is for D. The program gets number n as input and then gets the grades themselves: one by one.
The program should output four numbers in a single line: the number of D, C, B, and A grades respectively.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scan = new Scanner(System.in);
int numStudents = scan.nextInt();
int marks;
int gradeA = 0;
int gradeB = 0;
int gradeC = 0;
int gradeD = 0;
for (int i = 0; i <= numStudents; i++){
marks = scan.nextInt();
if(marks == 5){
gradeA++;
} else if (marks == 4){
gradeB++;
} else if (marks == 3){
gradeC++;
} else if (marks == 1){
gradeD++;
}
}
System.out.println(gradeD);
System.out.println(gradeC);
System.out.println(gradeB);
System.out.println(gradeA);
}
}
ERROR:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:17)
If you define numStudents as 5, then you should enter 6 (because of <= in your for loop)
for (int i = 0; i <= numStudents; i++){
This should be..
for (int i = 0; i < numStudents; i++){
When you enter 1 in stdin as first input, it will be numStudents. Now, you have to enter 2 inputs because of <=. So your stdin should be
1
2
3
Instead, better change <= to < in your code, so that you can enter 1 2
You get NoSuchElementException when you given only 1 2 in stdin with your code (with <=)
If there is no integer on the scanner, you will get this error. You have to put a condition. Try:
if(scan.hasNextInt()) {
marks = scan.nextInt();
}
I ran your code in editor fixing some minor issues in the loop and number of students check it worked fine with the input :
5
2 3 4 5 6
Here's the whole code block:
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
if(scan.hasNextInt() ){
int numStudents = scan.nextInt();
int marks;
int gradeA = 0;
int gradeB = 0;
int gradeC = 0;
int gradeD = 0;
for (int i = 0; i < numStudents; i++){
marks = scan.nextInt();
if(marks == 5){
gradeA++;
} else if (marks == 4){
gradeB++;
} else if (marks == 3){
gradeC++;
} else if (marks == 1){
gradeD++;
}
}
System.out.println(gradeD);
System.out.println(gradeC);
System.out.println(gradeB);
System.out.println(gradeA);
}
}
}
This is the output in this case:
0
1
1
1
For the D grade, the if condition should be else if (marks == 2).
You have put 1 instead of 2

Counting vowels in strings in java doesn't count the first string

Here is the code I wrote in Java to count vowels (a, e, i, o, u, y) in n strings:
import java.util.*;
import java.io.*;
public class VowelCount {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int n = x.nextInt();
int[] count = new int[n];
for(int i = 0; i < n; i++) {
if(x.hasNextLine()) {
String str = new String(x.nextLine());
int counter = 0;
for(int j = 0; j < str.length(); j++) {
char ch = str.charAt(j);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' || ch == 'y' || ch == 'Y') {
counter += 1;
}
}
count[i] = counter;
}
}
for(int k = 0; k < n; k++) {
System.out.print(count[k] + " ");
}
}
}
If I insert 10 strings like:
(hello, hi, string, int, double, boo, ad, ok, def, rep)
it should return
2 1 1 1 3 2 1 1 1 1
but what it returns is
0 2 1 1 1 3 2 1 1 1
so it count the first one as the second and doesn't count the last one (in fact right after writing "def" in the console it runs the code and prints the solution in console.
Can you help me figure it out where I am wrong? It would be really appreciated, thanks!
This looks like standard hackerrank format. I believe most of the templates include code to read the data - if one problem doesn't, just copy code from one that does.
I'm guess the problem here is that nextInt does not read the line ending. The first nextLine just reads the newline after the count.
int n = x.nextInt();
int[] count = new int[n];
for(int i = 0; i < n; i++) {
if(x.hasNextLine()) {
String str = new String(x.nextLine());
The method .nextInt() doesn't finish to read all the line, so your first call to x.nextLine() catch the space after the int.
Just add a line after : x.nextLine();
int n = x.nextInt();
int[] count = new int[n];
x.nextLine();

Small java program prints invisible newline?

I'm doing an assignment and I am done. This is a simple program that prints out pyramids of chars. However, I can't figure out why the program prints a newline when I never specified it with some input, even if it's meant to: https://i.imgur.com/gPs5oC5.png
Why do I have to have an extra newline when printing the pyramid upside down? Where is the newline printed?
import java.util.Scanner;
public class Test23 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean state = true;
String messageL = "Length: ";
String messageD = "Position: ";
String messageS = "Shutdown!";
while(state) {
int limit = 0;
int degree;
System.out.print(messageL);
int length = input.nextInt();
while ((length < 1 && length == -1) || length > 26) {
if (length == -1 ) {
System.out.println(messageS + "\n");
state = false;
break;
} else {
System.out.print(messageL);
length = input.nextInt();
}
}
if (!state)
break;
System.out.print(messageD);
degree = input.nextInt();
while((degree > 1) || (degree < 0)) {
System.out.print(messageD);
degree = input.nextInt();
}
if (degree == 0)
//No newline is needed here for some reason.
length++;
else if (degree == 1)
limit = length;
//New line here for the pyramids to print symmetrically.
//System.out.println("");
for (int i = 0; i < length; ++i) {
for (int counter = 0; counter < limit; counter++) {
char letter = (char)(counter + 'A');
System.out.print(letter);
}
if (degree == 0)
limit++;
else if (degree == 1)
limit--;
System.out.println("");
}
System.out.println("");
}
}
}
Small java program prints invisible newline?
In your program the last System.out.println(""); causes an extra line at the end of your program, i.e while(state) is true at the end, So either you comment the print statement or make your state=false at end.
while(state) {
...
System.out.println("");
}
The most inner loop won't run if the input is 0. limit will be 0, and hence the loop condition is false. As of this it will print en empty line, proceeding to add 1 too limit and then print chars.
for (int i = 0; i < length; ++i) {
for (int counter = 0; counter < limit; counter++) {
char letter = (char)(counter + 'A');

Categories