do-while loop is not constantly working - java

does anybody see wrong code here ?? i'd like to see do-while is working constantly as long as condition is not satisfied but it is certainly not. please tell me which part of code ruins my expected result?
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Item> cart = new ArrayList<Item>();
Item item;
String itemName;
double itemPrice;
int quantity;
String keepShopping;
double total = 0.0;
DecimalFormat m = new DecimalFormat("######,##");
do {
System.out.print ("Enter the name of the item: ");
itemName = scan.nextLine();
System.out.print ("Enter the unit price: ");
itemPrice = scan.nextDouble();
System.out.print ("Enter the quantity: ");
quantity = scan.nextInt();
item = new Item(itemName,itemPrice,quantity);
cart.add(item);
total +=itemPrice*quantity;
System.out.println ("Continue shopping (y/n)? ");
keepShopping = scan.nextLine();
} while (keepShopping.equals("y"));
for (int i = 0; i < cart.size(); i++) {
System.out.println(cart.get(i).toString());
System.out.println("Total price: " + m.format(total));
}
scan.close();
}

nextInt() does not consume any characters following the integer value, so the CR LF after it is still in the buffer and is read by the nextLine() call, meaning that keepShopping is always a blank string (or whatever was typed after the quantity value on the same line).
Your code is also calling nextDouble() and nextInt() without first calling the corresponding hasNextDouble() and hasNextInt() methods, so if you type something wrong, the program will crash and burn. Very common flaw in the use of Scanner.

Related

Storing object in array in Java

Here is a simple program. I am assigned to store the objects in an array. But as I am a beginner student so i dont know how to store objects in array. Could somebody please help me with this question?
import java.util.Scanner;
public class MainExample {
public static void main(String[] args) {
double length;
double width;
double price_per_sqyd;
double price_for_padding;
double price_for_installation;
String input;
double final_price;
boolean repeat = true;
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
System.out.println("\n" +"What is the length of the room?: ");
length = keyboard.nextInt();
System.out.println("What is the width of the room?: ");
width = keyboard.nextInt();
System.out.println("What is the price of the carpet per square yard?: ");
price_per_sqyd = keyboard.nextDouble();
System.out.println("What is the price for the padding?: ");
price_for_padding = keyboard.nextDouble();
System.out.println("What is the price of the installation?: ");
price_for_installation = keyboard.nextDouble();
keyboard.nextLine();
System.out.println( "\n" + "Type 'yes' or 'no' if this is correct: ");
input = keyboard.nextLine();
if ("yes".equals(input))
repeat = true;
else
repeat = false;
}
}
}
you would need to create a class to hold the attributes like so. Create a constructor to initialize these values.
public class Room{
double length;
double width;
double price_per_sqyd;
double price_for_padding;
double price_for_installation;
String input;
double final_price;
boolean repeat = true;
}
then in your main method/driver class create an array with the type of this class and store relevant objects.
Room arr=new Room[100];
int count=0;
while (repeat)
{
System.out.println("\n" +"What is the length of the room?: ");
length = keyboard.nextInt();
System.out.println("What is the width of the room?: ");
width = keyboard.nextInt();
System.out.println("What is the price of the carpet per square yard?: ");
price_per_sqyd = keyboard.nextDouble();
System.out.println("What is the price for the padding?: ");
price_for_padding = keyboard.nextDouble();
System.out.println("What is the price of the installation?: ");
price_for_installation = keyboard.nextDouble();
keyboard.nextLine();
System.out.println( "\n" + "Type 'yes' or 'no' if this is correct: ");
input = keyboard.nextLine();
arr[count]=new Room(length,width,price1,price2,price3,price4);//call to the constructor
if ("yes".equals(input))
repeat = true;
count++;
else
repeat = false;
}
}
Although not very elegant, a quick solution for this toy program would be to make a "Room" class with the various properties like "length", "width", "price_per_sqft" etc. Then you can set specific property of each room object and store the "room" objects in an array of "Room".
What are you trying to store in an array? The different final_price values?
Regardless, because you don't know how many times your loop will run, you probably need an ArrayList. You could create this by adding ArrayList <Double> prices = new ArrayList <Double> ();
Then, add a line at the end of your loop that stores the correct variable to the ArrayList. For example: prices.add(final_price);
If final_price is not what you are trying to store, then just replace it with the variable you do want to store.
Also, don't forget that if you do use an ArrayList, you will need the correct import statement at the top of your code: import java.util.ArrayList;

