So im a pretty new programmer so forgive me if i make any mistakes.
I need to make a higher or lower game for my class but im a little bit stuck now.
The purpose of this whole game is to guess the number which is random generated by the computer. But here's the tricky part, the user only needs to get 8 chances to guess the number right. If not the game must end and print something like: you lost, the number was.....
I came this far;
public static void main(String[] args) {
int timesGuessed = 0;
int randomNummer = (int)(Math.random()*100);
int number;
boolean won = true;
Scanner input = new Scanner(System.in);
do{
System.out.print("Guess the number: ");
number = input.nextInt();
timesGuessed++;
if(timesGuessed == 8){
won = false;
}
if(number > randomNummer){
System.out.println("Lower!");
}
else if(number < randomNummer){
System.out.println("Higher!");
}
}
while(number != randomNummer);
if(won == true){
System.out.println("The number is guessed right in " + timesGuessed + " attemts.");
}
else{
System.out.println("You lost. The number was " + randomNummer + ".");
}
}
Now the game lets you finish even though you already had 8 chances. Thats what i want to change. It needs to stop when you failed the eight time.
Thank you for the help, it would be very appreciated.
You also need to check your won variable in the condition of your loop. You may also want to add an else so it doesn't print "Higher" or "Lower" after the final try.
Related
I'm confused i'm suppose to get a positive int from user using recursion, the user can input words, and also numbers.(Words and negative numbers are invalid), Not sure what i'm doing wrong.
I'm sorry forgot to ask the question, well i'm getting compiler error, when I try to compile it, something is wrong with my Scanner, I was reading an it says I have to use an argument for the users input, I'm not sure how to, and the second question was, how do I let the code to repeat if the user inputs n<0 or a word, such as taxes. thank you
import java.util.*;
public class Recursion {
private static int getPositiveInt(Scanner keyboard) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a positive interger, n");
int n = keyboard.nextInt();
if (n > 0) {
return n;
}
else { //here the code should rerun if invalid input, but I cant figure it out
System.out.println("enter a positive number");
}
}
}
If I understood your question correctly, you want this function to run untill it will read a valid number.
To do this all you need to change is:
else { //here the code should rerun if invalid input, but I cant figure it out
System.out.println("enter a positive number");
}
to:
else {
//call the function again
return getPositiveInt(Scanner keyboard)
}
in my program a simple shopping application for my lab exercise, i just calculated the price of items inside a for loop but when i try to print it outside it is not getting printed...pls give me some suggestion.
for (int i = 1; i < 7; i++) {
String selection = request.getParameter("a" + i);
if (selection.equals("l")) {
price = Integer.parseInt(request.getParameter("b" + i));
total = total + price;
out.println("<h3>You have purchased the item:<br>Price is:</h3>" + price);
}
}
out.println("THE TOTAL IS"+total);
out.println("</body>");
out.println("</html>");
String selection = request.getParameter("a" + i);
//Here print the selection there is the problem
if (selection.equals("l")) ///Here alway it is false thats why you are getting this.
{
}
It gets not printed because its out of scope. Your total
variable only lives within the loop.
You have basic programming skills and know about variable scope, right?
http://www.java-made-easy.com/variable-scope.html
I'm attempting to make a sudoku solver for the sake of learning to use recursion. I seem to have gotten most of the code to work well together, but when I run the program, I get a windows error telling me that the program has stopped working. A debug indicates a segmentation fault, and I saw elsewhere that this can be caused by too many recursions. I know this is a brute-force method, but again, I'm more worried about getting it to work than speed. What can I do to fix this to a working level?
struct Playing_grid {
//Value of cell
int number;
//wether the number was a clue or not
bool fixed;
}
grid[9][9];
void recursiveTest(int row, int column, int testing)
{
//first, check to make sure it's not fixed
if(grid[row][column].fixed == false)
{
if((checkRow(testing, row) | checkColumn(testing, column) | checkBox(testing,boxNumber(row,column)) | (testing > 9)) == 0)
{
grid[row][column].number = testing;
moveForward(row,column,testing);
recursiveTest(row, column, testing);
}
else if(testing < 9)
{
testing ++;
recursiveTest(row, column, testing);
}
else if(testing == 9)
{
while(testing == 9)
{
moveBack(row,column,testing);
while(grid[row][column].fixed == true)
{
{
moveBack(row,column,test);
}
}
testing = grid[row][column].number;
recursiveTest(row,column,testing);
}
}
}
else
{
moveForward(row,column,testing);
recursiveTest(row,column,testing);
}
}
void moveForward(int& row, int& column, int& test)
{
if(column < 8)
{
column ++;
}
else if((column == 8) & (row != 8))
{
column = 0;
row ++;
}
else if((column == 8) & (row == 8))
{
finishProgram();
}
test = 1;
}
void moveBack(int& row, int& column, int& test)
{
grid[row][column].number = 0;
if(column > 0)
{
column --;
}
else if((column == 0) & (row > -1))
{
column = 8;
row --;
}
else
{
cout << "This puzzle is unsolveable!" << endl;
}
test++;
}
I tried to include all the relevant pieces. I essentially create a 9x9 matrix, and by this point it is filled with 81 values, where empty slots are written as 0. After confirming the test value is valid in the row, column and box, it fills in that value and moves onto the next space. Whenever it runs to 9 and has no possible values, it returns to the previous value and runs through values for that one.
So as to not overwrite known values, the recursive function checks each time that the value of the grid[row][column].fixed is false.
I'd appreciate any insight as to cleaning this up, condensing it, etc. Thanks in advance!
Edit: To exit the recursive loop, when the function is called to move forward, if it has reached the last cell, it completes (saves + outputs) the solution. The code has been adjusted to reflect this.
I'd normally try to fix your code, but I think in this case it's fundamentally flawed and you need to go back to the drawing board.
As a general rule, the pseudocode for a recursive function like this would be
For each possible (immediate) move
Perform that move
Check for win state, if so store/output it and return true.
Call this function. If it returns true then a win state has been found so return true
Otherwise unperform the move
Having tried every move without finding a win state, return false.
can some one help me to rectify this error i have am using VS2010 ASP.Net C#3.0 i found this could on net but it is not working as it give me the error as show in the Screen shot. I am not able to understand the error message
Code reference from http://weblogs.asp.net/abdullaabdelhaq/archive/2009/06/27/displaying-arabic-number.aspx
CODE :
protected void Button1_Click(object sender, System.EventArgs e)
{ //Call Function
this.Label1.Text = "Arabic Number : <b>" + TranslateNumerals(this.TextBox1.Text) + "</b>";
}
public static string TranslateNumerals(string sIn)
{
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decoder = null;
utf8Decoder = enc.GetDecoder();
dynamic sTranslated = new System.Text.StringBuilder();
char[] cTransChar = new char[2];
byte[] bytes = {217,160 };
// Start Converting characters into Arabic mode.
char[] aChars = sIn.ToCharArray();
foreach (char c in aChars)
{
if (char.IsDigit(c))
{
bytes[1] = 160 + Convert.ToInt32(char.GetNumericValue(c));
utf8Decoder.GetChars(bytes, 0, 2, cTransChar, 0);
sTranslated.Append(cTransChar[0]);
}
else
{
sTranslated.Append(c);
}
}
return sTranslated.ToString();
}
The compiler is complaining about your request to implicitly convert the result of the integer addition (160 + Convert.ToInt32...) to a byte. This is a narrowing conversion; integers have a wider range than bytes do, and the compiler wants you to acknowledge, with an explicit cast operator, that you're aware that this could produce runtime errors.
Assuming that adding 160 actually does something useful to a character, I'd advise using something like this instead.
if (c >= '0' && c <= '9')
{
bytes[i] = (byte)((int)c + 160);
}
...which will properly produce, as the i'th value of the array bytes, a byte with a value 160 greater than the char c, if c represents an ASCII digit between 0 and 9.
Don't use the function char.IsDigit, which will return true even if c is a digit outside of the ASCII digit range. I don't run into this much, but since you're explicitly writing multilingual code, you'll want to handle that case.
I haven't reviewed the rest of the post you link to, but given these two quite obvious errors, I wouldn't put much faith in the correctness of the rest of it, frankly.
You could add a cast like (byte) in front of the 160.
I'm a little confused why such a large function is required to do that.
Updated answer:
Given that there are only 10 possible numerals to convert between, you can do something like this to make it slightly more readable. I think, anyway, I don't usually code in c#, and I'm on a mac right now... feel free to bash my code.
public static string TranslateNumerals(string sIn)
{
var sb = new System.Text.StringBuilder();
char[] arabic = { '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'};
foreach (char c in sIn) {
int idx;
// if it wasn't a number, just append it, otherwise convert it
if(!Integer.tryParse("" + c, idx)) {
sb.Append(c);
} else {
sb.Append(arabic[idx]);
}
}
return sb.toString();
}
// backwards array (which appears frontwards here)
{ '٩','٨','٧','٦','٥','٤','٣', '٢', '١', '٠'};
Alright, so I'm trying to make a Java program to solve a picross board, but I keep getting a Stackoverflow error. I'm currently just teaching myself a little Java, and so I like to use the things I know rather than finding a solution online, although my way is obviously not as efficient. The only way I could think of solving this was through a type of brute force, trying every possibility. The thing is, I know that this function works because it works for smaller sized boards, the only problem is that with larger boards, I tend to get errors before the function finishes.
so char[][] a is just the game board with all the X's and O's. int[][] b is an array with the numbers assigned for the picross board like the numbers on the top and to the left of the game. isDone() just checks if the board matches up with the given numbers, and shift() shifts one column down. I didn't want to paste my entire program, so if you need more information, let me know. Thanks!
I added the code for shift since someone asked. Shift just moves all the chars in one row up one cell.
Update: I'm thinking that maybe my code isn't spinning through every combination, and so it skips over the correct answer. Can anyone verify is this is actually trying every possible combination? Because that would explain why I'm getting stackoverflow errors. On the other hand though, how many iterations can this go through before it's too much?
public static void shifter(char[][] a, int[][] b, int[] clockwork)
{
boolean correct = true;
correct = isDone(a, b);
if(correct)
return;
clockwork[a[0].length - 1]++;
for(int x = a[0].length - 1; x > 0; x--)
{
if(clockwork[x] > a.length)
{
shift(a, x - 1);
clockwork[x - 1]++;
clockwork[x] = 1;
}
correct = isDone(a, b);
if(correct)
return;
}
shift(a, a[0].length - 1);
correct = isDone(a, b);
if(correct)
return;
shifter(a, b, clockwork);
return;
}
public static char[][] shift(char[][] a, int y)
{
char temp = a[0][y];
for(int shifter = 0; shifter < a.length - 1; shifter++)
{
a[shifter][y] = a[shifter + 1][y];
}
a[a.length - 1][y] = temp;
return a;
}
Check Recursive call.and give the termination condition.
if(terminate condition)
{
exit();
}
else
{
call shifter()
}