Issue with resetting data with a do while loop (Java) - java

I'm working on a program for school where I need to sort how many vowels are in a string along with the # of non-vowels. My teacher wants us to ask the user if they want to continue so we can provide multiple test cases without running the program more than once. I successfully got the program to loop, but my problem is that the vowel and non-vowel numbers from the previous test case carry over to the next one. I've been searching around online for the solution but I've had no luck so far. Any help would be much appreciated. (I am a noob at programming btw, I still have much to learn.)
import java.util.*;
class VowelReader
{
public static void main(String[] args)
{
String line;
int vi= 0, a = 0, e = 0, o = 0, u = 0, nonvowels = 0;
String answer = null;
Scanner scan = new Scanner (System.in);
do {
System.out.println("Enter a String to be processed for vowels: ");
line = scan.nextLine( );
for(int i = 0; i < line.length(); i++){
char c = Character.toLowerCase(line.charAt(i));
switch (c)
{
case 'a':
a++;
break;
case 'e':
e++;
break;
case 'i':
vi++;
break;
case 'o':
o++;
break;
case 'u':
u++;
default:
nonvowels++;
break;
}
}
System.out.println(line);
System.out.println("a- " +a);
System.out.println("e- " +e);
System.out.println("i- " +vi);
System.out.println("o- " +o);
System.out.println("u- " +u);
System.out.println("Non-vowels -" +nonvowels);
System.out.println("Continue?(Y/N)");
answer = scan.nextLine();
}
while( answer.toLowerCase().equals( "y" ) );
}
}

Using a Map with the key as a String you can keep track of our counts in one object. You then could put as many Maps, one for each test/string into a List. Then you can loop over the list preforming the same test(s) on different data sets.
Being homework and all I'm not going to post any code.

Related

Decoder java program to turn numbers into letters using a while loop