Do-while loop inside a method [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
Everything is working fine in this code sample that i did, but everytime it calls the do-while loop on the output screen, it skips the "First name" input, and goes straight to "How old are you?" input. why is that happening and how can i fix it? I want to be able to repeat the whole thing without skipping "First name" when i pick 'y' to perform the loop.
public class WeightGoalTest
{
public static void main(String[]args)
{
doWhile person = new doWhile();
person.userInput();
}
}
import java.util.*;
public class doWhile
{
Scanner keyboard = new Scanner(System.in);
private String inputFn = "";
private int inputAge = 0;
private int inputHeight = 0;
private double inputWeight = 0.0;
private int inputCalculation = 0;
private int inputGender = 0;
private char loop;
public void userInput()
{
do
{
System.out.println("First Name: ");
inputFn = keyboard.nextLine();
System.out.println("How old are you?");
inputAge = keyboard.nextInt();
System.out.println("Gender 1 - Male: ");
System.out.println(" 2 - Female: ");
inputGender = keyboard.nextInt();
System.out.println("What is your Height in inches? ");
inputHeight = keyboard.nextInt();
System.out.println("Current Weight in pounds: ");
inputWeight = keyboard.nextDouble();
System.out.println("\nDo you want to use the calculator again? (y/n)");
loop = keyboard.next().charAt(0);
}while(loop == 'y');
}
}
Please note:
String java.util.Scanner.next() - Returns:the next token
String java.util.Scanner.nextLine() - Returns:the line that was skipped
Change your code [do while initial lines] as below:
System.out.println("First Name: ");
inputFn = keyboard.next();
use keyboard.next() instead of .nextLine(). For further informations have a look in the Java API concerning the Scanner class. nextLine() will
Advance this scanner past the current line and return the input that was skipped."

How to end a while Loop via user input

package cst150zzhw4_worst;
import java.util.Scanner;
public class CST150zzHW4_worst {
public static void main(String[] args) {
//Initialize Variables
double length; // length of room
double width; // Width of room
double price_per_sqyd; // Total carpet needed price
double price_for_padding; // Price for padding
double price_for_installation; // Price for installation
String input; // User's input to stop or reset program
double final_price; // The actual final price
boolean repeat = true;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
//User Input
System.out.println("\n" +"What is the length of the room?: ");
length = keyboard.nextInt();
System.out.println("What is the width of the room?: ");
width = keyboard.nextInt();
System.out.println("What is the price of the carpet per square yard?: ");
price_per_sqyd = keyboard.nextDouble();
System.out.println("What is the price for the padding?: ");
price_for_padding = keyboard.nextDouble();
System.out.println("What is the price of the installation?: ");
price_for_installation = keyboard.nextDouble();
final_price = (price_for_padding + price_for_installation + price_per_sqyd)*((width*length)/9);
keyboard.nextLine(); //Skip the newline
System.out.println("The possible total price to install the carpet will be $" + final_price + "\n" + "Type 'yes' or 'no' if this is correct: ");
input = keyboard.nextLine();
}
}
}
How would I make it so when the user says yes the program stop and if the user says no then the program just repeats? I don't know why I'm having so much trouble. I've searched for well over 4 hours. I am only supposed to use a while loop, I think.
You have to assign repeat in your while-loop so it becomes false if the user says yes:
repeat = !input.equalsIgnoreCase("yes");
You just need to set repeat to true or false based on user input. So in the end, compare input with yes or no. Something like this would work for you :
if ("yes".equals(input))
repeat = true; // This would continue the loop
else
repeat = false; // This would break the infinite while loop
boolean repeat = true;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
-----------------------
-------------------------
System.out.println("Do you want to continue:");
repeat = keyboard.nextBoolean();
}
you also if you want your code to be more systematic , go and search about the interrupt , specially thread interrupt , these answers above is correct , find the more organic code and implement it
You can use a break statement to exit a while loop.
while (...) {
input = ...;
if (input.equals("Y")) {
break;
}
}

JAVA beginner help needed string input in a loop

