import java.util.*;
public class GuessNumber{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
int x = 0;
String num = "65854"; // This is the secret code
String s;
System.out.println("This program asks you to guess the code of 5 digits. ");
System.out.println("You have 5 attempts. ");
for(int i=0; i<5; i++){
do{
s = in.nextLine();
for(int c=0; c<s.length(); c++){
if(s.charAt(c)==num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x
x++;
}
System.out.println("Number of correct digits in right position: " + x); // here the execution goes out of bounds
}
while(!s.equals(num));
System.out.println("Congrats! You guessed the secret code. ");
System.exit(0);
}
}
}
I tried to create a simple java program which should allow user to guess a prefixed code of five digits (with only five attempts). The do-while loop shows correct values only for the first two attempts, then it goes out of bounds (shows values>5, which are impossible for a code of only 5 digits). Can somebody explain why?
Remove your do-while loop. It will run till user guesses right code.
Insert following code to check length of string
if(s.length()!=5){
System.out.println("code should be of length 5");
continue;
}
You can add more restrictions for no characters in input string.
Also reset x at start of outer loop every time.
Also check if input string is correct in every outer loop
if(s.equals(num)){
System.out.println("Congrats! You guessed the secret code. ");
System.exit(0);
}
this code is gonna run for EVER since you enter the true code , because you have do-while that its condition say !s.equals(num) , so you must remove the do-while at first , it is not neccessary , when your predicted code is equal to the num then the variable x must equal to 5 , so you terminate your program using a return statement after the printing success. be aware of the value of x , it must be equal to zero at each iteration , i mean x=0!
for(int i=0; i<5; i++){
s = in.nextLine();
if(s.length!=5){
System.out.println("code should be of length 5");
continue;
}
x = 0;
for(int c=0; c<5; c++){
if(s.charAt(c)==num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x
x++;
}
System.out.println("Number of correct digits in right position: " + x); // here the execution goes out of bounds
if(x==5){
System.out.println("Congrats! You guessed the secret code. ");
return;
}
}
System.out.println("Sryy !! :((");
Current Code -
for (int i = 0; i < 5; i++) {
do {
s = in.nextLine();
for (int c = 0; c < s.length(); c++) { // the length of s can exceed 5 as of **num = "65854"**
if (s.charAt(c) == num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x
x++;
System.out.println("Number of correct digits in right position: " + x);
}
}
while (!s.equals(num)); // this ensures currently N number of attempts NOT JUST 5 as stated otherwise.
System.out.println("Congrats! You guessed the secret code. ");
System.exit(0); // with this line the for loop would execute just once
}
Suggested Code -
String s;
int count = 0;
int x;
do {
x = 0;
if (count >= 5) { break; } // 5 attempts
s = in.nextLine();
String formattedNumber = String.format("%05d",
Integer.parseInt(s)); // make sure the input is of 5 digit integer (padding here with 0's)
for (int c = 0; c < formattedNumber.length(); c++) {
if (formattedNumber.charAt(c) == num.charAt(c)) {
x++;
}
if (x == 5) { // correct guess if all chars are equal
System.out.println("Congrats! You guessed the secret code.");
break; // break if guessed correct
} else {
System.out.println("Number of correct digits in right position: " + x);
}
}
count++; //next attempt
} while (!s.equals(num)); //input not equals the desired, next attempt
Related
import java.util.*;
public class happy_number
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
String num = in.next();
for (int i = 0; i < num.length(); i++){
double index = num.charAt(i);
(double)index = Math.pow((double)i,2);
System.out.println(index);
}
}
}
For some reason, the second line in the for loop is returning as unexpected type– required: variable found: value. Any insight?
error: image of the error
It doesn't continue to ask you for an input. What is happening here is that the execution get's struck in an infinite loop, for certain types of inputs (in this case non-magic numbers).
For Eg.:
Let's take the example 44, below will be the values for each iteration in the for loop.
num
num1
num2
Start
44
-
-
After 1st iteration
8
4
4
After 2nd iteration
8
8
0
After 3rd iteration
8
8
0
…
…
…
…
We can see that the execution get's struck in the loop.
You have to exit out of the loop when you get such inputs.
One way to exit out of the loop is to add a condition in the for loop.
Another way is to add an if statement inside the for loop, and exit out of the loop based on the condition.
You have to decide what condition you should use in order to exit the loop, based on your problem statement.
Look on to the loop and the value populated inside. There is no breaking condition found and the correct test for a magic number:
A simple code:
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number to check: ");
int num = in.nextInt();
int n = num;
while (n > 9) {
int sum = 0;
while (n != 0) {
int d = n % 10;
n /= 10;
sum += d;
}
n = sum;
}
if (n == 1)
System.out.println(num + " is Magic Number");
else
System.out.println(num + " is not Magic Number");
}
So i'm trying to write a programme whereby the user enters two integers .
The programm is supposed to subtract 5 from the second integer entered in a loop depending on the first number entered. (so the first number should dictate how many times it will loop.
public int getScheme1() {
while (Mark >= 20) {
System.out.printf((Mark = Mark - 5) + Mark + " ");
}
for (int Day = 1; Day <= 20; Day++) {
System.out.printf("( " + Day + "):" + Mark + " ");
}
return Mark;
}
All my code does is print the user's second input integer 20 times.
Also im sorry im totally new to java
you must call this function in your main program.
public int getScheme1 (int num1, int num2){
for(int i = 1 ; i >= num1 ; i++ ){
num2 -= 5;
}
return num2;
}
to call it simply use getScheme1(num1,num2);
Based on what you described, you are looking for something like this:
Scanner input = new Scanner(System.in); //create a scanner to get user input
int a1 = input.nextInt(); //get 2 ints from the user
int a2 = input.nextInt();
for(int i = 0; i < a1; i++) { //loop as many times as a1 specifies
a2-=5; //subtract 5 from a2 each time it loops
}
System.out.println(a2);
The key part of this is the for loop, which works in the following:
for(variable; condition; increment),
basically, what the for loop I wrote is saying:
Set i = 0 at the start. If i is meeting the condition (in this case being less then a1), then loop. The increment part is called when it finishes running the code block, it now makes i bigger (in this case 1 bigger using ++) Another important thing to note is that the first time the loop runs, i = 0.
So for example, if I wanted to loop 10 times, with a starting variable of 3 and incremented 5 each time, I'd do:
for(int i = 3; i <= 53; i+=5) {}
Also, one last thing: please look at variable naming conventions, variables shouldn't start with caps like that, they should be camelCase
I'm creating a java project called magicsquare and I've searched online on how to do it. Now, I'm trying to understand how the 2nd loop works, I know that it prints and align the magic square, but I don't know the details. I already know the first one. I would really appreciate if someone explains to me the 2nd loop. Thanks!
import java.util.*;
public class Magicsquare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try{
int N;
System.out.print("Enter a number to create a Magic Square: ");
N=input.nextInt();
if (N % 2 == 0){
System.out.print("N must be an Odd number!");
}
else{
int[][] magic = new int[N][N];
int row = N-1;
int col = N/2;
magic[row][col] = 1;
for (int i = 2; i <= N*N; i++) {
if (magic[(row + 1) % N][(col + 1) % N] == 0) {
row = (row + 1) % N;
col = (col + 1) % N;
}
else {
row = (row - 1 + N) % N;
}
magic[row][col] = i;
}
for (int c = 0; c < N; c++) {
for (int r = 0; r < N; r++) {
if (magic[r][c] < 10) System.out.print(" "); // for alignment
if (magic[r][c] < 100) System.out.print(" "); // for alignment
System.out.print(magic[r][c] + " ");
}
System.out.println();
}
}main (null);
}catch (Exception e){
System.out.print("Invalid Input!");
}
}
}
Well, first the obvious. The part about < 10 and < 100: if a number is between 0 and 9, it's only going to print out one digit. If it's between 10 and 99, it's going to print out two. And if it's between 100 and 999, it'll print out using three digits. (It seems as if this code is written to assume it will only encounter numbers between 0 and 999. Generally speaking, it's best to ensure that somehow rather than just hope.)
So, with the if statements and their extra spaces, a "5" will print out as " 5" (note the two leading spaces for a total of three characters). 25 will print out as " 25" (again, three characters) and 125 as "125" (three digits again). Since all of the numbers print out using three characters, everything will line up neatly in columns.
What confuses me is that you're iterating over c first, then r. This seems to say that you're printing out the first column on a single row on the screen, then the second column as a second row, and the third column as a third row. I.e. the whole thing has been rotated on a diagonal. But maybe that's just a naming issue.
This is what I have so far. I am supposed to write this code with a For loop and if/else statement, but /i am stuck on how to do it properly. It would be nice if someone can tell me how to properly use a For loop and if/else statement together instead of giving the answer:
import java.util.*;
public class SumEvenOdd
{
public static void main(String []args)
{
Scanner keyboard= new Scanner(System.in);
int counter;
int i= 0;
int num=0;
int sumOdd= 0;
int sumEven= 0;
System.out.println("Enter integers other then Zero: ");
num=keyboard.nextInt();
System.out.println("The numbers you entered are: ");
for (i =num; i !=0; i=i)
{
if (i % 2 == 0)
sumEven = sumEven + i;
else
sumOdd = sumOdd + i;
i = keyboard.nextInt();
}
System.out.println("Even sum: " + sumEven);
System.out.println("Odd sum: " + sumOdd);
}
}
Your loop never executes because your loop condition is false to begin with:
for (i =num; i !=0; i=i) // i already equals 0 so i != 0 equates to false
You also aren't incrementing or decrementing with i=i so even if your condition was true you'd be stuck in an infinite loop. Use i++ to increment the value of i by 1 in each iteration of your for loop.
Also, you're only taking in one number from the user. One simple way of handling this would be to first ask the user how many numbers they want to enter first, then use that input to loop that many times asking for the numbers to sum. For example:
System.out.println("How many numbers do you want to enter? ");
num=keyboard.nextInt();
int[] addThese = new int[num]; // create an array of size num to store numbers
for(int i = 0; i < num; i++) {
System.out.print(": ");
addThese[i] = keyboard.nextInt();
}
// now use your for loop to iterate over addThese[] and find your sums
...
EDIT
You've confused yourself (and me) with your print statements and lack thereof. Your program runs fine but I don't think you're realizing it because of this.
Add something like this inside your loop so you know it's waiting for input:
if (i % 2 == 0)
sumEven = sumEven + i;
else
sumOdd = sumOdd + i;
System.out.print(": "); // <-- let the user know you're expecting more input
i = keyboard.nextInt();
You can use an array like I used above to store the user input so you actually can tell the user what numbers they entered.
In your application you do not need a for loop as you are breaking the loop as long you dont enter 0.
for loops is used to iterate through collections (for each loop) or iteratively increment a counter till it satisfies the break(classic for loop).
A do while(i!=0) loop would be more appropriate in your scenario.
If you want the answer in while loops
import java.util.*;
/*
EXPLANATION
Question: write a program that reads a set of integers and tells the sum of the even and odd numbers
First: Initialize 4 variables(all integers)
Second: Take input and print title
Third: Take a while loop that will run when i is smaller than a
Fourth: take inputs of the numbers and check for condition od or even and add the numbers
Fifth: Break the while loop if input =
*/
public class EvenOddSum
{
public static void main(String[]args)
{
//initializing variables
int InputNums = 0, OddNums = 0, EvenNums = 0, loopingVar = 0, PrintAmount;
//initializing scanner class
Scanner scanner = new Scanner(System.in);
//Input using Scanner
System.out.print("How many numbers you want to input: ");
PrintAmount = scanner.nextInt();
//Loop to execute if PrintAmount is bigger than or equal to The loop Variable
while(loopingVar <= PrintAmount)
{
//increase Loop Variable by 1 if it is smaller than PrintAmount
loopingVar++;
//The input which will be sorted into odd or even
System.out.print("Please input a number : ");
InputNums = scanner.nextInt();
//Conditional statements to Sort Input into Odd or even
if (InputNums % 2 == 0)
{
//store input numbers into OddNums var if it is not divisible by 2
OddNums = OddNums + InputNums;
}
else
{
//store input numbers into EvenNums var if it is divisible by 2
EvenNums = EvenNums + InputNums;
}
if(loopingVar == PrintAmount)
{
//If the loop variable is equal to the print amount the break will end the loop
break;
}
}
//if the condition is true the sums are printed and the code is stopped
if (loopingVar == PrintAmount)
{
System.out.println("Sum of even numbers is : " + OddNums);
System.out.println("Sum of odd numbers is : " + EvenNums);
System.exit(0);
}
//if InputNums is smaller than 0 there has been some error in the code
if (InputNums < 0)
{
System.out.print("Invalid input");
System.exit(0);
}
}
}
Scanner input = new Scanner(System.in);
int num;
int i;
int x = 0;
int y = 0;
System.out.print("How many numbers you want to input: ");
i = input.nextInt();
for (;;) {
i--;
System.out.print("Please input a number : ");
num = input.nextInt();
if (num % 2 == 0) {
x = x + num;
} else {
y = y + num;
}
if (num < 0) {
System.out.print("Inivald input");
System.exit(0);
}
if (i == 0) {
System.out.println("Sum of even numbers is : " + x);
System.out.println("Sum of odd numbers is : " + y);
System.exit(0);
}
}
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// printing the sum of even and odd number input from the user
int evensum = 0 ;
int oddsum = 0 ;
System.out.println("Enter the number:");
for(int n1= sc.nextInt(); n1>0; n1=sc.nextInt()) {
if(n1 % 2 == 0) {
evensum+=n1 ; // evensum = evensum + n1 ;
}
else {
oddsum+=n1 ; // oddsum = oddsum + n1 ;
}
System.out.println("Sum of even number is :"+evensum);
System.out.println("Sum of odd number is :"+oddsum);
// asking for continuing y or n?
System.out.println("Do you want to continue ? yes = 1 or no = 0");
int choice = sc.nextInt();
if(choice==1) {
System.out.println("Enter the number :");
}
else {
System.out.println("End");
break;
}
}
System.out.println("Sum of even number is :"+evensum);
System.out.println("Sum of odd number is :"+oddsum);
}
}
I am trying to define a main method that asks the user for an input (x). If the value is >= 0, it asks for another input (y). But if the value was < 0 the player has three chances to enter a correct value, otherwise he exits the game. This is what I have until now:
Scanner keyboard = new Scanner(System.in);
final int NUMBER_OF_TRIES = 3;
boolean correctNumber = false;
int attemptNumber = 0;
int x = keyboard.nextInt();
keyboard.nextLine();;
while (x < 0)
{
System.out.println("Must not be negative.");
System.out.print("Initial x: ");
int x = keyboard.nextInt(); keyboard.nextLine();
if (x >= 0)
{
correctNumber = true;
}
else
{
System.out.println("Incorrect answer");
attemptNumber++;
}
if(x < 0 && attemptNumber == NUMBER_OF_TRIES)
{
System.out.println("Too many errors. Exiting.");
break;
}
But as I already defined 'x', I cannot do it again inside the loop. I think my problem is really simple but I cannot figure out a way to fix that. Does anyone know how?
It looks like this might work if you just remove "int " from line 12. You don't need to declare the variable there since you have already declared it.
If the condition to exit the loop is to enter a negative value 3 times, then use that as the actual condition. Code should be easier to read as well.
incorrectAttempts = 0;
while (incorrectAttempts < 3)
{
get new value
value invalid?
yes: incorrectAttempts = incorrectAttempts + 1;
no: do anything else;
}