Trouble getting my while loop to work - java

I'm currently working on this assignment for a class and I'm having a hard time getting my while loop to work. Can anyone assist me on figuring out why I can't get the user to enter y or n to either restart the loop or terminate it? Thank you so much!
import java.util.Scanner;
import java.text.NumberFormat;
public class EvenQuizzes {
public static void main (String[] args) {
String another="y";
double percent;
int answers;
int score = 0;
Scanner scan = new Scanner(System.in);
NumberFormat fmt = NumberFormat.getPercentInstance();
// Asks the user to input the amount of questions on the quiz
System.out.print("How many questions are on the quiz? ");
final int QUESTIONS = scan.nextInt();
System.out.println(); // spacer
int[] key = new int [QUESTIONS];
// Asks the user to enter the key
for (int i=0; i<key.length; i++){
System.out.print("Enter the correct answer for question "+ (i+1) +": ");
key[i] = scan.nextInt();
}
System.out.println(); // spacer
while (another.equalsIgnoreCase("y")) {
// Asks the user to enter their answers
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
// Grades the amount of questions right and gives the percentage
percent = (double)score/QUESTIONS;
System.out.println();
System.out.println("Your number of correct answers is: " + score);
System.out.println("Your quiz percentage: " + fmt.format(percent));
System.out.println();
System.out.println("Grade another quiz? (y/n)");
another = scan.nextLine();
}
}
}

So instead of this
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
you should try this
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
scan.nextLine();

At the end of your while loop, try adding this print statement:
System.out.println("Next line is >>>" + another + "<<<");
That should make it clear what you are getting from the scan.nextLine() call. It won't fix your problem, but it will make the issue obvious.

It has to do with that your scan is reading integers before getting the y/n from the user.
In this transition, the scan is reading a newline character instead of y. As a result, the another is a newline char and hence fails the while-loop condition.
To overcome this, the shortcut method is what #3kings had mentioned.
Another method is scan all inputs as string (nextLine) and then for the quiz part, parse for integer. It may seems a lot of work but you get to use parseInt and try/catch exception.

Related

FOR Loop array in JAVA, not working

Can someone point out what is wrong with my program?
I have done most of it but I can't seem to find what's wrong with it.
It doesn't ask the user for the "enter your grade" prompt for each course.
This is for an array assignment for school. Here is my code.
I am having difficulties figuring out what is wrong with the for loop I made specifically the for loop.
This program is supposed to ask the user for their courses and then the user enters their grades for that course.
If possible, please provide me hints on what I am doing wrong.
import java.io.*;
public class StudentMarks {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
//Declare BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int x=0, y=0;
double grade=0.0;
String course;
//ask user how many courses they completed
System.out.println("How many courses have you completed?");
//obtain answer
int completed=Integer.parseInt(br.readLine());
//declare array for course
String courses[]=new String[completed];
//ask user to enter the course names use a FOR loop for this
for(int i=0;i<courses.length;i++)
{
i++;
System.out.println("Please enter course name " + i);
course = br.readLine();
for(int j=i--;j<i;j++)
{
j++;
System.out.println("What is the grade you got for " + course+ " " + j);
//get their answer
grade = Double.parseDouble(br.readLine());
}
}//end for loop
//display to the user the high achievement award qualifiers:
System.out.println("High-Ahcievement Award Qualifiers: \n");
if(grade>93)
{
//output
}
else if(grade<70)
{
System.out.println("Needs Improvement:");
//output
}
}
}
Instead of i++ use
System.out.println("Please enter course name " + (i+1));
you do not need any nested loop
for(int j=i--;j<i;j++)
{
j++;
System.out.println("What is the grade you got for " + course+ " " + j);
//get their answer
grade = Double.parseDouble(br.readLine());
}
instead use
System.out.println("What is the grade you got for " + course);
//get their answer
grade = Double.parseDouble(br.readLine());
HERE is the Full code if you still having trouble understanding it let me know .
import java.io.*;
public class sort {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
//Declare BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int x=0, y=0;
double grade=0.0;
String course;
//ask user how many courses they completed
System.out.println("How many courses have you completed?");
//obtain answer
int completed=Integer.parseInt(br.readLine());
//declare array for course
String courses[]=new String[completed];
//ask user to enter the course names use a FOR loop for this
for(int i=0;i<courses.length;i++)
{
System.out.println("Please enter course name " + (i+1));
course = br.readLine();
System.out.println("What is the grade you got for " + course);
//get their answer
grade = Double.parseDouble(br.readLine());
//end for loop
//display to the user the high achievement award qualifiers:
System.out.println("High-Ahcievement Award Qualifiers: \n");
if(grade>93)
{
//output
}
else if(grade<70)
{
System.out.println("Needs Improvement:");
//output
}
}
}
}
I think you didnt intend to have the i++ / j++ in your for loops (first statement).
The third “parameter” of the loop head actually tells the program what to do, when it reaches the end of the loop. Therefore you increment twice each time.
Your inner loop (with int j = i--) has a condition that is always false, and so it's body is never executed.
The line of code:
j = i--
isn't as simple as it seems and can be broken down into two lines:
j = i;
i = i - 1;
Note that j is set to the value of i, and only after that does i get decremented. So if j is set to i, and then i becomes i - 1, i will be one less than j. So the condition of the for loop i.e. j < i, will always be false, and so the body of the loop will never be executed.
Example:
i = 5;
j = i--;
this boils down to
i = 5;
j = i; //j is 5
i = i - 1; //i is 4
j < i; //5 < 4 is false, inner for loop not executed
Hope this helps!