im a beginner in Java, and i have a problem to do:
the problem prompts the user 5 times to enter, the Name of a stock then the Share Price then the number of shares owned and we should calculate the sum of all the stock values, i wrote it using only two prompts using a loop, but my issue is that, in the second prompt time the loop Skips the String input for the second Name of stock instead of promting...bellow is the code:
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sharePrice =0,stockPrice = 0, temp = 0 ;
int i = 0;
double sum=0;
String name;
while (i < 2) {
System.out.println("Enter the Name of the Stock ");
name = input.nextLine();
System.out.println("Enter the Share price ");
sharePrice = input.nextDouble();
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
stockPrice = sharePrice * (double)(numberOfshares);
sum += stockPrice;
i++;
}
System.out.println("the total stockprice owned is: " + sum );
}
}
And this is the output i get:
Enter the Name of the Stock
nestle
Enter the Share price
2
Enter the number of owned shares
4
Enter the Name of the Stock
Enter the Share price
What makes the input skip during the second loop?
Again as per my comment the problem is that your code doesn't handle the End Of Line (EOL) token when calling nextInt() or nextDouble().
The solution is to use input.nextLine() after getting your int and double in order to swallow the EOL token:
sharePrice = input.nextDouble();
input.nextLine(); // add this
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
input.nextLine(); // add this
stockPrice = sharePrice * (double)(numberOfshares);
The problem is that the last time you call
int numberOfshares = input.nextInt();
in the first iteration of the loop your first passes a carriage return as the next stock name. You could instead use:
double sharePrice = Double.parseDouble(input.nextLine());
and
int numberOfshares = Integer.parseInt(input.nextLine());
You should readout the newline characters after reading the share price and number of shares:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double sharePrice = 0, stockPrice = 0;
int i = 0;
double sum = 0;
String name;
while (i < 2)
{
System.out.println("Enter the Name of the Stock ");
name = input.nextLine();
System.out.println("Enter the Share price ");
sharePrice = input.nextDouble();
// Read out the newline character after the share price.
input.nextLine();
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
// Read out the newline character after the number of shares.
input.nextLine();
stockPrice = sharePrice * (double) (numberOfshares);
sum += stockPrice;
System.out.println(String.format("Name: %s, Price: %f, Shares: %d, Total: %f",
name,
sharePrice,
numberOfshares,
stockPrice));
i++;
}
System.out.println("the total stockprice owned is: " + sum);
}
See the lines with comments above:

scanner won't scan

I am having trouble coding a hw program that is made to generate test with multiple choice and essay questions. Everything works except my program skips lines when it goes to read a part of the essay class. I know it has to do with the scanner and scan.nextline, scan.nextInt and scan.next, etc but I am confused on how exactly to fix it.
Thank you for your help.
import java.util.*;
public class TestWriter
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
String type=null;
System.out.println ("How many questions are on your test?");
int num = scan.nextInt ();
Question [] test = new Question [num];
for (int i=0; i <num; i++)
{
System.out.println ("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");
type = scan.next ();
scan.nextLine ();
if (type.equals ("e"))
{
test [i] = new Essay ();
test [i].readQuestion ();
}
if (type.equals ("m"))
{
test [i] = new MultChoice ();
test [i].readQuestion ();
}
}
for (int i=0; i <num; i++)
{
System.out.println ("Question " + (i+1)+": "+ type);
test [i].print ();
}
}
}
here is the essay class
public class Essay extends Question
{
String question;
int line;
public void readQuestion ()
{
System.out.println ("How many lines?");
line = scan.nextInt ();
scan.next ();
System.out.println ("Enter the question");
question = scan.nextLine ();
}
public void print ()
{
System.out.println (question);
for (int i=0; i <line; i++)
System.out.println ("");
}
}
Using scan.nextInt() will generate the following problems
If your input is "5 5", nextInt() will get the next integer leaving the remaining " 5" of the buffer line. Of which the remaining " 5" will be caught by
type = scan.next();
In the class test writer:
System.out.println("How many questions are on your test?");
int num = scan.nextInt();
Question[] test = new Question[num]; for(int i=0; i<num; i++)
{
System.out.println("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");
type = scan.next();
This will generate the issue as i have mentioned above.
To fix this you can either
a) Ensure that input is solely a number
b) Get the entire line like so String temp = scan.nextLine(); then convert it to a integer. This will you can play with the string and check if its the input you require i.e if the 1st letter / set of numerical digits is an e/m or an integer.
The problem with scan.nextInt() is that it only gets the next integer of the input line. If there are spaces after the input it was taken from i.e "5 5" it will grab only the next int 5 and leave " 5" behind.
Thus i would recommend using scan.nextLine() and manipulating the string to ensure that the input can be handled and verified and at the same time ensuring that you do not get confused of where the scanner is at.
You should use .next() / .nextInt() if you are handling an input with various parameters you want to specifically catch such as "25 Male Student 1234" in this case the code would be as such
int age = scan.nextInt();
String sex = scan.next();
String job = scan.next();
int score = scan.nextInt();
Your readQuestion function should be ...
public void readQuestion()
{
System.out.println("How many lines?");
line = scan.nextInt();
scan.nextLine();
System.out.println("Enter the question");
question = scan.nextLine();
}
It should be scan.nextLine(); to add an empty new line at the end
In your TestWriter.main() method what are you expecting at 3 line in following code:
System.out.println("Question " + (i+1) + ": Essay or multiple choice question? (e/m)");
type = scan.next();
scan.nextLine(); //LINE 3: What are you expecting user to enter over here.
the control flow will stuck at this point unless you enter something on the console.

Categories

Resources