Java. Multiple while conditions and boolean - java

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);

Related

Palindrome program works fine for a single test case but keeps taking input otherwise

public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int test_cases = Integer.parseInt(br.readLine());
if (test_cases >= 1 && test_cases <= 20) {
String[] ans = new String[test_cases];
for (int i = 0; i < test_cases; i++) {
char[] n = br.readLine().toCharArray();
int k = 0;
int j = n.length - 1;
while (k <= j) {
if (n[k] == n[j]) {
k++;
j--;
ans[i] = "wins";
}
else
ans[i] = "loses";
}
}
for (String s : ans)
System.out.println(s);
}
}
catch (Exception x) {
}
}
PROBLEM STATEMENT: The first line of the input contains an integer T, the number of testcases. This is followed by T lines containing an integer N. For each input output "wins" if the number is a palindrome and "loses" if not, in a new line.
For test_cases=1, the program works fine but for test_cases>1 the program keeps taking input. I have solved the palindrome problem but I still can't understand what is wrong with this code. Can anybody explain to me why does it keeps taking input?
For non palindrome, your code runs in infinite loop. Just add break for that.
while (k <= j) {
if (n[k] == n[j]) {
k++;
j--;
ans[i] = "wins";
}
else {
ans[i] = "loses";
break;
}
}
This can be one of the solution.
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int test_cases = Integer.parseInt(br.readLine());
if (test_cases >= 1 && test_cases <= 20) {
for (int i = 0; i < test_cases; i++) {
char[] n = br.readLine().toCharArray();
int k = 0;
int j = n.length - 1;
boolean flag=false;
while (k <= j) {
if (n[k] == n[j]) {
k++;
j--;
flag=true;
}
else{
flag=false;
break;
}
}
if(flag) System.out.println("wins");
else System.out.println("loses");
}
}
}
catch (Exception x) {
}
}
For a string which is not a palindrome, your loop runs infinitely.
Also, you need not store the results in an array for all the test cases, you can print it every time for each test case. However, if you intend to store strings and display results later, you can use something like StringBuffer classes.

can someone help me clear these errors