Listing multiples of user-inputted numbers

The task is to "Write a program that displays a user-indicated number of multiples for an integer entered by the user."
I suppose I do not need a completely direct answer (although I do want to know the methods/formula to use), as I want to use this as a learning experience in order to do and learn from the task myself. I really want to know about the process and which methods to use, along with finding a formula. :||
I'm really not sure how to write a code that displays a user-inputted number of a user-inputted integer. The hardest part seems to be writing the loop formula. Not sure where to start.
So far, I have:
import java.util.Scanner;
public class MultipleLooping
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
\\just stuff to base my code off of
int integer;
int numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
\\pretty much everything from here on out.. I'm not sure what to really do.
int n = integer;
int result = (integer * (numberMultiples));
while (result > 0){}
System.out.print(result);
}
} \\at the moment this code doesn't seem to have any running errors
I'm really not sure how to write a code that displays a user-inputted number of a user-inputted integer. The hardest part seems to be writing the loop formula. Not sure where to start.
NEW QUESTION
I need to loop my program as well. (By asking a question to the user first.) Mines isn't working, as it just keeps looping only the integer loop and doesn't let me type yes/no.
import java.util.Scanner;
public class MultipleLoops
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int integer, numberMultiples;
String repeat = "yes";
while (repeat != "no")
{
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
for (int i=1; i<=numberMultiples; i++){
System.out.println(integer + " * " + i + " = " + i*integer );
}
System.out.println("Would you like to do this again? Enter yes or no: ");
repeat = keyboard.nextLine();
}
}
}
Ok so you need to understand the problem first to know how to solve it
x = First input
n = Second input
you need to calculate n multiple of x
example with x = 3 and n = 10
To calculate 10 multiple of 3 we need to do :
1st multiple = x*1
2nd multiple = x*2
3rd multiple = x*3
...
n multiple = x*n
you can notice that these operations can be replaced by one for loop (notice first and last character of every line, it can be index of your loop )
Back to java :)
for (int i=1; i<=numberMultiples; i++){
System.out.println("Listing multiple N# " + i + " = "+ i*integer );
}
Replace your code with the following and try this code :
import java.util.Scanner;
public class MultipleLooping{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int integer,numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
for (int i=1; i<=numberMultiples; i++){
System.out.println("Listing multiple N# " + i + " = "+ i*integer );
}
}
}
Enter an integer:
3
How many multiples of 3 would you like to know?
7
Listing multiple N# 1 = 3
Listing multiple N# 2 = 6
Listing multiple N# 3 = 9
Listing multiple N# 4 = 12
Listing multiple N# 5 = 15
Listing multiple N# 6 = 18
Listing multiple N# 7 = 21
Do you want like this ? Below is the code
package com.ge.cbm;
import java.util.Scanner;
public class MultipleLooping
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//just stuff to base my code off of
int integer;
int firstEntered;
int numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
firstEntered = integer;
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
//pretty much everything from here on out.. I'm not sure what to really do.
for (int i=0;i<numberMultiples;i++){
integer=integer*firstEntered;
System.out.println(integer);
}
}
}
Output:
Enter an integer:
3
How many multiples of 3 would you like to know?
7
Listing the first 7 multiples of 3:
9
27
81
243
729
2187
6561
this should work
while(repeat.equals("yes"))
{
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
for (int i=1; i<=numberMultiples; i++)
{
System.out.println(integer + " * " + i + " = " + i*integer );
}
System.out.println("Would you like to do this again? Enter yes or no: ");
repeat = keyboard.nextLine();
repeat = keyboard.nextLine();
}

