-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.
Related
I am new at coding and now I am learning Java. I tryed to write something like calculator. I wrote it with switch case but then I realized I must take all inputs in single line. For example in this code I took 3 inputs but in 3 different lines. But I must take 2 input and 1 char in single line. First first number second char and then third number. Can you help me ?
Public static void main(String[] args) {
int opr1,opr2,answer;
char opr;
Scanner sc =new Scanner(System.in);
System.out.println("Enter first number");
opr1=sc.nextInt();
System.out.println("Enter operation for");
opr=sc.next().charAt(0);
System.out.println("Enter second number");
opr2=sc.nextInt();
switch (opr){
case '+':
answer=opr1+opr2;
System.out.println("The answer is: " +answer);
break;
case '-':
answer=opr1-opr2;
System.out.println("The answer is: " +answer);
break;
case '*':
answer=opr1*opr2;
System.out.println("The answer is: " +answer);
break;
case '/':
if(opr2>0) {
answer = opr1 / opr2;
System.out.println("The answer is: " + answer);
}
else {
System.out.println("You can't divide to zero");
}
break;
default:
System.out.println("Unknown command");
break;
}
Try following way
System.out.print("Enter a number then operator then another number : ");
String input = scanner.nextLine(); // get the entire line after the prompt
String[] sum = input.split(" ");
Here numbers and operator separated by "space". Now, you can call them by sum array.
int num1 = Integer.parseInt(sum[0]);
String operator = sum[1]; //They are already string value
int num2 = Integer.parseInt(sum[2]);
Then, you can do as you did than.
You can try something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter number, operation and number. For example: 2+2");
String value = scanner.next();
Character operation = null;
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
Character c = value.charAt(i);
// If operation is null, the digits belongs to the first number.
if (operation == null && Character.isDigit(c)) {
a.append(c);
}
// If operation is not null, the digits belongs to the second number.
else if (operation != null && Character.isDigit(c)) {
b.append(c);
}
// It's not a digit, therefore it's the operation itself.
else {
operation = c;
}
}
Integer aNumber = Integer.valueOf(a.toString());
Integer bNumber = Integer.valueOf(b.toString());
// Switch goes here...
}
Note: didn't validate input here.
My program is designed to assign an integer value based on a class size that the user inputs (S, M, L, X). Then, in a later method, I use this value to calculate the remaining seats available in the class. This issue that I'm having is that, in spite of the program running, the value returned is always zero, no matter what class size the user inputs or the number of students entered as being registered already.
The program includes a few other unrelated steps, so I've isolated the aforementioned methods for ease of reference but I can post my complete code if this is easier.
My code to assign the integer value:
public static int courseSize() {
System.out.print("Please enter the course size (possible values are:
S, M, L, or X):");
size = console.next().charAt(0);
switch(size) {
case 'S': totalSeats = 25;
break;
case 'M': totalSeats = 32;
break;
case 'L': totalSeats = 50;
break;
case 'X': totalSeats = 70;
break;
default: System.out.println("Please enter S, M, L, or X");
}//Close switch statement
console.nextLine();
return totalSeats;
}//Close courseSize
This is the code for obtaining the number of students registered and calculating the number of seats available:
public static void numStudents() {
System.out.print("How many students are currently registered for this course? ");
studentsReg = console.nextInt();
}//Close numStudents method
//This method returns the number of open seats remaining
public static int calcAvail () {
openSeats = (totalSeats - seatsTaken);
return openSeats;
} //Close calcAvail method
This is the output for collecting the user input. You can see the user entered L (50 seats) and 13 students are registered.
However, you can see in the below output that it states there are 0 remaining seats.
All of the variables in this code are declared under my class as public, static variables.
Any thoughts as to why my calculation isn't working? I'm leaning toward the issue being my switch statement because it uses a char as input and then stores it as an integer; however, the output is still printing out the correct number to the screen.
move this console.nextLine(); in numStudents()
default is missing break
default: System.out.println("Please enter S, M, L, or X");
break;
}
return totalSeats;
}
You can do
default: System.out.println("Incorrect entry");
courseSize();
break;
}
and
openSeats = (totalSeats - seatsTaken); should be
openSeats = (totalSeats - studentsReg );
I would clear the EOL character left by your call to nextInt() in your numStudents() with the following code
public static void numStudents() {
System.out.print("How many students are currently registered for this course? ");
//code A
studentsReg = console.nextInt();
console.nextLine();
//or
//code B
studentsReg = Integer.parseInt(console.nextLine());
}//Close numStudents method
Then I would wrap a while() around your switch to make sure your user has to input a valid selection or retry, and use nextLine() instead of next() which also leaves behind an EOL character ('\n').
public static int courseSize() {
boolean validInput = false;
while(!validInput)
{
validInput = true;
System.out.print("Please enter the course size (possible values are: S, M, L, or X):");
size = console.nextLine().charAt(0);
switch(size) {
case 'S': totalSeats = 25;
break;
case 'M': totalSeats = 32;
break;
case 'L': totalSeats = 50;
break;
case 'X': totalSeats = 70;
break;
default: System.out.println("Incorrect Value Entered, Please enter S, M, L, or X");
validInput = false;
break;
}//Close switch statement
}
return totalSeats;
}//Close courseSize
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.
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 7 years ago.
Improve this question
I have an exercise that using switch case. Assuming the code like
int choice;
do {
choice = //user input here;
switch (choice) {
case 1: //print something; break;
case 2: //print something; break;
case 3: //print something; break;
default: //print default; break;
}
} while(condition);
i want the user can only choose the case once. If they did choose case 1, they cannot choose that again.
Define a private bool variable for each one of your options and set it true if user called each one. Then check whether its true before running that option codes, again.
For example:
bool _case1=false;
int choice;
do{
choice = //user input here;
switch(choice){
case 1:
if(!_case1)
{
//print something;
_case1=true;
}
else
{
//Tell the user "You have selected this option once"
}
break;
//etc
}
}while(condition);
You could call methods for each case and have some bools that mark whether each case has already been chosen, use an if statement to check if the case has already been chosen and if so print a notice to pick another, otherwise perform the action.
You could also do this without separate methods but I am a fan of modular code. :)
I am assuming that a function that contains this switch case is called over and over again. If you want such a functionality, I would point to Set. Use the set to store the choices. If a set already contains a certain choice, take whatever action you deem fit.
Using a set is better than having a global array of booleans, since that could potentially be wasting a lot of memory, depending on the number of choices that you have.
Does that answer your question?
When user press the input
if the input is match case then
store this input in one List.
Next time you have to check this input.
If it belongs in List or not,
if belongs then case will not execute
if not belongs then it will execute the case.
Try in this way :
List<Integer> choiceList = new ArrayList<Integer>();
int choice;
do {
choice = //user input here;
if (choiceList.contains(choice)) {
continue;
}
choiceList.add(choice);
switch(choice) {
case 1: //print something; break;
case 2: //print something; break;
case 3: //print something; break;
default: //print default; break;
}
} while(condition);
As some of the other answers have said you can use a boolean to check if a case has been used or not. However, you can also use an int. The advantage of using an int is that you can specify how many times each case can be used. For example, the following code can only use each case once.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int choice;
int case1 = 0, case2 = 0, case3 = 0;
int case1lim = 1, case2lim = 1, case3lim = 1;
System.out.println("You may use may enter the number 1 " + case1lim + " times");
System.out.println("You may use may enter the number 2 " + case2lim + " times");
System.out.println("You may use may enter the number 3 " + case3lim + " times");
do {
System.out.println("Please enter a number between 1 and 3");
choice = user_input.nextInt();
if(choice == 1 && case1 < case1lim || choice == 2 && case2 < case2lim || choice == 3 && case3 < case3lim) {
switch(choice){
case 1: //print something;
case1++;
break;
case 2: //print something;
case2++;
break;
case 3: //print something;
case3++;
break;
default: //print default;
break;
}
} else {
System.out.println("Please pick another number since you have already used that case or you entered a bad value");
}
} while(true);
}
}
However if you change the values of the line
int case1lim = 1, case2lim = 1, case3lim = 1;
to
int case1lim = 2, case2lim = 1, case3lim = 1;
You can use the first case twice and all the other cases once.
Im writing a program in java that is suppose to receive a phone number as a string, (ex. 1800helpmee) from the user and print out its corresponding numbers. 1800 435 7633 should be the answer. this is the code i have so far. I've loaded the number into the array. I am having an issue with the next part. my array is called inputNumber. I tried something like this but it doesn't seem to be working
for (int j = 0; j<9; j ++) {
if ( inputNumber[j] =='A' || inputNumber[j] == 'B' || inputNumber[j] =='C'){
System.out.println("2");
} etc.
switch inputNumber[j] =='A' to inputNumber[j].equalsIgnoreCase("a") apply this for a, b and c then retry
You could use a for each loop to iterate the strings array
public static void main(String[] args) {
String [] inputNumber = {"1","8","0","0","h","e","l","p"};
for (String number : inputNumber) {
switch (number.toUpperCase()) {
case "A":
case "B":
case "C":
System.out.println("2");
break;
case "D":
case "E":
case "F":
System.out.println("3");
break;
// other letters
default:
System.out.println(number);
}
}
}
Evaluate each letter with a switch (as of Java 7) and print the aproppriate number. Notice the fall through, a break statement after several case. The toUpper() method is called to compare only with the uppercase version of each letter.