for loop ( Java) [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am making a guessing game for fun. For some reason, the code in the for loop never processes. I didvided it into three parts. Please let me knowCan someone help me? I have checked and the code doesnt proceed int the for loop. I am certain there is nothing wrong with the for loop. Thanks for your hwlp Thanks
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class Guess {
public static Random r = new Random();
public static BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
public static final String YES_S = "y";
public static final String NO_S = "n";
public static void main(String [] args) throws IOException {
boolean menu = true;
boolean start = false;
boolean end = false;
boolean ans = true;
boolean rand = true;
int num = -1;
int guessNum = -1;
while(menu) {
System.out.println( "Start game [ y ]:");
String input = in.readLine();
if(input.equals(YES_S)) {
menu = false;
start = true;
end = false;
}
}
while(start) {
while(ans) {
while(rand) {
num = r.nextInt(11);
rand = false;
}
for (int i = 0; i > 3; i++) {
System.out.println( " Guess a number from 0 to 10 :");
String input1 = in.readLine();
guessNum = Integer.parseInt(input1);
if (guessNum == num) {
System.out.println( " Congratulations !");
ans = false;
rand = true;
} else {
System.out.println( " Try again");
}
}
if(ans = true) {
end = true;
}
}
}
}
}

Well, let's decompose your for loop:
for (int i = 0; i > 3; i++)
Start with i = 0
Perform the body while i > 3 .... whops, do you see the problem?

for (int i = 0; i > 3; i++) {
The guard condition is never true - 0 > 3 is false immediately, so the loop never runs.
Use i < 3 as the guard instead.

You have i>3 and i=0... 0 is not greater than 3. So, this is wrong! Change to this:
for (int i = 0; i < 3; i++) {
System.out.println( " Guess a number from 0 to 10 :");
String input1 = in.readLine();
guessNum = Integer.parseInt(input1);
if (guessNum == num) {
System.out.println( " Congratulations !");
ans = false;
rand = true;
} else {
System.out.println( " Try again");
}
}

Check that if(ans = true) { is an assigment and not a check condition
if you want to check the value of ans do
if(ans == true) {
OR EVEN BETTER
if(ans) {
the other reason why is not working is because this:
for (int i = 0; i > 3; i++) {
the condition is never met
do instead
for (int i = 0; i < 3; i++) {

Flip your comparison operator:
for (int i = 0; i < 3; i++) {

Related

Implementing While loop so my code repeats itself properly

In my code:
public static String input() {
Scanner input = new Scanner(System.in);
while(true) {
int qcount = 0;
String key = input.nextLine();
char[] keyCharArray = key.toCharArray();
for (int i = 0; i<keyCharArray.length;i++) {
//Here the while loop is supposed to break
if(keyCharArray[i]=='q') {
qcount++;
break;
}
}
int[] radie = new int[(keyCharArray.length)/2];
int[] höjd = new int[(keyCharArray.length)/2];
int counter = 0;
for(int i = 0; i < keyCharArray.length; i++){
if(i % 2 == 0){
radie[i/2] = keyCharArray[i] - '0';
}
else if(i % 2 != 0){
höjd[i/2] = keyCharArray[i] - '0';
}
}
for(int i = 0; i < (keyCharArray.length)/2; i++) {
System.out.print("r = " + radie[i] + " " + "h = " + höjd[i] + "\n\r" + "Basytans area: " + area(radie[i], höjd[i]) + "\n\r" + "Mantelytans area:" + area(radie[i]) + "\n\r" + "Volym: " + volume(radie[i], höjd[i]) + "\n\r");
}
return key;
}
}
The While loop is supposed to repeat the content until keyCharArray[i] =='q' -> There after the while loop is supposed to break
How can I make this work? Thanks
I have tried everything, yet I can't seem to solve it.
Appreciate any efforts, Thanks alot
Tried everything, doesn't work
sadasd
dsadsa
sdadsa
asdsda
You current code is (partially) like this:
public static String input(){
Scanner input = new Scanner(System.in);
while(true){
int qcount = 0;
String key = input.nextLine();
char[] keyCharArray = key.toCharArray();
for (int i = 0; i<keyCharArray.length;i++) {
if(keyCharArray[i]=='q') {
qcount++;
break;
}
}
// The rest...
}
}
The problem with this is that the break only breaks the inner for loop.
The simplest solution is to use the qcount variable you already have, and after the for loop check if it's non-zero to break out of the while loop:
for (int i = 0; i<keyCharArray.length;i++) {
if(keyCharArray[i]=='q') {
qcount++;
break;
}
}
if (qcount > 0) {
break; // Breaks out of the while loop
}
As for my suggestion in the comment it would be something like this instead:
private boolean shouldBreak(String key) {
char[] keyCharArray = key.toCharArray();
for (int i = 0; i<keyCharArray.length;i++) {
if(keyCharArray[i]=='q') {
return true; // Return that we should break the while loop
}
}
return false; // Do not break the while loop
}
public static String input(){
Scanner input = new Scanner(System.in);
while(true){
String key = input.nextLine();
if (shouldBreak(key)) {
break; // Breaks out of the while loop
}
// The rest...
}
}
I personally recommend something like this, as it makes the code cleaner and easier to read and understand and maintain.

Which test case causes the Runtime Error?

This was one of coding jam 2020 questions with the link attached below (round is complete), and while I could not reproduce it, the google engine reported that this was a runtime error even for the small test case. It could pretty much handle any test case I threw at it. Perhaps I am missing an edge case, but not sure what it is.
My understanding is that this is O(N) performance. All it really does is to check if the boolean sub array is free(false) and if so, assign the task to that sub array(true) with may be 2N compares.
https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd27/000000000020bdf9
import java.util.*;
import java.io.*;
//Parenting Partnering Returns
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int t = in.nextInt(); // Scanner has functions to read ints, longs, strings, chars, etc.
for (int ijk = 1; ijk <= t; ++ijk) {
int N = in.nextInt();
String ans;
StringBuilder sb = new StringBuilder();
boolean[] cal = new boolean[1442];
boolean[] jal = new boolean[1442];
int si, se;
boolean canC,canJ, isPossible = true;
for (int i = 0 ; i < N ; i++) {
si = in.nextInt();
se = in.nextInt();
canC = false; canJ = false;
if (cal[si + 1] == false && cal[se] == false || cal[si] == false && cal[se -1] == false) {
for (int j = si ; j <= se; j++) cal[j] = true;
sb.append('C'); canC = true; continue;
} else if (jal[si + 1] == false && jal[se] == false || jal[si] == false && jal[se -1] == false) {
for (int k = si ; k <= se; k++) jal[k] = true;
sb.append('J'); canJ = true; continue;
} else {
isPossible = false;
break;
}
}
ans = sb.toString();
if(isPossible)
System.out.println("Case #" + ijk + ": " + ans);
else System.out.println("Case #" + ijk + ": " + "IMPOSSIBLE");
}
//in.close();
}
}

Java. Multiple while conditions and boolean

I am trying to do a school project and I'm having problems; my code is:
public class Class {
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
int code = 0, i = 0;
boolean error = true;
//Start of program
System.out.println("Inputs ------------------");
//Ask for input
do {
System.out.print("Code: ");
code = lector.nextInt();
if ( code < 0 || code > 2000) {
error = false;
} i = i + 1;
} while (!error || i < 3);
if (error) {...rest of the program
My problem is that I need to exit the loop if the input is > 0 & < 2000, and I need to stop executing the program if the user exceed 3 intents.
Any help would be very apreciated! Thank you!
This
while (!error || i < 3);
should be
while (!error && i < 3);
You want to continue looping while error is false and i < 3. Also i = i + 1; can be written as i++ (or with a preincrement). So you could do
boolean valid = false;
do {
System.out.print("Code: ");
code = lector.nextInt();
if (code > 0 && code < 2000) {
valid = true;
}
i++;
} while (!valid && i < 3);

Currently compiling, but receiving nothing but end to program?

import java.util.Scanner;
public class PD {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter your number: " );
int number = input.nextInt();
for (int count = 2; count < number; count++) {
String blank = "";
String Snumber = count + blank;
if (isPalindromic(count) && isPrime(count) &&
isPalindromic((int)(Snumber.length())) &&
isPrime((int)(Snumber.length()))){
System.out.println( count + "is double palidromic prime");
}
else
continue;
}
}
// method to find palindromic
public static boolean isPalindromic(int count) {
String blank = "";
String convert = count + blank;
for (int i = 0, q = 1; i <= (convert.length()/2 - 1); i++, q++) {
if (convert.substring(i,q) == convert.substring(convert.length() - q, convert.length() - i)){
return true;
}
}
return false;
}
// method to find prime
public static boolean isPrime(int count ) {
for (int divisor = 2; divisor <= count/2; divisor++) {
if (count % divisor == 0) {
return false;
}
}
return true;
}
}
Currently the thing compiles and ask for input, but it always results in nothing.
Does someone see something wrong with my program that is obvious wrong.
Overall, the program receives input and has to look through values 2 until it hits the value the user wants and print the ones that follow the if statement.
Your isPalindromic method is not functioning properly. It is not returning true for palindromic numbers. Change it to this:
public static boolean isPalindromic(int count) {
String blank = "";
String convert = count + blank;
int n = convert.length();
for (int i = 0; i < (n / 2 + 1); i++) {
if (convert.charAt(i) != convert.charAt(n - i - 1)) {
return false;
}
}
return true;
}

changing 'invisible' chaaracters to letters, game of hangman

so in my program im trying to incorporate a couple of different classse into my main program which i am coming up with the code.
What i am given
Dictionary() {
dictionary = new String[NUMBER_OF_WORDS];
Scanner inputStream = null;
try {
inputStream = new Scanner(new File(FILE_NAME));
}catch (FileNotFoundException e) {
System.out.println("Dictionary class cannot find file \"dictionaryData.txt\".");
System.out.println("Please make sure that the file is in the project folder.");
System.exit(0);
}
for (int i = 0; i < NUMBER_OF_WORDS; i++) {
dictionary[i] = inputStream.next();
}
}
public String getRandomWord(){
Random generator = new Random();
String temp = new String();
temp += dictionary[generator.nextInt(NUMBER_OF_WORDS)];
return temp;
}
public boolean find(String word) {
int count = 0;
int lowerIndex = 0;
int upperIndex = NUMBER_OF_WORDS - 1;
int middleIndex;
while(lowerIndex <= upperIndex){
middleIndex = (lowerIndex + upperIndex) / 2;
count++;
if(word.equalsIgnoreCase(dictionary[middleIndex])) { // found it
return true;
}
else if (word.compareToIgnoreCase(dictionary[middleIndex]) < 0) { // word smaller than middle
upperIndex = middleIndex - 1;
}
else { // word is larger than middle
lowerIndex = middleIndex + 1;
}
}
return false;
}
}
along with another class WordHider
WordHider() {
secretWord = new String();
wordMask = new String();
}
public String getWordMask() {
return wordMask;
}
public String getSecretWord() {
return secretWord;
}
public void setSecretWord(String newSecretWord) {
secretWord = newSecretWord.toLowerCase();
if (secretWord.length() > 0) {
wordMask = HIDE_CHAR;
for (int i = 1; i < secretWord.length(); i++) {
wordMask += HIDE_CHAR;
}
}
}
public boolean isHiddenWordFound() {
for (int i = 0; i < wordMask.length(); i++) {
if(wordMask.charAt(i) == HIDE_CHAR.charAt(0)) {
return false;
}
}
return true;
}
public int revealLetter(String letter) {
int count = 0;
String newFoundWord = "";
if (letter.length() == 1) {
for (int i = 0; i < secretWord.length(); i++) {
if ((secretWord.charAt(i) == letter.charAt(0))
&& (wordMask.charAt(i) == HIDE_CHAR.charAt(0))) {
count++;
newFoundWord += letter;
}
else {
newFoundWord += wordMask.charAt(i);
}
}
}
wordMask = newFoundWord;
return count;
}
}
and using those classes i have to come up with code that looks like this:
Word: ********** Guesses Left: 5
Enter your guess: a
Miss!
Word: ********** Guesses Left: 4
Enter your guess: e
Miss!
Word: ********** Guesses Left: 3
Enter your guess: i
Word: i**i*i**** Guesses Left: 3
Enter your guess: o
Word: i**i*i*o** Guesses Left: 3
And ive got a couple of questions about this,
1) i have a dictionaryData.text that i was given and have to implement
that into my code. it contains a list of 81thousand words and im not
sure how to have my program recognize its there. Dictionary class
cannot find file "dictionaryData.txt". Please make sure that the file
is in the project folder. ^ i get that error when i try and print a
random word
2) How do i get my program to change the letters of a word to
stars(Hide the word)
3) put it all in a loop?
Parts of the Dictionary class and the WordHider class are missing. Nevertheless, I'll try and answer your questions.
1) Like I said, you're missing part of the Dictionary class. You incorporate the class like this:
Dictionary dictionary = new Dictionary();
String word = dictionary.getRandomWord();
2) Like this:
wordHider.setSecretWord(word);
3) I'm not sure what "it" is, but yes, your user has to guess a letter. Then you have to check to see if the letter is in the word. Like this:
wordHider.revealLetter(letter);
Then you have to display the word and let the user guess another letter. This guess / check / display has to be in a loop.

Categories