How can I make this java code go back to a certain point in the code?

So as you could probably tell, it is a calculator. This is the second program I have made in Java, besides robotics code. I am pretty new to Java, so I don't know a ton about it. I want to be able to go back to the menu (lines 19-27) after it gives the answer to the question. If I can do this, I will put something like M for menu or E to exit after the answer. I want it so if they put M, it will go back to those lines of code to be able to start over again instead of restarting the program. Thanks, Matt.
public class Calculator {
public static void main(String[] args) {
System.out.println("Calculator");
System.out.println("----------");
System.out.println("Press 1 for addition");
System.out.println("Press 2 for subtraction");
System.out.println("Press 3 for multiplication");
System.out.println("Press 4 for division");
int Menu;
Scanner menu_scanner = new Scanner(System.in);
Menu = menu_scanner.nextInt();
if (Menu == 1){
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Please enter the first number in the problem");
System.out.println("--------------------------------------------");
double iAddition1;
double iAddition2;
double aAddition;
Scanner sAddition1 = new Scanner(System.in);
iAddition1 = sAddition1.nextDouble();
System.out.println("Please enter the second number in the problem");
System.out.println("---------------------------------------------");
Scanner sAddition2 = new Scanner(System.in);
iAddition2 = sAddition2.nextDouble();
aAddition = iAddition1 + iAddition2;
System.out.println("The answer to " + iAddition1 + " + " + iAddition2 + " = " + aAddition);
}
if (Menu == 2){
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Please enter the first number in the problem");
System.out.println("--------------------------------------------");
double iSubtraction1;
Scanner sSubtraction1 = new Scanner(System.in);
iSubtraction1 = sSubtraction1.nextDouble();
System.out.println("Please enter the second number in the problem");
System.out.println("---------------------------------------------");
double iSubtraction2;
Scanner sSubtraction2 = new Scanner(System.in);
iSubtraction2 = sSubtraction2.nextDouble();
double aSubtraction = iSubtraction1 - iSubtraction2;
System.out.println("The answer to " + iSubtraction1 + " - " + iSubtraction2 + " = " + aSubtraction);
}
if (Menu == 3){
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Please enter the first number in the problem");
System.out.println("--------------------------------------------");
double iMultiplication1;
double iMultiplication2;
Scanner sMultiplication1 = new Scanner(System.in);
iMultiplication1 = sMultiplication1.nextDouble();
System.out.println("Please enter the second number in the problem");
System.out.println("---------------------------------------------");
Scanner sMultiplication2 = new Scanner(System.in);
iMultiplication2 = sMultiplication2.nextDouble();
double aMultiplication = iMultiplication1 * iMultiplication2;
System.out.println("The answer to " + iMultiplication1 + " * " + iMultiplication2 + " = " + aMultiplication);
}
if (Menu == 4){
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Please enter the first number in the problem");
System.out.println("--------------------------------------------");
Scanner sDivision1 = new Scanner(System.in);
double iDivision1;
iDivision1 = sDivision1.nextDouble();
System.out.println("Please enter the second number in the problem");
System.out.println("---------------------------------------------");
Scanner sDivision2 = new Scanner(System.in);
double iDivision2;
iDivision2 = sDivision1.nextDouble();
double aDivision = iDivision1 / iDivision2;
System.out.println("The answer to " + iDivision1 + " / " + iDivision2 + " = " + aDivision);
}
}
}
You are looking for a loop. Probably a while loop.
A while loop with a condition of your choice (such as checking a certain value isn't encountered), or a for loop with a certain number of iterations if you're content with doing the set of operations, say, 10 times for example.
One solution is to wrap the entire block of code after Menu = menu_scanner.nextInt in a while loop such as while(Menu < 5), and offer another option of 5 to exit the program.
Essentially though, you need to learn about the control structures in Java from a guide e.g. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html
First off all try to group parts of your program into functions. You can do a loops with a while or for loop. You can do this also with labels.
Make sure you reduce the amount of code you have by using method. I also think you should use cases for e.g
public static double doMath(double firstNum,double secondNum){
Scanner scan = new Scanner();
System.out.println("Enter the operation number?");
int i = scan.nextInt();
switch (i) {
case 1: total = firstnum + secondNum;
break;
case 2: total = firstnum - secondNum;
break;
......
}
return total;
}
This method take two numbers (doMath(first, second)) and return the total/answer.
It's a very good start but every time you see yourself repeating lines of code take advantage of methods/functions they are very important in programming. Also use while loops to repeat the call until the user wants to end the program.
Wish you the best of luck
I am also new to Java programing, but i agree a "While Loop" is what you need.
My Version of your Code:
http://pastebin.com/H34FRWP3
Good Luck :)
I use Eclipse IDE, it has helped me ALOT.
http://eclipse.org