I am creating a decoder program that will essentially turn numbers into specific letters using a while loop but I'm having difficulties figuring out what's wrong with my code and also if there is a simpler way to put it using switch for example. Here is what I have so far:
import java.util.Scanner;
public class Decoder{
public static String decode(String str){
int i = 0;
while(i<str.length()){
if(str.charAt(i)=='1')
return("D");
else if(str.charAt(i)=='2')
return("W");
else if(str.charAt(i)=='3')
return("E");
else if(str.charAt(i)=='4')
return("L");
else if(str.charAt(i)=='5')
return("H");
else if(str.charAt(i)=='6')
return("O");
else if(str.charAt(i)=='7')
return("R");
return("Sorry, you must input numbers from 1-7 inclusive");
}
i++;
}
public static void main(String[] args){
System.out.println("Enter a number ");
}
}
Sure. Use a constant char array as a lookup table.
At index 0, store 'D'. At index 1, store 'W', etc.
Whenever you encounter a number in the source, subtract '1' to it to get the index in the array for this number, and get the matching letter from the array.
The code is left as an exercise.
Other than the array mentioned by JB Nizet, you could try:
switch statement
a Map<Integer, String> containing the digit/letter pairs
You can use StringBuilder and switch/case like that:
public class Decoder {
public static String decode(String str) {
int i = 0;
StringBuilder decodedString = new StringBuilder();
while (i < str.length()) {
switch (str.charAt(i)) {
case '1':
decodedString.append("D");
break;
case '2':
decodedString.append("W");
break;
case '3':
decodedString.append("E");
break;
case '4':
decodedString.append("L");
break;
case '5':
decodedString.append("H");
break;
case '6':
decodedString.append("O");
break;
case '7':
decodedString.append("R");
break;
default:
return ("Sorry, you must input numbers from 1-7 inclusive");
}
i++;
}
return decodedString.toString();
}
public static void main(String[] args) {
while (true) {
System.out.println("Enter a number: ");
Scanner input = new Scanner(System.in);
System.out.println(decode(input.next()));
System.out.println();
}
}

How to count how many vowels our String have? [duplicate]

This question already has answers here:
Use string methods to find and count vowels in a string?
(10 answers)
Closed 6 years ago.
I'm new in Java and I'm trying to solve a challenge. I have to write some words and to compare which one is longer, and how many vowels the longer one have. Also if you write "end", writing of words to end and to print something else, in our case You didn't wrote any word.
Output Example in Terminal (CMD):
Write a word, or write 'end' to end writing: test
Write a word, or write 'end' to end writing: tee
Write a word, or write 'end' to end writing: testing
Write a word, or write 'end' to end writing: end
Word testing is longest and it have 2 vowels.
Output Example if you don't write any word:
Write a word, or write 'end' to end writing:
Write a word, or write 'end' to end writing:
Write a word, or write 'end' to end writing: end
You didn't wrote any word.
Program should be coded using Scanner (Input), Switch Case and Do While. Strings should be compared using method equalsIgnoreCase().
I tried many times, and what I did is only writing and deleting code.
This is my code:
import java.util.Scanner;
public class VowelFinder {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String word = null;
int num = 0;
String max = null;
final String SENTINEL = "end";
System.out.println(" ");
do {
System.out.print("Write a word, or write `" + SENTINEL + "` to end writing: ");
word = scan.nextLine();
if(!word.equalsIgnoreCase(SENTINEL)) {
int nr = countVowels(word);
if (num <= nr) {
num = nr;
max = word;
}
}
} while (!word.equalsIgnoreCase(SENTINEL));
if (max != null) {
System.out.println(" ");
System.out.println("Word `" + max + "` is longest word, and countains " + num + " vowels.");
}
else {
System.out.println(" ");
System.out.println("You din't wrote any word !");
}
}
private static int countVowels(String word) {
int counter = 0;
int vowels = 0;
while(counter < word.length()){
char ch = word.charAt(counter++);
switch (ch) {
//Lower Case
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
//Upper Case
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'Y':
vowels++;
default:
// do nothing
}
}
return vowels;
}
}
Problem is:
When I do so in terminal (CMD)
Write a word, or write 'end' to end writing:
Write a word, or write 'end' to end writing:
Write a word, or write 'end' to end writing: end
It prints me Word ' ' is longest word, and countains 0 vowels., but it should print You didn't wrote any word.
Can someone help me ? Where I did wrong ?
It should print me You didn't wrote any word if I don't write any word.
I hope I was clear and you can help me. If I wasn't clear please ask me.
Thanks for your contribution.
change the if condition to
if (word != null && !"".equals(word.trim()) && !word.equalsIgnoreCase(SENTINEL))
I added a null check and did a trim to remove the white spaces.
I have made some changes and it worked for me...
if (max != null && !max.trim().isEmpty() && max.length()>0) {
System.out.println(" ");
System.out.println("Word `" + max + "` is longest word, and countains " + num + " vowels.");
}
You could check in countVowels() whether the current word is nothing.
private static int countVowels(String word) {
int counter = 0;
int vowels = 0;
if(word.length() == 0){
return -1;
}
...
}
The return value is less than 0 so max won't be replaced.

Java program doesn't have any output when using a switch statement inside a while loop?

So I need the statements inside the while loop to repeat until the user enters 4 (which exits the program), but when I try to run the program, nothing is outputted to the screen (but it compiles just fine). Why would it do this? This answer is probably really simple, but any help would be really appreciated!
public class Driver
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int answer;
boolean bool = true;
while(bool);
{
System.out.println("\n\tGeometry Calculator\n" +
"\t1. Calculate the Area of a Circle\n" +
"\t2. Calculate the Area of a Rectangle\n" +
"\t3. Calculate the Area of a Triangle\n" +
"\t4. Quit\n");
System.out.print("\tEnter your choice (1-4): ");
answer = keyboard.nextInt();
switch(answer)
{
case 1:
System.out.println("\n\tCalculating the area of a circle...");
break;
case 2:
System.out.println("\n\tCalculating the area of a rectangle...");
break;
case 3:
System.out.println("\n\tCalculating the area of a triangle...");
break;
case 4:
System.out.println("\n\tQuiting...");
System.exit(0);
break;
default:
System.out.println("\n\tPlease enter a number between 1 and 4.");
}
if(answer == 4)
bool = false;
}
}
You have one tiny mistake. You have added ; after the while loop. Just delete it. Your code should be
while(bool)