I am trying to do a summation puzzle, the questions asks to use summation puzzles by enumerating and testing all possible configurations and then it says use it to solve the examples given. The examples given were
pot + pan = bib
dog+cat= pig
boy + girl = baby
I keep getting an error saying left hand side of assignment must be a variable
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
cannot convert from int to bool.
if (exists = 0)
Also in my code where I try to display the output it doesn't run.
import java.util.Scanner;
public class Recursion
{
// Example program
public static String stringOne = new String(new char[10]);
public static String stringTwo = new String(new char[10]);
public static String stringThree = new String(new char[11]);
public static String charSet = new String(new char[11]);
public static int numberOne;
public static int numberTwo;
public static int numberThree;
public static int maxCharCount;
public static int[] numberSet = new int[10];
public static void checkForEquality()
{
numberOne = numberTwo = numberThree = 0;
int loop;
int subloop;
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringOne.length(); loop++)
{
for (subloop = 0; subloop < stringTwo.length(); subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the numeber
numberTwo = (numberTwo * 10) + numberSet[subloop];
}
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
for (subloop = 0; subloop < maxCharCount; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
if (loop == 0 && numberSet[subloop] == 0)
return;
//generate the number
numberThree = (numberThree * 10) + numberSet[subloop];
}
}
}
if (numberOne + numberTwo == numberThree)
{
//display the output
System.out.print(" Summation Puzzle solved. ");
System.out.print("\n");
System.out.print(stringOne);
System.out.print("<==>");
System.out.print(numberOne);
System.out.print("\n");
System.out.print(stringTwo);
System.out.print("<==>");
System.out.print(numberTwo);
System.out.print("\n");
System.out.print(stringThree);
System.out.print("<==>");
System.out.print(numberThree);
System.out.print("\n");
//loop to show the result
for (loop = 0; loop < maxCharCount; loop++)
{
System.out.print(charSet.charAt(loop));
System.out.print("<==>");
System.out.print(numberSet[loop]);
System.out.print("\n");
}
System.exit(0);
}
}
public static void generateCombinations(int indexCounter, int[] availableSet)
{
int loop;
if (indexCounter != 0)
{
for (loop = 0; loop < 10; loop++)
{
numberSet[indexCounter] = loop;
if (availableSet[loop] == 1)
{
availableSet[loop] = 0;
generateCombinations(indexCounter + 1, availableSet);
availableSet[loop] = 1;
}
}
}
if (indexCounter == maxCharCount)
{
checkForEquality();
}
}
public static void createCharSet()
{
int loop;
int setIndex;
int exists;
int subloop;
setIndex = 0;
for (loop = 0; loop < stringOne.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringOne.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
}
}
for (loop = 0; loop < stringTwo.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringTwo.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringTwo.charAt(loop));
}
}
for (loop = 0; loop < stringThree.length(); loop++)
{
exists = 0;
for (subloop = 0; subloop < setIndex; subloop++)
{
if (stringThree.charAt(loop) == charSet.charAt(subloop))
{
exists = 1;
}
}
if (exists == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, stringThree.charAt(loop));
}
}
maxCharCount = setIndex;
}
public static void calculateSummation()
{
int loop;
if (maxCharCount > 10)
{
System.out.print("Please check the input again");
return;
}
else
{
int[] avaliableSet = new int[10];
for (loop = 0; loop < 10; loop++)
{
avaliableSet[loop] = 1;
}
generateCombinations(0, avaliableSet);
}
}
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Enter the first String :");
stringOne = scan.next();
System.out.print(" Enter the second String :");
stringTwo = scan.next();
System.out.print(" Enter the thirsd String :");
stringThree = scan.next();
createCharSet();
System.out.print(" The character set formed from the given string = ");
System.out.print(charSet);
calculateSummation();
checkForEquality();
}
}
A lot of your problems are stemming from the syntax errors in the code you've written. For example:
line 74: if (stringThree.charAt(loop) == charSet.charAt(subloop) != null)
charSet.charAt(subloop) != null is an invalid comparison since the != operator cannot be used for booleans when comparing to null. If you're trying to determine if the characters return from .charAt(var) exist, use parentheses to make independent comparisons of each object.charAt(var) to null.
line 183: charSet = tangible.StringFunctions.changeCharacter(charSet, setIndex++, stringOne.charAt(loop));
tangible is ironically not tangible, as the variable does not exist locally or has not been defined globally.
charSet.charAt(setIndex++) = stringTwo.charAt(loop);
charSet.charAt(setIndex++) is a method that returns a character. This does not mean you can set the character at the specified index like it's a variable.
line 227: if (exists = 0)
You must use == when conducting comparisons in a conditional.
line 269: Scanner scan = new Scanner(System.in);
The Scanner class was not imported and thus cannot be used.
line 283: charSet.charAt(maxCharCount) = '\0';
Again, you can't use .charAt(var) to set the character at that index like it's a variable.
All of these problems can be self-determined by using a proper IDE, such as Eclipse.
Edit: Try to spend a little more time with pencil and paper working out the logic of your program before writing the code to represent your algorithm. This way you have focus and can write more comprehensive, commented, cleaner code. Here is a bit of a guide to help condense your existing project.

