I'm not able to understand that why is the compiler just shows running(which is forever) when I change char to int in this program. By changing I mean using just int to take the option number and hence using int numbers itself in switch.
This one is normal char 1 which is working-
public static void main(String args[])
throws java.io.IOException{
char option; int i=0;
do{
if(i==1)
System.out.println("\nNotice: Wrong option chosen, pick again.");
i=1;
System.out.println("Help on:");
System.out.println("1. if");
System.out.println("2. switch");
System.out.println("3. while");
System.out.println("4. do-while");
System.out.println("5. for");
System.out.println("Pick any option for brief informatrion.");
option= (char)System.in.read();
}while(option<'1' || option>'5');
switch(option){
case '1':
System.out.println("The If:\n");
System.out.println("If(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The Switch:\n");
System.out.println("switch(expression){");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The While:\n");
System.out.println("while(condition statement;)");
break;
case '4':
System.out.println("The Do-While:\n");
System.out.println("do{");
System.out.println(" statement;");
System.out.println("}while(condition);");
break;
case '5':
System.out.println("The For:\n");
System.out.println("for(init; condition; iteration){");
System.out.println(" statement;");
System.out.println("}");
break;
}
}
}
This is int 1 which just keeps running forver
public static void main(String args[])
throws java.io.IOException{
int option; int i=0;
do{
if(i==1)
System.out.println("\nNotice: Wrong option chosen, pick again.");
i=1;
System.out.println("Help on:");
System.out.println("1. if");
System.out.println("2. switch");
System.out.println("3. while");
System.out.println("4. do-while");
System.out.println("5. for");
System.out.println("Pick any option for brief informatrion.");
option= System.in.read();
}while(option<1 || option>5);
switch(option){
case 1:
System.out.println("The If:\n");
System.out.println("If(condition) statement;");
System.out.println("else statement;");
break;
case 2:
System.out.println("The Switch:\n");
System.out.println("switch(expression){");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case 3:
System.out.println("The While:\n");
System.out.println("while(condition statement;)");
break;
case 4:
System.out.println("The Do-While:\n");
System.out.println("do{");
System.out.println(" statement;");
System.out.println("}while(condition);");
break;
case 5:
System.out.println("The For:\n");
System.out.println("for(init; condition; iteration){");
System.out.println(" statement;");
System.out.println("}");
break;
}
}
}
See https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read%28%29
The System.in.read return an int represent for character.
Let's say you type 1, it will read as 49.
And if you use file to be stdin when it reach EOF it will return -1
Even if the char version, the same error happens.
See this demo: https://ideone.com/Q83qxn
Related
I need a little help here. The question is the output (PS! the last output line).The program only prints only number 2 on the last line. How can I get the calculation. Thank You!
Output is here:
Choose from the following calculations:
1: subtraction
2: addition
3: multiplication
4: division
5: remainder
Make your choice: 1
Type in the first number: 9
Type in the second number: 7
9 - 7 = 2
import java.util.Scanner;
public class Calculation
{
public static void main(String[] args)
{
System.out.println("Choose from the following calculations:");
System.out.println("1: subtraction");
System.out.println("2: addition");
System.out.println("3: multiplication");
System.out.println("4: division");
System.out.println("5: remainder");
Scanner input = new Scanner(System.in);
System.out.print("\nMake your choice:");
int choice = input.nextInt();
if( 1 <= choice && choice <= 5 )
{
System.out.print("\nType the first number: ");
int first = input.nextInt();
System.out.print("Type the second number: ");
int second = input.nextInt();
switch (choice)
{
case 1:
System.out.println(+ (first - second));
break;
case 2:
System.out.println(+ (first + second));
break;
case 3:
System.out.println(+ (first * second));
break;
case 4:
System.out.println(+ ((double)first / (double)second));
break;
case 5:
System.out.println(+ (first % second));
break;
default:
break;
}
}
else
{
System.out.println("Invalid choice");
}
}
}
try this
System.out.println(first+"-"+second+"="+(first-second));
System.out.println(first+"+"+second+"="+(first+second));
System.out.println(first+"*"+second+"="+(first*second));
System.out.println(first+"/"+second+"="+((double)first / (double)second));
System.out.println(first+"%"+second+"="+(first%second));
P.S you are not considering Divide by zero error for your division.
I'm trying to code simple calculator (all in one) using Switch cases in java. I came up with following code so far. However I'm stuck with while loop. I want to keep showing main menu after each case execution until user decides to exit the program.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result=0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is "+result);
}
}
Above code works fine. Program ends itself after execution of user selected choice. I want to put main menu on a repeat.
Add a while loop like this:
public static void main(String[] args) {
// Moved this outside the while loop as davidxxx pointed out +1
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i = s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;//'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is " + result);
System.out.println("Go again?");
String goAgain = s.next();
if (!goAgain.equals("y")) {
break;
}
}
}
Try this:
import java.util.Scanner;
public class Calculator {
private static final String EXIT = "EXIT";
public static void main(String[] args) {
Calculator calc = new Calculator();
Scanner s = new Scanner(System.in);
while (true) {
String res = calc.runCalc(s);
if (res.equals(EXIT)) {
break;
} else {
System.out.println(res);
}
}
}
private String runCalc(Scanner s) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.println("Enter your choice: ");
int i = s.nextInt();
if (i == 5) {
return EXIT;
}
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;// 'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
return "Wrong Choice.";
}
return "Answer is " + result;
}
}
There is more than one way to achieve this, you can use
while loop.
do-while loop.
for loop.
I think do-while loop is better for your situation. Because either user wants to continue or not you have to proceed one time(before loop false). And you do not want to use another variable for quit the loop.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int result=0;
do{
System.out.println("Main Menu:");
System.out.println("-1. complete and calculate");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
if(i ==-1){
System.out.println("Answer is "+result);
return;
}
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
break;
}
}while(true);
}
import java.io.*;
import java.util.*;
public class Stack1{
static final int MAX=100;
int top=-1;
int[] stack=new int[MAX];
public static void main(String args[])
{
Stack1 s1=new Stack1();
int opt, val;
System.out.println("1. PUSH ");
System.out.println("2. POP ");
System.out.println("3. PEEP ");
System.out.println("4. DISPLAY STACK ");
System.out.println("5. EXIT ");
System.out.println("\n Enter Your Option: ");
Scanner s=new Scanner(System.in);
opt=s.nextInt();
do{
switch(opt)
{
case 1: System.out.println("Enter the value to be added to the stack: ");
val=s.nextInt();
s1.push(val);
break;
case 2: s1.pop();
break;
/*
case 3: s1.peep();
break; */
case 4: s1.display();
break;
}
}while(opt!=5);
}
public void push(int val)
{
if(top==MAX-1)
{
System.out.println("Stack is FULL!");
}
else
{
top++;
stack[top]=val;
System.out.println("Element added to the stack is: "+val);
display();
}
}
public void pop()
{
int x;
if(top==-1)
{
System.out.println("Stack is EMPTY!");
}
else
{
x=stack[top];
System.out.println("The element deleted from the stack is: "+x);
top--;
display();
}
}
public void peep()
{
int n;
n=stack[top];
System.out.println("The value at the top of the stack is: "+n);
}
public void display()
{
int i;
if(top==-1)
System.out.println("STACK IS EMPTY!");
else
{
for(i=0; i<=top; i++)
System.out.println("The elements in the stack are: "+stack[i]);
}
}
}
I wrote this java code to implement stack. But once I select any option, only that method gets executed and the program ends. I want the program to provide me to enter another option once the current method is executed. What should I do?
As #LordWilmore pointed out in his comment, the opt value will be set just once causing program to spin forever in a corresponding case (unless the value is 5). Moving opt = s.nextInt(); inside loop will fix the issue.
do {
System.out.println("Enter Your Option: ");
opt = s.nextInt();
switch(opt) {
//...
}
} while (opt != 5);
You can modify your main method in a manner like this:
public static void main(String args[]){
int option;
Scanner sc = new Scanner(System.in);
MyStack1 s = new MyStack1();
while(true){
System.out.println("Enter the choice You want to perform on the stack: ");
System.out.println(" 1. push \n 2. Pop \n 3. Display \n 4. peep \n 5. Exit");
System.out.println("Enter your option: ");
option = sc.nextInt();
switch(option){
case 1: System.out.println("Enter the element you want to push into the stack: ");
s.push(sc.nextInt());
break;
case 2: s.pop();
break;
case 3: System.out.println("Displaying the stack contents: ");
s.display();
break;
case 4: System.out.println("The top element in the stack is: ");
s.peek();
break;
case 5: System.out.println("You selected Exit!!");
break;
default: System.out.println("Wrong choice!! Please enter a valid option!!");
return;
}
}
}
I have a method which uses a switch statement to give the user options to select, once they have selected an option and the code in the case has been executed how do I get back into the main method which offers another menu?
Part of my code:
static void modifyStudent() {
System.out.println("Wish student would you like to change?");
for(int i=0;i<10;i++){
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
System.out.println("1: Change name.");
....
int detailChange = input.nextInt();
switch (detailChange) {
case 1:
String newName = input.next();
studentNamesArray[studentChoice] = newName;
break;
....
}
public static void main(String[] args) {
while (1 == 1) {
System.out.println("Please select an option:");
System.out.println("1: Add a student.");
....
int choice = input.nextInt();
switch (choice) {
case 1:
....
}
EDIT (full code requested):
/**
* User: Colin Shewell
* Date: 26/11/13
* Time: 10:32
*/
import java.util.Scanner;
import java.util.Arrays; //REMOVE THIS!!!
public class StudentMarks {
static Scanner input = new Scanner(System.in);
static String[] studentNamesArray = new String[10];
static int[][] studentMarksArray = new int[10][3];
static int nameArrayCount, markArrayCount = 0;
static int markOne, markTwo, markThree;
static String studentName;
static void printArrays(){
System.out.println(Arrays.toString(studentNamesArray));
for (int index=0;index<10;index++)
{
System.out.println(studentMarksArray[index][0]);
System.out.println(studentMarksArray[index][1]);
System.out.println(studentMarksArray[index][2]);
}
}
static void addStudent() {
if (nameArrayCount < 10) {
System.out.println("Enter the student's name in the following format - surname, forename: ");
studentName = input.next();
studentNamesArray[nameArrayCount] = studentName;
nameArrayCount = nameArrayCount + 1;
}
else if (nameArrayCount == 10) {
System.out.println("******Array is full, please delete a student before adding another.*****");
}
if (markArrayCount < 10){
System.out.println("Enter the first mark: ");
markOne = input.nextInt();
System.out.println("Enter the second mark: ");
markTwo = input.nextInt();
System.out.println("Enter the third mark: ");
markThree = input.nextInt();
studentMarksArray[markArrayCount][0] = markOne;
studentMarksArray[markArrayCount][1] = markTwo;
studentMarksArray[markArrayCount][2] = markThree;
markArrayCount = markArrayCount + 1;
}
}
static void modifyStudent() {
System.out.println("Wish student would you like to change?");
for(int i=0;i<10;i++){
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
System.out.println("1: Change name.");
System.out.println("2: Change first mark.");
System.out.println("3: Change second mark.");
System.out.println("4: Change third mark.");
System.out.println("5: Change all marks.");
int detailChange = input.nextInt();
switch (detailChange) {
case 1:
System.out.println("Enter the new student name.");
String newName = input.next();
studentNamesArray[studentChoice] = newName;
return;
case 2:
System.out.println("Enter the new mark for mark one.");
int newMarkOne = input.nextInt();
studentMarksArray[studentChoice][0] = newMarkOne;
return;
case 3:
//two
break;
case 4:
//three
break;
case 5:
//all
break;
default:
System.exit(0);
break;
}
}
public static void main(String[] args) {
while (true) {
System.out.println("Please select an option:");
System.out.println("1: Add a student.");
System.out.println("2: Modify the details of an existing student.");
System.out.println("3: Delete an existing student.");
System.out.println("4: Sort in alphabetical order by name.");
System.out.println("5: Output the student name and corresponding marks in ascending name order.");
System.out.println("6: Output the student name and corresponding marks in descending name order.");
System.out.println("7: Display the student with the highest average mark.");
System.out.println("8: Display the student with the lowest average mark.");
System.out.println("9: Display the average score of all students recorded.");
System.out.println("10: Exit.");
int choice = input.nextInt();
switch (choice) {
case 1:
addStudent();
System.out.println(Arrays.toString(studentNamesArray));
break;
case 2:
modifyStudent();
break;
case 3:
printArrays();
break;
/* case 4:
sortAlphabetical();
break;
case 5:
outputNameMarksAsc();
break;
case 6:
outputNameMarksDsc();
break;
case 7:
highestStudentAvgMark();
break;
case 8:
lowestStudentAvgMark();
break;
case 9:
displayAvgScore();
break; */
case 10:
System.exit(0);
break;
default:
System.exit(0);
break;
}
}
}
}
Just return to the main method. return just exits the method and continues executing code from the line it was called.
case 1:
String newName = input.next();
studentNamesArray[studentChoice] = newName;
return; //exits this method
//break; <-- not needed after a return!
Your code will run in an infinite loop, you can make it run with a conditional flag like this
boolean isRunning = true;
while (isRunning) {
System.out.println("Please select an option:");
System.out.println("1: Add a student.");
....
int choice = input.nextInt();
switch (choice) {
case 1:
isRunning = false;
//your code for case 1
....
}
//rest of the code in main executes now
This will exit the while loop back to the main method
I need help on how to use for-loops in Java
This is an assignment for class, so I'd rather just be pointed in the right direction instead of given an answer.
"List of valid seven dwarfs: Sleepy, Bashful, Doc, Sneezy, Happy, Grumpy, Dopey
Pool of random characters, non-valid Dwarfs: Lion-O, Cheetara, Panthro, Tigra, Snarf, Donald Duck, Mickey Mouse, Minnie Mouse, Goofy, Heathcliff, Huey, Dewey, Louie, Scrooge McDuck,
Declare these variables:
int counter = 7;
boolean firstSelection = false;
boolean secondSelection = false;
boolean thirdSelection = false;
boolean fourthSelection = false;
boolean fiveSelection = false;
boolean sixSelection = false;
boolean sevenSelection = false;
Print a list of three choices to the console. Ask the user to pick the correct dwarf of the three choices.
The list of three choices will include two names from the random characters list and one name from the seven dwarfs.
You will create a switch statement to handle the choice selection
When the wrong case is selected then decrement the int variable called counter and print to the console “wrong selection”
When the correct case is selected then change the corresponding boolean variable to true (ie.. firstSelection, secondSelection, etc) and print to the console “Hi Ho, you picked the correct one”
The default case will print a statement to the console “invalid selection”
Create a loop that will perform this seven times until you covered all seven dwarfs.
Use a for loop
Recreate the loop again using a do-while loop
Recreate the loop again using a while loop
At the end, create an if-else statement. This statement will have short circuit &&’s that will test all of the Boolean variables. If true, print a statement to the console “You earned a gold star!”. Else, print a statement to the console “You did not get all correct”. "
I completed the previous assignment, which was just this specification without the loops, with no problem. However I really don't understand how the professor wants us to integrate the loops into the problem. The only thing I can think of is that he wants up to create a loop seven times that somehow asks about a different dwarf each of the seven times. Is that even possible? Can you change the content of the loops as you are running through it? I feel like I am just not even thinking about this correctly.
Here is my code from the previous assignment, sans loops:
import java.util.Scanner;
public class SevenDwarfs {
public static void main(String[] args) {
int counter = 7;
boolean firstSelection = false;
boolean secondSelection = false;
boolean thirdSelection = false;
boolean fourthSelection = false;
boolean fiveSelection = false;
boolean sixSelection = false;
boolean sevenSelection = false;
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Sleepy");
System.out.println("2 Lion-O");
System.out.println("3 Cheetara");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Hi Ho, you picked the correct one");
firstSelection = true;
break;
case 2:
System.out.println("Wrong selection");
--counter;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Panthro");
System.out.println("2 Bashful");
System.out.println("3 Tigra");
Scanner input2 = new Scanner(System.in);
int choice2 = input2.nextInt();
switch (choice2) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
secondSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Snaf");
System.out.println("2 Doc");
System.out.println("3 Donald Duck");
Scanner input3 = new Scanner(System.in);
int choice3 = input3.nextInt();
switch (choice3) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
thirdSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Mickie Mouse");
System.out.println("2 Sneezy");
System.out.println("3 Minie Mouse");
Scanner input4 = new Scanner(System.in);
int choice4 = input4.nextInt();
switch (choice4) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
fourthSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Heathcliff");
System.out.println("2 Happy");
System.out.println("3 Goofy");
Scanner input5 = new Scanner(System.in);
int choice5 = input5.nextInt();
switch (choice5) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
fiveSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Huey");
System.out.println("2 Grumpy");
System.out.println("3 Dewey");
Scanner input6 = new Scanner(System.in);
int choice6 = input6.nextInt();
switch (choice6) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
sixSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
System.out
.println("Which of the following is one of the seven drawfs?");
System.out.println("1 Scrooge McDuck");
System.out.println("2 Dopey");
System.out.println("3 Louie");
Scanner input7 = new Scanner(System.in);
int choice7 = input7.nextInt();
switch (choice7) {
case 1:
System.out.println("Wrong selection");
--counter;
break;
case 2:
System.out.println("Hi Ho, you picked the correct one");
sevenSelection = true;
break;
case 3:
System.out.println("Wrong selection");
--counter;
break;
default:
System.out.println("Invalid selection");
--counter;
break;
}
if (firstSelection == true && secondSelection == true
&& thirdSelection == true && fourthSelection == true
&& fiveSelection == true && sixSelection == true
&& sevenSelection == true) {
System.out.println("You earned a gold star!");
} else {
System.out.println("\nYou did not get all correct.");
}
}
}
The fact that you realized you might be thinking about the concept incorrectly and asked for help is a good thing.
Read the following to get familiar with loops in Java.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
To answer your question, yes, you can change the content of a loop as you run it. That's what variables are for. You can modify their values as your program runs. Look at this sample. The variable i increments with every iteration of the loop. The variable outsideLoop also changes inside the loop. Play with this and you'll start to understand.
class ForDemo
{
public static void main(String[] args)
{
int outsideLoop = 0;
for (int i = 1; i < 11; i++)
{
outsideLoop += i;
System.out.println("Count is: " + i);
}
System.out.println("Outside loop is: " + outsideLoop);
}
}
You've got a good starting point for the process of printing the selection, getting user input, and validating user input. Repeat that chunk (in a loop) 7 times.