Switch questions, Array printing

-So in case 2, i'm trying to have the user to input elements (N,Y,P,D,G) only with specific Array location. I used switch inside a switch, but how do i re-loop if he enters wrong elements?
-in case 3, i'm trying to print the whole 2D array, but the original array is filled with the element G.
-in case 4, i'm trying to change the map view to the symbols.
Just found this as a practice, trying to learn, to some point, beginner complex programming, so any help is appreciated and any criticism is highly appreciated because i want to have a good basic knowledge of java :)
import java.util.Scanner;
public class Studyone {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int row;
int col;
int row1; //for case 2, so it would allow the user to input the element in the request array
int col1;
System.out.println("Enter the row: ");// knowing the row and the col of the 2D array to base the rest on.
row = input.nextInt();
System.out.println("Enter the col: ");
col = input.nextInt();
String sentence;
String sentence2;
String sentence3;
String tempelement;
String N;
String Y;
String G;
String P;
String D;
int choice;
System.out.println("The menu\n1)Enter the Elements in order\n2)Enter the the Col and row number spec.\n3)Show the Orig. map as is\n4)Show symbolic map.");
choice = input.nextInt();
System.out.println(choice);
String [][] map = new String[row][col];
switch (choice)
{
case 1:
sentence3=input.nextLine(); // for some reason it auto enters the first map [0][0] as null, this line allows the user to input the map[0][0]
map[0][0]=sentence3;
for (int i = 0; i < map.length; i++)
{
for (int j = 0;j < map[i].length; j++)
{
System.out.println("Enter the element");
sentence2 = input.nextLine();
map[i][j]=sentence2;
}
System.out.println(map[1][1]);
System.out.println(choice);
}
break;
case 2:
System.out.println("Enter the row");
row1 = input.nextInt();
System.out.println("Enter the col");
col1 = input.nextInt();
System.out.println("Enter the element you want to enter");
tempelement = input.nextLine();
switch (tempelement)
{
case "Y":
map[row1][col1] = tempelement;
case "N":
map[row1][col1] = tempelement;
case "P":
map[row1][col1] = tempelement;
case "D":
map[row1][col1] = tempelement;
case "G":
map[row1][col1] = tempelement;
}
System.out.println(tempelement); // test,does not let me enter any temp elements, lets it empty in the input without letting the use enter anything. Figure out error
System.out.println(choice); // test, prints the right choice, Correct.
break;
case 3:
for (int i=0;i > map.length;i++)
{
for (int j=0; j > map[i].length; j++)
{
map[i][j] = N;
// print statment, need to find how to do.
}
}**strong text**
break;
case 4:
// having symbols instead of the letters, N=* , P= ~ , Y=. , G= #, D=#
//
}
}
}
Case 2:
I don't know why you're using a switch statement within to check if the cases are either N,Y,P,D or G. In order to check for correct inputs, you could use a while loop and break when the correct input is placed.
System.out.println("Enter the row");
row1 = input.nextInt();
System.out.println("Enter the col");
col1 = input.nextInt();
while(true){
System.out.println("Enter the element you want to enter");
tempelement = input.nextLine();
if(tempelement.equals("N") || tempelement.equals("Y") || tempelement.equals("P") || tempelement.equals("D") || tempelement.equals("G")){
map[row1][col1] = tempelement;
break;
}
}
Case 3:
To print a 2D array, you need a nested for loop. It requires 2 for loops.
for(int i=0; i<map.length; i++){
for(int j=0; j<map[i].length; j++){
System.out.print(map[i][j]);
}
System.out.print("\n"); // this is for spacing after a row of element prints
}
Case 4:
This is the same as Case 3, just within the inner for-loop, you would have an if-else statement block or switch block to print out a symbol instead of a map. For example,
...
for(int j=0; j<map[i].length; j++){
switch(map[i][j]){
case "N": System.out.print("Symbol"); break;
case "P": ... code
... code
}
}
sentence3=input.nextLine(); // for some reason it auto enters the first map [0][0] as null, this line allows the user to input the map[0][0]
Use input.next() instead of nextLine().
Scanner.nextLine() as described in official document is:
Advances this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
After nextInt() is called it isn't properly terminating the allocated line of memory. So when nextLine() is called first time it is actually terminating the previous line that actually had value in it -- entered via nextInt() rather than taking in a new String value. That's why sentence3 is getting null value.
So in case 2, i'm trying to have the user to input elements
(N,Y,P,D,G) only with specific Array location. I used switch inside a
switch, but how do i re-loop if he enters wrong elements?
You can try in this way:
boolean bVaildInput = true;
do{
System.out.println("Enter the element you want to enter");
tempelement = input.next();
switch (tempelement)
{
case "Y":
map[row1][col1] = tempelement;
break;
case "N":
map[row1][col1] = tempelement;
break;
case "P":
map[row1][col1] = tempelement;
break;
case "D":
map[row1][col1] = tempelement;
break;
case "G":
map[row1][col1] = tempelement;
break;
default :
System.out.println("Invalid Input");
bValidInput = false;
}
}while(!bVaildInput);
in case 3, i'm trying to print the whole 2D array, but the original
array is filled with the element G.
for (int i=0;i < map.length;i++)
{
for (int j=0; j < map[i].length; j++)
{
System.out.print(map[i][j]+"\t");
}
System.out.print("\n");
}
in case 4, i'm trying to change the map view to the symbols.
Show some effort.
Since you are using this as practice, I'm not going to answer your problems but provide some insight into what it is that is going on and some links to look into:
Case 2:
You don't really need a second switch here. Look at the code for each case in the switch, it is exactly the same. What you want to use is a while loop and test that the input is valid. That way if the user enters invalid input it will ask them to try again. See Example 3 in this post
Case 3: There are plenty of examples out there of how to print 2D arrays - it depends on how you want it to look. I Suggest looking at this example
Case 4: This really is just an extension of Case 3 except rather then printing out the stored Input letter, print out the symbol. This is where a second switch statement maybe useful.