Need help declaring a variable within a for loop (Java)

I'm currently working on a program and ran into an error while trying to execute a for loop. I want to declare a variable in the for loop, then break once that variable obtains a certain value, but it returns the error "cannot be resolved to a variable."
Here's my code
int i = -1;
for (; i == -1; i = index)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
int index = (input.indexOf('y'));
}
I want to run the output segement of my program until the user inputs yes, then the loop breaks.
The variable index's scope is local to the block of the for loop, but not the for loop itself, so you can't say i = index in your for loop.
You don't need index anyway. Do this:
for (; i == -1;)
or even
while (i == -1)
and at the end...
i = (input.indexOf('y'));
}
Incidentally, I'm not sure you want input.indexOf('y'); an input of "blatherskyte" will trigger this logic, not just "yes", because there's a y in the input.
Instead of using a for loop, you can do-while(it suits much better for this scenario.
boolean exitLoop= true;
do
{
//your code here
exitLoop= input.equalsIgnoreCase("y");
} while(exitLoop);
for indefinite loop, i would prefer while.
boolean isYes = false;
while (!isYes){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
isYes = input.equalsIgnoreCase("yes");
}
You cannot do this. If the variable is declared inside of the loop, then it is re-created every run. In order to be part of the condition for exiting the loop, it must be declared outside of it.
Alternatively, you could use the break keyworkd to end the loop:
// Should we exit?
if(input.indexOf('y') != -1)
break;
Here you want to use a while loop. Usually you can decide which loop to use by saying your logic out loud to yourself, While this variable is(not) (value) do this.
For your problem, initialize the variable outside of the loop, and then set the value inside.
String userInput = null;
while(!userInput.equals("exit"){
System.out.println("Type exit to quit");
userInput = scan.nextLine();
}

Identifying if the user presses <enter>

I have been working on this for several days and I'm super frustrated. This is my first course in Java so please bear with me on lack of knowledge still. I'm supposed to write a program that contains an array of 10 grades entered by the user and I calculate the average. In particular I'm having problems with what is down below.
You should not read doubles numbers from the user, you should read a string. Here is the process:
Read a string from the user
trim the string and get the length
if the length <1 then the user hit and you get out
if the length is >0 then you convert the string into a double using
d =Double.parseDouble(S);
So far I just have this. I have been adding and deleting a lot of coding to this for the past week. And I still cant seem to get it to work. Any help would be much appreciated!
import java.util.*;
import java.io.*;
public class Arrays {
public static void main(String[] args) {
double d = 0;
final int SIZE = 10;
Scanner reader = new Scanner(System.in);
String[ ] grades = new String[SIZE];
System.out.println("Please enter up to 10 grades.");
for (int i = 0; i < grades.length; i++){
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine( );
}
System.out.println("\nNumber of valid grades entered: " + grades.length);
}
}
Try this
for (int i = 0; i < grades.length; ){
System.out.print("Grade " + (i + 1) + ": ");
String str = reader.nextLine();
if(str.trim().length() > 0){
try{
grades[i] = Double.parseDouble(str);
i++;
}catch(NumberFormatException e){
e.printStackTrace();
}
}
}
System.out.println("\nNumber of valid grades entered: " + i);
IMHO i think grades should be an array of double ie
double[] grades=new double[SIZE];
You can try it in following way
int correctGrades=0;
double[] grades=new double[SIZE]; //Create array of double instead of String
for (int i = 0; i < SIZE; i++){
System.out.print("Grade " + (i + 1) + ": ");
String str=reader.nextLine();
if(str.length() > 0){ // If length is greater than 0 then its correct grade
grades[i]=Double.parseDouble(str);
correctGrades++;
}
}
System.out.println("\nNumber of valid grades entered: " + correctGrades);
As per my understanding this should be your for loop
for (int i = 0; true; i++) {
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine();
if (grades[i].equals("")) {
break;
}
//check for number format exception if user enters invalid input
try {
d = Double.parseDouble(grades[i]);
}
catch (NumberFormatException exception) {
exception.printStackTrace();
}
}
System.out.println("The value of double entered is : " + d);
}
Here you run the loop for infinite number of times but with every loop you check the user input.
Now if the user enters an empty string you exit the loop using the break statement

Categories