for loop ( Java) [closed]

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++) {

Comparing String inputs to desired length

I am running this program which taking inputs from command line for t(Desired Length),no of test
cases(N). But it is giving a run time error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index
out of range: -1
at java.lang.AbstractStringBuilder.insert(AbstractStringBuilder.java:979)
at java.lang.StringBuilder.insert(StringBuilder.java:300)
at Test.main(Test.java:28)
I am getting confused where i am accessing wrong index.
import java.io.BufferedReader;
import java.io.InputStreamReader;
class TestClass {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
String line = br.readLine();
int N = Integer.parseInt(line);
String[] profiles = null;
for (int i = 0; i < N; i++) {
profiles = br.readLine().trim().split(" ");
}
for (int i = 0; i < N; i++) {
if (Integer.parseInt(profiles[0]) > t && Integer.parseInt(profiles[1]) == t ||
Integer.parseInt(profiles[0]) > t || Integer.parseInt(profiles[1]) > t
|| Integer.parseInt(profiles[0]) == t && Integer.parseInt(profiles[1]) > t)
{
System.out.println("Crop");
}
if (Integer.parseInt(profiles[0]) < t && Integer.parseInt(profiles[1]) < t) {
System.out.println("Upload next");
}
if (Integer.parseInt(profiles[0]) == t && Integer.parseInt(profiles[1]) == t) {
System.out.println("Accepted");
}
}
System.out.println("Hello World!");
}
}
Your coding is unsafe, as you use the indexes [0] and [1] on profiles without checking that this array has any elements. Further you loop around overwriting the contents of profiles in a loop. What happens when there is no text to read from br?
You should always check the values before access (as in defensive programming).
Perhaps some Rubber Duck debugging is needed here.
I don't understand the checks you want to do, but if you want to check if each string is longer, shorter or equals to t, you should use this code:
public class Main
{
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[]) throws IOException {
int t = Integer.parseInt(br.readLine());
int N = Integer.parseInt(br.readLine());
/* MUST INITIALISE BEFORE FILLING IT! */
String [] profiles = new String[N];
for (int i = 0; i < N; i++) {
profiles[i] = br.readLine().trim();
if (profiles[i].length() < t)
System.out.println("shorter than t");// do something
else if (profiles[i].length() == t)
System.out.println("equals to t");// do something
else
System.out.println("longer than t");// do something
}
}
}
You are using a buffer reader to read some lines, with System.in . And before closing this buffer you try to make use of System.out . Could it be the reason for your trouble ? I think that asking the System to write and read at the same time is definitely not a good idea. Can you try to put a br.close() before the second loop ?
Here Lies the Demon in your Code :
// Let t=3 and N=5
String [] profiles=null; // Let the Input Here Be 12, 23, 34, 45, 56
for (int i = 0; i < N; i++) {
profiles=br.readLine().trim().split(" ");
}
System.out.println(Arrays.toString(profiles)); // [56] Only ? because you are initializing the same rer again and again
So when execution Goes Here :
for (int i = 0; i < N; i++) {
if (Integer.parseInt(profiles[0]) > t &&
Integer.parseInt(profiles[1]) == t || ... // Throws Index out of bounds exception
EDIT 1 : Here is the full Working Code :
package com.stackoverflow;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class TestClass {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
System.out.println(t);
String line = br.readLine();
int N = Integer.parseInt(line);
System.out.println(N);
String[] profiles = new String[N];
for (int i = 0; i < N; i++) {
profiles[i] = br.readLine().trim();
}
for (int i = 0; i < N; i++) {
System.out.println(Integer.parseInt(profiles[0]) > t && Integer.parseInt(profiles[1]) == t);
System.out.println(Integer.parseInt(profiles[0]) > t || Integer.parseInt(profiles[1]) > t);
System.out.println(Integer.parseInt(profiles[0]) == t && Integer.parseInt(profiles[1]) > t);
if (Integer.parseInt(profiles[0]) > t && Integer.parseInt(profiles[1]) == t ||
Integer.parseInt(profiles[0]) > t || Integer.parseInt(profiles[1]) > t
|| Integer.parseInt(profiles[0]) == t && Integer.parseInt(profiles[1]) > t)
{
System.out.println("Crop");
}
System.out.println(Integer.parseInt(profiles[0]) < t && Integer.parseInt(profiles[1]) < t);
if (Integer.parseInt(profiles[0]) < t && Integer.parseInt(profiles[1]) < t) {
System.out.println("Upload next");
}
System.out.println(Integer.parseInt(profiles[0]) == t && Integer.parseInt(profiles[1]) == t);
if (Integer.parseInt(profiles[0]) == t && Integer.parseInt(profiles[1]) == t) {
System.out.println("Accepted");
}
}
System.out.println("Hello World!");
}
}
EDIT 2 : Adding the Test Cases for the if conditions inside for loop :
Test Case1 Values : Let t=3, N=5 and the values for five(i.e N) test case be 12, 23, 34, 45, 56
Prints "crop" to the Console.
Test Case2 Values : Let t=30, N=5 and the values for five(i.e N) test case be 12, 23, 34, 45, 56
Prints "upload next" to the Console.
Test Case3 Values : Let t=10, N=5 and the values for five(i.e N) test case be 10, 20, 34, 45, 56
Prints "Accepted" to the Console.

Reading Data from Multiple txt Files in Java

I'm a beginner taking Intro to Computer Science and I'm working with java. I get the following error in this program when trying to read from multiple txt files in the getLetterGrade method:
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
import java.util.Scanner;
import java.io.*;
public class Exam
{
private int grade;
private float examAvg;
private String name;
private File exam1Data;
private File exam2Data;
private File namesData;
private Scanner inFileExam1;
private Scanner inFileExam2;
private Scanner inFileName;
//constructor
public Exam() throws IOException
{
exam1Data = new File("exam1.txt");
exam2Data = new File("exam2.txt");
namesData = new File("names.txt");
inFileExam1 = new Scanner(exam1Data);
inFileExam2 = new Scanner(exam2Data);
inFileName = new Scanner(namesData);
}
public float getExam1Avg()
{
examAvg = 0;
while (inFileExam1.hasNext()) {
grade = inFileExam1.nextInt();
examAvg += grade;
}
inFileExam1.close();
examAvg = (float)(examAvg / 25.0);
return examAvg;
}
public float getExam2Avg()
{
examAvg = 0;
while (inFileExam2.hasNext()) {
grade = inFileExam2.nextInt();
examAvg += grade;
}
inFileExam2.close();
examAvg = (float)(examAvg / 25.0);
return examAvg;
}
//method that finds the letter grade given a student name and
//the exam number
public char getLetterGrade(String inputName, int examNum)
{
char letter;
int count = 1;
//inputName = inputName.toLowerCase();
do {
if (inFileName.hasNext()){
name = inFileName.nextLine();
}
count++;
} while (inFileName.hasNext() && !name.equalsIgnoreCase(inputName));
inFileName.close();
if (!name.equalsIgnoreCase(inputName)) {
return 'x';
}
if (examNum == 1) {
for (int i = 1; i <= count && inFileExam1.hasNextInt(); i++) {
grade = inFileExam1.nextInt();
}
inFileExam1.close();
}
else if (examNum == 2) {
for (int i = 1; i <= count && inFileExam2.hasNextInt(); i++) {
grade = inFileExam2.nextInt();
}
inFileExam2.close();
}
else {
return 'x';
}
if (grade >= 90) {
letter = 'A';
}
else if (grade < 90 && grade >= 80) {
letter = 'B';
}
else if (grade < 80 && grade >= 70) {
letter = 'C';
}
else if (grade < 70 && grade >= 60) {
letter = 'D';
}
else {
letter = 'F';
}
return letter;
}
}
The error occurs at the following line:
for (int i = 1; i <= count && inFileExam1.hasNextInt(); i++) {
Please help!!
Here is the main class:
import java.util.Scanner;
import java.io.*;
public class ExamAverages
{
public static void main(String[] args) throws IOException
{
Exam exam = new Exam();
System.out.println(exam.getExam1Avg());
System.out.println(exam.getExam2Avg());
System.out.println(exam.getLetterGrade("name", 1));
}
First of all, you're resetting grade every time you read a line, and you aren't doing anything with it, so that part of the code is useless.
But to answer your question:
According to the API, Scanner only returns an IllegalStateException after the object is closed using Scanner.close() or is somehow closed by the system.
Try moving your Scanner declaration for inFileExam1 next to where you are using it, like this:
if (examNum == 1) {
inFileExam1 = new Scanner(exam1Data); // Add this
for (int i = 1; i <= count && inFileExam1.hasNextInt(); i++) {
grade = inFileExam1.nextInt();
}
inFileExam1.close();
}
else if (examNum == 2) {
inFileExam2 = new Scanner(exam2Data); // And this
for (int i = 1; i <= count && inFileExam2.hasNextInt(); i++) {
grade = inFileExam2.nextInt();
}
inFileExam2.close();
}
}
Your error is in getAverageExam1Avg and the other one. Instead of closing your Scanners in the getLetterGrade method, you should keep them open and add a close method like this:
public void close() {
inFileName.close();
inFileExam1.close();
inFileExam2.close();
}
Make sure to add the proper exceptions into that code.
The reason it is failing now is because you haven't opened the Scanners. Un-comment the instantiations in the constructor.
If this doesn't work, I have no idea what will.
you are closing your scanner
inFileName.close();
and then trying to use it again without opening as like:
inFileName = new Scanner(..);
EDIT1
It does not fail for me, but maybe i have missed some stuff (I still don't know how exactly you are willing to read these files, how they relate to each other)
public char getLetterGrade(String inputName, int examNum) {
char letter;
int count = 0;
do {
if (inFileName.hasNext()) {
name = inFileName.nextLine();
}
count++;
} while (inFileName.hasNext() && !name.equalsIgnoreCase(inputName));
if (!name.equalsIgnoreCase(inputName)) {
return 'x';
}
if (examNum == 1) {
for (int i = 1; i <= count && inFileExam1.hasNextInt(); i++) {
grade = inFileExam1.nextInt();
}
inFileExam1.close();
} else if (examNum == 2) {
for (int i = 1; i <= count && inFileExam2.hasNextInt(); i++) {
grade = inFileExam2.nextInt();
}
inFileExam2.close();
} else {
return 'x';
}
if (grade >= 90) {
letter = 'A';
} else if (grade < 90 && grade >= 80) {
letter = 'B';
} else if (grade < 80 && grade >= 70) {
letter = 'C';
} else if (grade < 70 && grade >= 60) {
letter = 'D';
} else {
letter = 'F';
}
return letter;
}
You don't include the code that has your main method, but I'm going to make an educated guess that you construct a new Exam object in it, and call getLetterGrade more than once. Since you open your Scanners in the constructor, and close them after reading, the second time you call getLetterGrade you will see an IllegalStateException.
If this psychic reading is inaccurate, can you please update your post with the contents of main(String[] args)?
EDIT: After your latest edit I see that you call the getExam1Avg method before calling getLetterGrade. Since getExam1Avg calls close on your Scanner you get an IllegalStateException when calling the other method. You need to either instantiate a new scanner for each method call or otherwise reset the scanners after each method is complete.

Categories