pop()ing stacks doesn't seem to be erasing the values

This program is supposed to read the values of the string input and return a result.
However, when I use
System.out.println(Arrays.toString(stack.toArray()));
to check what the stack looks like at the end, or even during the program, I noticed that the pop() method foe the stack doesn't seem to be removing the elements it's returning.
I'm probably doing something horribly wrong, but I haven't been able to figure it out.
I'd really appreciate any insight !
// Test example : (((1+1)+1)+1)
import java.util.*;
public class Task2
{
public static void main(String[] args) //run Start() method
{
System.out.print("Enter an expression, or press Enter to quit: ");
Stack<String> stack = new Stack<String>();
Scanner scanner = new Scanner(System.in);
String n = scanner.nextLine();
if(!n.isEmpty())
{
for(int i = 0 ; i < n.length() ; i++)
{
if(!(n.charAt(i) == ')'))
{
stack.push(n.charAt(i) + "");
}
else
{
int two = Integer.parseInt(stack.pop());
char op = (stack.pop()).charAt(0);
int one = Integer.parseInt(stack.pop());
switch(op)
{
case '+':{stack.push((one + two) + "");}
case '-':{stack.push((one - two) + "");}
case '*':{stack.push((one * two) + "");}
case '/':{stack.push((one / two) + "");}
}
}
}
}
else
{
System.out.print("\ngoodbye");
System.exit(0);
}
}
}
Sorry for the lack of comments, and thanks !
This is my first solution here, so be gentle :D. The issue was not with pop(), as pop was doing what it was supposed to. You forgot to add break points in your switch statement. It did every operation and added it to the stack giving it the illusion that pop was not working. I will leave the printing part to you. Cheers.
switch(op)
{
case '+':
stack.push((one + two) + "");
break;
case '-':
stack.push((one - two) + "");
break;
case '*':
stack.push((one * two) + "");
break;
case '/':
stack.push((one / two) + "");
break;
}

Categories