Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
class Que{
char q[];
int front , rear ;
Que(int size){
q = new char[size];
front = rear =0;
}
void push(char ch){
if(rear == q.length){
System.out.println("Que is Full");
}
else{
q[rear++]=ch;
System.out.println(ch + " Added");
}
}
void pop(){
if(front==rear){
System.out.println("Que is Empty");
}
else{
System.out.println(q[front] + " Is being popped ");
front++;
}
}
void disp(){
char temp = q[front];
for(int i = front;i<rear ; i++)
{
System.out.println(q[i]);
}
}
}
class Example{
public static void main(String args[])
throws java.io.IOException{
Que Sample1 = new Que(10);
int opt = 1;
char j,k;
while(opt!=0){
System.out.println("1-Add , 2 - Pop , 3 - Display");
j = (char) System.in.read();
if(j=='1'){
System.out.println("What to push ?");
k = (char)System.in.read();
Sample1.push(k);
}
else if(j=='2'){
Sample1.pop();
}
else if(j=='3'){
Sample1.disp();
}
else if(j=='4'){
opt = 0;
}
else{ System.out.println("Try Again");}
}
}
}
This is not working . When I compile and run it it show me the main menu and as soon as I press 1)ADD - it skips displaying 'Added' msg from the function .
What am I doing wrong?
When I press 1 (Add) it should ask me "what To Push " which it does, but then does not wait for my input and plays loop again .
So this is what displays --
1)ADD
2)Pop
3)Display
1
What to push ( takes no input)
Added (automatically displayed)
1)ADD
2)Pop
3)Display
What are you typing in your terminal ?
If you type more than one character for example 11 or even 1<Enter>, your second call to System.in.read() will immediatly return with this second character: 1 or <Enter>.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I need to find the maximum and minimum statistics for the student marks from a list. The list contains the student ID and the student Mark. Im not too sure how to do this.
This is the code for reading in the file and creating the list:
public void readFile(Scanner in)
{
inputStudentID = null;
inputMark = 0;
try
{
File file = new File("Marks.txt");
in = new Scanner(file);
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
System.out.println("in " + System.getProperty("user.dir"));
System.exit(1);
}
while (in.hasNextLine())
{
String studentRecord = in.nextLine();
List<String> values = Arrays.asList(studentRecord.split(","));
String inputStudentID = values.get(0);
String sInputMark;
sInputMark = values.get(1);
int inputMark = Integer.parseInt(sInputMark);
addStudent(inputStudentID, inputMark);
}
in.close();
}
Assuming you have some indexed list since addStudent doesn't really tell me much (else just apply the logic to whatever you have):
private int getMax(ArrayList<Integer> marks) {
int max = marks.get(0);
int index = 0;
for(int x = 1; x < marks.size(); x++) {
if(max < marks.get(x)) {
max = marks.get(x);
index = x;
}
}
return index;
}
Better solution:
You could simply do Collections.max(list) – Imaginary Pumpkin
Yet I'll still leave mine to show the logic of how to find a max.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying to create a simple TicTacToe game but I am having trouble having the program recognize a row of x's.
If you look at the following line of code:
public void run() {
setFont("Helvetica-40");
fillArray();
checkWinner();
run();
}
//fill array:
public void fillArray() {
for(int row = 0; row<3; row++) {
String fill = readLine("");
for(int col=0; col<3;col++) {
char xo = fill.charAt(row);
String xoString = Character.toString(xo);
ticTac[row][col] = xoString;
}
}
}
public boolean checkWinner() {
// array[row][col]
if (ticTac[0][0].equals("x") && ticTac[0][1].equals("x") && ticTac[0][2].equals("x")) {
println("Player X wins!");
return true;
} else
println("no x");
return false;
}
String[][] ticTac = new String[3][3];
}
I think you have a mistake, you have to change one of these two things :
1.
if (ticTac[0][0].equals("x") && ticTac[0][1].equals("x") && ticTac[0][2].equals("x"))
to
if( ticTac[0][0].equals("x") && ticTac[1][0].equals("x") && ticTac[2][0].equals("x"))
or
2.
char xo = fill.charAt(row);
to
char xo = fill.charAt(col);
just one of them, it depend on your design
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
How do recursive calls work with stacks? I have this sample code in which line B prints B 654321, c prints C, d prints D 2468 and e throws an exception. I do not understand why the program is printing those outputs! For instance, in line B, doesn't s become 0 as a result of the stack? Thank you
public class Problem1 {
public static void main(String args[]) {
Stack<Integer> s = setStack(5); printStack("A", s); // line A
s = setStack(6); stackStack(s); printStack("B", s); // line B
s = setStack(8); cutStack(s); printStack("C", s); // line C
s = setStack(8); s = cutStack(s); printStack("D", s); // line D
s = setStack(7); s = cutStack(s); printStack("E", s); // line E
}
public static Stack<Integer> setStack(int n) {
Stack<Integer> ans = new Stack<>();
for (int i = 1; i <= n; i++)
ans.push(i);
return ans;
}
public static void printStack(String tag, Stack<Integer> s) {
System.out.print(tag + " ");
while (!s.empty()) System.out.print(s.pop());
System.out.println();
}
public static Stack<Integer> cutStack(Stack<Integer> s)
{
Stack<Integer> ans = new Stack<>();
while (!s.empty()) {
ans.push(s.pop());
s.pop();
}
s = ans; return s;
}
public static void stackStack(Stack<Integer> s) {
if (s.empty()) return;
int x = s.pop();
stackStack(s);
s.push(x);
}
}
For stackStack, consider a smaller stack: 123 (with 3 on the top of the stack).
Let F1 be the first call to stackStack(), F2 be the nested call, and so on.
F1: stackStack(123) pops out the 3 and stores it in x. So x_1=3 and s=12
F2: stackStack(12) is now called. So x_2=2 and s=1
F3: Now stackStack(1) is called. Now, x_3=1 and s is empty.
Now, s is empty. So the control simply returns to F3.
F3 then pushes x_3 =1 onto the empty s. So s=1 and the control returns to F2.
F2 pushes x_2=2 onto s=1. So s=12 and the control returns to F1.
F1 pushes x_1=3 onto s=12. So s=123.
You've just ended up with the original stack and printStack() simply prints out 321.
This should give you an idea of how recursion works in general.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I've been trying to write a simple program in java to find time complexity of a program.A program whih just searches for "for" loop or "while" loop and prints the no of iteration such as O(n) or O(2n) etc.
I got the i/p program in textarea.Is there any way by which i could do the opertaion?
Please any one help me.
This is not full proof, but would work for you
import java.util.StringTokenizer;
public class Complexity {
public static void main(String[] args) {
String input = "for(i=0;i<10;i++)\n{\nfor(i=0;i<10;i++)\n{\nfor(i=0;i<10;i++)\n{\n}\n}\n}\nfor(i=0;i<10;i++)\n{\n}\nfor(i=0;i<10;i++)\n{\nfor(i=0;i<10;i++)\n{\n}\n}";
int open_bracket=0;
StringTokenizer t = new StringTokenizer(input);
String result = "";
String token="";
int current = 0;
System.out.println("CODE \n"+input);
while(t.hasMoreTokens())
{
token = t.nextToken();
if(token.equals("{")) open_bracket++;
if(token.equals("}")) open_bracket--;
if(token.length()>=3) if(token.substring(0, 3).equals("for")) current++;
if(open_bracket==0&&token.equals("}"))
{
result += " n^"+current+" +";
current = 0;
}
}
if(result.length()>0) result = result.substring(0, result.length()-1);
result = "O( "+result+")";
System.out.println("RESULT = "+result);
}
}
OUTPUT
CODE
for(i=0;i<10;i++)
{
for(i=0;i<10;i++)
{
for(i=0;i<10;i++)
{
}
}
}
for(i=0;i<10;i++)
{
}
for(i=0;i<10;i++)
{
for(i=0;i<10;i++)
{
}
}
RESULT = O( n^3 + n^1 + n^2 )
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am writing a TicTacToe game, and it repeatedly prompts the user for a move. It is asking for a selection more than 9 times and I am not sure why.
My design has a 2-dimensional array to store information about the current state of the board, use JOptionPane to ask users for selection of the board (1 for top left, 2 for top middle, 3 for top right, 4 for middle left, etc). After every move, output into the console the current board. If a spot is already used, prompt the user again. (There is no need for a winner check, as we were told to do this another time.
Here is my entire code:
import javax.swing.JOptionPane;
// Basic TicTacToe game.
public class TicTacToe1 {
public static void main(String[] args){
// Hello there!
Object[] options = { "I'm ready to play!",};
Object[] options2 = { "Select another number.",};
JOptionPane.showOptionDialog(null,"To play TicTacToe, use the numbers 1 to 9 to choose where you place a mark. Are you ready?","TicTacToe1",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
// Define the board.
char board[][] = new char[3][3];
// Zero out the board.
for(int a=0; a<3; a++) {
for(int b=0; b<3; b++) {
board[a][b] = ' ';
}
}
// Print an initial, clean board.
print(board);
// Use a for loop to ask for the selection and nest the selector into it.
for(int i=1; i<10 ; i++) {
if ((i%2) == 1) {
boolean goahead = true;
while (goahead) {
int selection = Integer.parseInt(JOptionPane.showInputDialog(null,"Where do you want to place an X?"));
if ((board[(((selection-1)-((selection-1)%3))/3)][(selection-1)%3]=='X') || (board[(((selection-1)-((selection-1)%3))/3)][(selection-1)%3]=='O')) {
JOptionPane.showOptionDialog(null,"I'm sorry, the number "+selection+" spot is already being used.","TicTacToe1",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options2, options2[0]);
} else {
goahead = false;
board[(((selection-1)-((selection-1)%3))/3)][(selection-1)%3] = 'X';
print(board);
}
}
}
if ((i%2) == 1) {
boolean goahead = true;
while (goahead) {
int selection = Integer.parseInt(JOptionPane.showInputDialog(null,"Where do you want to place an O?"));
if ((board[(((selection-1)-((selection-1)%3))/3)][(selection-1)%3]=='X') || (board[(((selection-1)-((selection-1)%3))/3)][(selection-1)%3]=='O')) {
JOptionPane.showOptionDialog(null,"I'm sorry, the number "+selection+" spot is already being used.","TicTacToe1",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options2, options2[0]);
} else {
goahead = false;
board[(((selection-1)-((selection-1)%3))/3)][(selection-1)%3] = 'O';
print(board);
}
}
}
// didsomeonewinyet(board);
}
}
// Make a helper function named print to print the board
public static void print(char board[][]){
for(int a=0; a<3; a++) {
for(int b=0; b<3; b++) {
System.out.print("|"+board[a][b]+"|");
}
System.out.println();
}
System.out.println();
}
// Winner checker.
// public static void didsomeonewinyet(char board[][]){
// Manually checking will yield 16 cases (2 diagonal, 3 horizontal, 3 vertical, either X or O), which is not that bad.
// }
}
Why does it ask for a selection too many times?
Your if conditions in the for loop are the same so they both occur during the same iteration of the loop:
if ((i%2) == 1) {
one of the if statements should be:
if ((i%2) == 0) {
depending on who you want to go first.
Alternatively you could just use an else statement:
if ((i%2) == 1) {
//code for x to go
}else {
//code for y to go
}