Need assistance! printing previous user input data from a loop - java

Hey new guy here need assistance in my problem! i need to print previous user input data from a loop the problem is that it prints the last data the user inputs. Please shed some light my mind is getting dark. I appreciate all of you answers. Thank you!
My program: (Sorry if it's disgusting af)
package activity2;
import java.util.Scanner;
public class Activity2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] name = {"Milk","Juice","Energy drink","Water","Softdrink","Beer","Wine","Coffee"};
int[] pnum = {0,1,2,3,4,5,6,7};
double[] price = {300,100,220,120,200,350,400,130};
String[] list = {"Enter product #: ","Enter quantity: ","Sub-total: "};
double sum=0,q=0,v,s;
int sum2=0, w;
String z = "";
int x,c = 0;
System.out.println(" Product Information");
System.out.println("------------------------------------------");
System.out.println("Name Price");
System.out.println("------------------------------------------");
System.out.println(pnum[0]+"."+name[0]+" "+price[0]);
System.out.println(pnum[1]+"."+name[1]+" "+price[1]);
System.out.println(pnum[2]+"."+name[2]+" "+price[2]);
System.out.println(pnum[3]+"."+name[3]+" "+price[3]);
System.out.println(pnum[4]+"."+name[4]+" "+price[4]);
System.out.println(pnum[5]+"."+name[5]+" "+price[5]);
System.out.println(pnum[6]+"."+name[6]+" "+price[6]);
System.out.println(pnum[7]+"."+name[7]+" "+price[7]);
System.out.println("------------------------------------------");
do{
System.out.print("Enter number of products: ");
int a = sc.nextInt();
for (x=0;x<a;x++){
System.out.print(list[0]);
w = sc.nextInt();
sum2 =w;
System.out.print(list[1]);
s = sc.nextDouble();
q = s * price[w];
System.out.println(list[2]+q);
sum +=q;
}
System.out.println("Total: " + sum);
System.out.print("Do you want another transaction?(y/n):");
z = sc.next();
x = a;
v = q;
System.out.println("Transaction Details");
for(int t=0; t<x; t++){
System.out.println(pnum[sum2]+"."+name[sum2]+"---------"+v);
}
System.out.println("TOTAL: " + sum);
System.out.print("Enter cash amount: ");
double i = sc.nextDouble();
if(sum>i){
System.out.println("Cash is insuffecient! Please try again:");
System.out.print("Enter cash amount: ");
i = sc.nextDouble();
}
double tc = i - sum;
System.out.print("Cash change"+tc);
}
while(z.equals("y"));
}
}

One approach is to use a StringBuilder.
(direct quote below from link)
"StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations."
You can save data with StringBuilder, then print everything all at one time. This makes life a little easier too ;-)
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] name = {"Milk","Juice","Energy drink","Water","Softdrink","Beer","Wine","Coffee"};
int[] pnum = {0,1,2,3,4,5,6,7};
double[] price = {300,100,220,120,200,350,400,130};
String[] list = {"Enter product #: ","Enter quantity: ","Sub-total: "};
double sum=0,q=0,v,s;
int sum2=0, w;
String z = "";
int x,c = 0;
System.out.println(" Product Information");
System.out.println("------------------------------------------");
System.out.println("Name Price");
System.out.println("------------------------------------------");
System.out.println(pnum[0]+"."+name[0]+" "+price[0]);
System.out.println(pnum[1]+"."+name[1]+" "+price[1]);
System.out.println(pnum[2]+"."+name[2]+" "+price[2]);
System.out.println(pnum[3]+"."+name[3]+" "+price[3]);
System.out.println(pnum[4]+"."+name[4]+" "+price[4]);
System.out.println(pnum[5]+"."+name[5]+" "+price[5]);
System.out.println(pnum[6]+"."+name[6]+" "+price[6]);
System.out.println(pnum[7]+"."+name[7]+" "+price[7]);
System.out.println("------------------------------------------");
do{
System.out.print("Enter number of products: ");
int a = sc.nextInt();
StringBuilder sb = new StringBuilder();
for (x=0;x<a;x++) {
System.out.print(list[0]);
w = sc.nextInt();
sum2 =w;
System.out.print(list[1]);
s = sc.nextDouble();
q = s * price[w];
System.out.println(list[2]+q);
sb.append(pnum[sum2]+"."+name[sum2]+"---------"+q + "\n");
sum +=q;
}
System.out.println("Total: " + sum);
System.out.print("Do you want another transaction?(y/n):");
z = sc.next();
x = a;
v = q;
System.out.println("Transaction Details");
System.out.println(sb);
System.out.println("TOTAL: " + sum);
System.out.print("Enter cash amount: ");
double i = sc.nextDouble();
if(sum>i){
System.out.println("Cash is insuffecient! Please try again:");
System.out.print("Enter cash amount: ");
i = sc.nextDouble();
}
double tc = i - sum;
System.out.print("Cash change"+tc);
}
while(z.equals("y"));
}
This will give you the output you're looking for.

The issue is you're not saving each entry. If you want to be able to print it back at the end you need to do this. I'm not exactly sure what you're trying to do, but this should at least give you an idea on what you need to do in order to be able to print out transaction details. Also you really need to name your variables a lot better.
import java.util.Scanner;
public class Activity2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] name = {"Milk","Juice","Energy drink","Water","Softdrink","Beer","Wine","Coffee"};
int[] pnum = {0,1,2,3,4,5,6,7};
double[] price = {300,100,220,120,200,350,400,130};
String[] list = {"Enter product #: ","Enter quantity: ","Sub-total: "};
double sum=0,q=0,v,s;
int sum2=0, w;
String z = "";
int x,c = 0;
System.out.println(" Product Information");
System.out.println("------------------------------------------");
System.out.println("Name Price");
System.out.println("------------------------------------------");
System.out.println(pnum[0]+"."+name[0]+" "+price[0]);
System.out.println(pnum[1]+"."+name[1]+" "+price[1]);
System.out.println(pnum[2]+"."+name[2]+" "+price[2]);
System.out.println(pnum[3]+"."+name[3]+" "+price[3]);
System.out.println(pnum[4]+"."+name[4]+" "+price[4]);
System.out.println(pnum[5]+"."+name[5]+" "+price[5]);
System.out.println(pnum[6]+"."+name[6]+" "+price[6]);
System.out.println(pnum[7]+"."+name[7]+" "+price[7]);
System.out.println("------------------------------------------");
do{
System.out.print("Enter number of products: ");
int a = sc.nextInt();
int[] productNum = new int[a];
String[] products = new String[a];
double[] prices = new double[a];
for (x=0;x<a;x++){
System.out.print(list[0]);
w = sc.nextInt();
sum2 =w;
System.out.print(list[1]);
s = sc.nextDouble();
q = s * price[w];
System.out.println(list[2]+q);
sum +=q;
productNum[x] = w;
products[x] = name[w];
prices[x] = q;
}
System.out.println("Total: " + sum);
System.out.print("Do you want another transaction?(y/n):");
z = sc.next();
x = a;
v = q;
System.out.println("Transaction Details");
for(int t=0; t<x; t++){
System.out.println(productNum[t]+"."+products[t]+"---------"+prices[t]);
}
System.out.println("TOTAL: " + sum);
System.out.print("Enter cash amount: ");
double i = sc.nextDouble();
if(sum>i){
System.out.println("Cash is insuffecient! Please try again:");
System.out.print("Enter cash amount: ");
i = sc.nextDouble();
}
double tc = i - sum;
System.out.print("Cash change"+tc);
}
while(z.equals("y"));
}
}

Related

Java grades exercise

I'm Adrian and i'm kinda new to programming, would like to learn more and improve. I was asked to do a grade average exercise and i did this , but i'm stuck at making the code so if you type a number instead of a name the code will return from the last mistake the writer did , like it asks for a name and you put "5". In my code gives an error and have to re-run it. Any tips?
import java.util.*;
import java.math.*;
import java.io.*;
class Grades {
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
At the heart of any solution for this, it requires a loop, and a condition for resetting.
String result = null;
while (result == null) {
//OUT: Prompt for input
String input = keyboard.next();
if (/* input is valid */) {
result = input; //the loop can now end
} else {
//OUT: state the input was invalid somehow
}
//Since this is a loop, it repeats back at the start of the while
}
//When we reach here, result will be a non-null, valid value
I've left determining whether a given input is valid up to your discretions. That said, you may consider learning about methods next, as you can abstract this prompting/verification into a much simpler line of code in doing so (see: the DRY principle)
There are several ways to do it.
But the best way is to use regex to validate the user input.
Have a look at the below code, you can add other validations as well using regex.
import java.util.Scanner;
class Grades {
public static boolean isAlphabetOnly(String str)
{
return (str.matches("^[a-zA-Z]*$"));
}
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
if(!isAlphabetOnly(name)){
System.out.println("Please enter alfabets only");
return;
}
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}

I keep getting the java:122 error: '.class' expected. How do I resolve it?

import java.util.*;
public class Averages{ //name class as public
public static void main(String[] args){
Scanner sc = new Scanner(System.in); //initialized string using 'new'
String Course;
int knowledgemark;
int communicationmark;
int thinkingmark;
int applicationmark;
int average;
int finalexam;
int average2;
String answer;
int maxK;
int maxC;
int maxA;
int maxT;
int knowledgeweight;
int communicationweight;
int thinkingweight;
int applicationweight;
String Assignment;
String Test;
int average3;
int weight;
int weightaverage;
int average4= 0;
System.out.println("What class are you calculating for?");
Course = Scan.nextLine();
System.out.println("What's your knowledge mark for this course?");
knowledgemark = Scan.nextLine();
System.out.println("What's your application mark for this course?");
applicationmark = Scan.nextLine();
System.out.println("What's your thinking mark for this course?");
thinkingmark = Scan.nextLine();
System.out.println("What's your communication mark for this course?");
communicationmark = Scan.nextLine();
average = ((knowledgemark + communicationmark + applicationmark + thinkingmark)/4);
average = Scan.nextInt();
System.out.println("Your average for" + Course + "is" + average);
System.out.println("Do you want to calculate your exam with your final exam mark? (yes or no)");
answer = Scan.next();
if(answer.equals ("yes")){
System.out.println("What is your final exam mark?");
finalexam = scan.nextInt();
average2 = (((average * 70) + finalexam * 30) /100);
System.out.println("Your final average in this course is" + average2);
}
else{
System.out.println("You average for" + Course + "is" + average);
}
System.out.println("You can also calculate your marks with tests/assignments");
Test = Scan.nextLine();
System.out.println("What test/assignment are you calculating for?");
Test = Scan.nextLine();
System.out.println("What is the weighting for knowledge?");
knowledgeweight = Scan.nextLine();
System.out.println("What is your knowledge mark for the test/assignment?");
maxK = Scan.nextLine();
System.out.println("What is the weighting for communication?");
communicationweight = Scan.nextLine();
System.out.println("What is your communication mark for the test/assignment?");
maxC = Scan.nextLine();
System.out.println("What is the weighting for application?");
applicationweight = Scan.nextLine();
System.out.println("What is your application mark for the test/assignment?");
maxA = Scan.nextLine();
System.out.println("What is the weighting for knowledge?");
thinkingweight = Scan.nextLine();
System.out.println("What is your thinking mark for the test/assignment?");
maxT = Scan.nextLine();
average3 = (maxK * knowledgeweight + maxC * communicationweight + maxT * thinkingweight + maxA * applicationweight);
System.out.println("Your final average for this test/assignment is" + average3);
System.out.println("What is the weight of the test/assignment (10, 30, 50)?");
weightaverage = Scan.nextInt;
weightaverage = (average3 * weightaverage);
System.out.println("Your assignment/test weighted is" + weightaverage);
int length;
Scanner scan = new Scanner(System.in);
System.out.println("How many classes do you have?");
length = scan.nextInt();
int[] firstArray = new int[length];
for(int i=0; i<length; i++){
System.out.println("What is your course mark for each class in order" + (1 + i) + "?");
firstArray[i] = scan.nextInt[];
}
}
}
Here is my code. The error is near the bottom of the page. Thanks ahead of time!
Please hep me fix this as I do not know what to do
It is my only error left to compile.
Thanks and greatly appreciated!
Edit: Formatted to show code in one snippet.
You are missing () in your call to nextInt() at
weightaverage = Scan.nextInt;
change it to something like
weightaverage = Scan.nextInt();
and
firstArray[i] = scan.nextInt[];
should be
firstArray[i] = scan.nextInt();
And, you aren't consistent with your Scanner name.
Scanner sc = new Scanner(System.in);
needs to be
Scanner Scan = new Scanner(System.in);
if you're going to call Scan.nextInt(). Also, you are calling nextLine() (which returns a String) and assigning the result to int variables.
Here's the code corrected with suggestions made by Elliott Frisch.
To reiterate:
You declared Scanner with the variable name sc, but used Scan.nextLine() in the remainder of the code. The correction is sc.nextLine().
sc.nextLine() cannot be converted to String. It returns an integer so for example, int knowledgemark = sc.nextInt(); is correct.
Some code was using sc.nextInt; or sc.nextInt[]; which should be corrected to sc.nextInt();.
import java.util.*;
public class Averages { //name class as public
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //initialized string using 'new'
String Course;
int knowledgemark;
int communicationmark;
int thinkingmark;
int applicationmark;
int average;
int finalexam;
int average2;
String answer;
int maxK;
int maxC;
int maxA;
int maxT;
int knowledgeweight;
int communicationweight;
int thinkingweight;
int applicationweight;
String Assignment;
String Test;
int average3;
int weight;
int weightaverage;
int average4 = 0;
System.out.println("What class are you calculating for?");
Course = sc.nextLine();
System.out.println("What's your knowledge mark for this course?");
knowledgemark = sc.nextInt();
System.out.println("What's your application mark for this course?");
applicationmark = sc.nextInt();
System.out.println("What's your thinking mark for this course?");
thinkingmark = sc.nextInt();
System.out.println("What's your communication mark for this course?");
communicationmark = sc.nextInt();
average = ((knowledgemark + communicationmark + applicationmark + thinkingmark) / 4);
average = sc.nextInt();
System.out.println("Your average for" + Course + "is" + average);
System.out.println("Do you want to calculate your exam with your final exam mark? (yes or no)");
answer = sc.next();
if (answer.equals("yes")) {
System.out.println("What is your final exam mark?");
finalexam = sc.nextInt();
average2 = (((average * 70) + finalexam * 30) / 100);
System.out.println("Your final average in this course is" + average2);
} else {
System.out.println("You average for" + Course + "is" + average);
}
System.out.println("You can also calculate your marks with tests/assignments");
Test = sc.nextLine();
System.out.println("What test/assignment are you calculating for?");
Test = sc.nextLine();
System.out.println("What is the weighting for knowledge?");
knowledgeweight = sc.nextInt();
System.out.println("What is your knowledge mark for the test/assignment?");
maxK = sc.nextInt();
System.out.println("What is the weighting for communication?");
communicationweight = sc.nextInt();
System.out.println("What is your communication mark for the test/assignment?");
maxC = sc.nextInt();
System.out.println("What is the weighting for application?");
applicationweight = sc.nextInt();
System.out.println("What is your application mark for the test/assignment?");
maxA = sc.nextInt();
System.out.println("What is the weighting for knowledge?");
thinkingweight = sc.nextInt();
System.out.println("What is your thinking mark for the test/assignment?");
maxT = sc.nextInt();
average3 = (maxK * knowledgeweight + maxC * communicationweight + maxT * thinkingweight + maxA * applicationweight);
System.out.println("Your final average for this test/assignment is" + average3);
System.out.println("What is the weight of the test/assignment (10, 30, 50)?");
weightaverage = sc.nextInt();
weightaverage = (average3 * weightaverage);
System.out.println("Your assignment/test weighted is" + weightaverage);
int length;
Scanner scan = new Scanner(System.in);
System.out.println("How many classes do you have?");
length = scan.nextInt();
int[] firstArray = new int[length];
for (int i = 0; i < length; i++) {
System.out.println("What is your course mark for each class in order" + (1 + i) + "?");
firstArray[i] = scan.nextInt();
}
}
}

Recall use input to perform certain tasks

It's a bit of a read, but I need to reuse the user input, is there a method I can use to manipulate the data input by the user.
Also for some reason when I output the total at the end it gives me an accumulated sum for each entry, i just need the total.
import java.util.*;
public class Account {
String Name = NewCamper.getCamperName();
private static double balance;
Account(){
balance = 0.0;
}
Account(String aFname, String aLname){
aFname = NewCamper.first;
aLname = NewCamper.last;
}
public void deposit(double amountDep){
balance=balance+amountDep;
}
private double oldBalance(){
return(Account.balance);
}
private double newBalance(double total){
return(balance-total);
}
public static void main(String args[]){
do{
System.out.println("Credit Camper Account? (yes/no)");
Scanner q =new Scanner(System.in);
String uq = q.nextLine();
if (uq.equalsIgnoreCase("yes")){
System.out.println("How much to credit?");
double c = q.nextDouble();
Account camp1 = new Account();
camp1.deposit(c);
System.out.println("Camper Credit: " + c);
}
else if(uq.equalsIgnoreCase("no")){
System.out.println(Account.balance);
}
else{
System.out.println("Invalid Response");
continue;
}
break;
}while(true);
List<String> transactions=new ArrayList<String>();
List<Double> amount=new ArrayList<>();
do{
System.out.println("Enter a Transaction: ");
Scanner tInput =new Scanner(System.in);
Scanner dInput =new Scanner(System.in);
String a =tInput.nextLine();
transactions.add(a);
System.out.println("Enter purchase amount: ");
double b =dInput.nextDouble();
amount.add(b);
System.out.println("Do you have new record ?(yes/no)");
String answer= tInput.nextLine();
if(answer.equalsIgnoreCase("Yes")){
continue;
}
break;
}while(true);
for (int i = 0; i < transactions.size(); i++) {
System.out.println(transactions.get(i));
}
System.out.println(transactions+" (£)"+amount);
System.out.println("Input Camper First Name: ");
Scanner afn = new Scanner(System.in);
String af = afn.nextLine();
System.out.println("Input Camper Surname: ");
Scanner aln = new Scanner(System.in);
String al = afn.nextLine();
NewCamper.first = af;
NewCamper.last = al;
System.out.println(af+" "+al+" 's transactions:"+transactions);
System.out.println(af+" "+al+" 's purchase amounts:"+amount);
double total=0.0d;
for(int counter = 0; counter<amount.size(); counter++){
total+=amount.get(counter);
System.out.println("Total Price: £"+ total);
}
}
}
Change this:
double total=0.0d;
for(int counter = 0; counter<amount.size(); counter++){
total+=amount.get(counter);
System.out.println("Total Price: £"+ total);
}
to:
double total=0.0d;
for(int counter = 0; counter<amount.size(); counter++){
total+=amount.get(counter);
}
System.out.println("Total Price: £"+ total);
Shouldn't come as a surprise that putting an output statement into a loop tends to output more than one line.

Java.Lang.Stringindexoutofboundsexception index out of range (0)

each time the program tries to loop, the error "java.lang.stringindexoutofboundsexception" comes up and highlights
ki=choice.charAt(0);
Does anyone know why that happens?. I'm brand new to programming and this has me stumped. Thanks for any help. Any solution to this problem would be amazing.
import java.util.Date;
import java.util.Scanner;
public class Assignment2
{
public static void main(String Args[])
{
Scanner k = new Scanner(System.in);
Date date = new Date();
double Wine = 13.99;
double Beer6 = 11.99;
double Beer12 = 19.99;
double Beer24 = 34.99;
double Spirit750 = 25.99;
double Spirit1000 = 32.99;
int WinePurchase = 0;
double WineTotal=0.0;
double GrandTotal = 0.0;
double GST = 0.0;
String complete = " ";
String choice;
char ki = ' ';
double Deposit750 = 0.10;
double Deposit1000 = 0.25;
System.out.println("------------------------------\n" +
"*** Welcome to Yoshi's Liquor Mart ***\nToday's date is " + date);
System.out.println("------------------------------------\n");
do{
if(ki!='W' && ki!='B' && ki!='S')
{
System.out.print("Wine is $13.99\nBeer 6 Pack is $11.99\n" +
"Beer 12 pack is $19.99\nBeer 24 pack is $34.99\nSpirits 750ml is $25.99\n"+
"Spirits 100ml is $32.99\nWhat is the item being purchased?\n"+
"W for Wine, B for beer and S for Spirits, or X to quit: ");
}
choice = k.nextLine();
ki= choice.charAt(0);
switch (ki)
{
case 'W':
{
System.out.print("How many bottles of wine is being purchased: ");
WinePurchase = k.nextInt();
System.out.println();
WineTotal = Wine*WinePurchase;
GST = WineTotal*0.05;
WineTotal += GST;
System.out.println("The cost of "+WinePurchase+ " bottles of wine including" +
" GST and deposit is " + WineTotal);
System.out.print("Is this customers order complete? (Y/N) ");
complete = k.next();
break;
}
}
}while (ki!='X');
The error means there the index "0" is outside the range of the String. This means the user typed in no input, such as the case when you start the program and hit the enter key. To fix this, simply add the following lines of code:
choice = k.nextLine();
if(choice.size() > 0){
//process the result
}
else{
//ignore the result
}
Let me know if this helps!
As you pointed out, the problem is in:
choice = k.nextLine();
ki= choice.charAt(0);
From the docs nextLine(): "Advances this scanner past the current line and returns the input that was skipped."
So in case the user pressed "enter" the scanner will go to the next line and will return an empty String.
In order to avoid it, simply check if choice is not an empty string:
if (!"".equals(choice)) {
// handle ki
ki= choice.charAt(0);
}
Try this:
Your problem was with the Scanner (k) you need to reset it everytime the loop start over.
import java.util.Date;
import java.util.Scanner;
public class Assignment2
{
public static void main(String Args[])
{
Scanner k;
Date date = new Date();
double Wine = 13.99;
double Beer6 = 11.99;
double Beer12 = 19.99;
double Beer24 = 34.99;
double Spirit750 = 25.99;
double Spirit1000 = 32.99;
int WinePurchase = 0;
double WineTotal=0.0;
double GrandTotal = 0.0;
double GST = 0.0;
String complete = " ";
String choice;
char ki = ' ';
double Deposit750 = 0.10;
double Deposit1000 = 0.25;
System.out.println("------------------------------\n" +
"*** Welcome to Yoshi's Liquor Mart ***\nToday's date is " + date);
System.out.println("------------------------------------\n");
do{
if(ki!='w' && ki!='b' && ki!='s')
{
System.out.print("Wine is $13.99\nBeer 6 Pack is $11.99\n" +
"Beer 12 pack is $19.99\nBeer 24 pack is $34.99\nSpirits 750ml is $25.99\n"+
"Spirits 100ml is $32.99\nWhat is the item being purchased?\n"+
"W for Wine, B for beer and S for Spirits, or X to quit: ");
}
k= new Scanner(System.in);
choice = k.nextLine();
ki= choice.toLowerCase().charAt(0);
switch (ki)
{
case 'w':
System.out.print("How many bottles of wine is being purchased: ");
WinePurchase = k.nextInt();
System.out.println();
WineTotal = Wine*WinePurchase;
GST = WineTotal*0.05;
WineTotal += GST;
System.out.println("The cost of "+WinePurchase+ " bottles of wine including" +
" GST and deposit is " + WineTotal);
System.out.print("Is this customers order complete? (Y/N) ");
complete = k.next();
break;
}
if(complete.toLowerCase().equals("y"))
break;
}while (ki!='x');
}
}

Code seems to skip over if or for loop

When I enter input that satisfies everything and doesn't trigger any of my errors, the program just exits after last input like it is skipping over the for or if loop.
Also after System.out.printf("Enter the name of your second species: "); it won't allow for any input, it just skips to the next prompt. I'm not sure why that is. The section above it asking for the first species' info works fine.
import java.util.Scanner;
public class HW2johnson_pp1 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.printf("Please enter the species with the higher" +
" population first\n");
System.out.printf("Enter the name of your first species: ");
String Species1 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop1 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth1 = keyboard.nextInt();
System.out.printf("Enter the name of your second species: ");
String Species2 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop2 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth2 = keyboard.nextInt();
if (Pop2 > Pop1) {
System.out.printf("The first population must be higher. \n");
System.exit(0);
}
Species input1 = new Species();
input1.name = Species1;
input1.population = Pop1;
input1.growthRate = Growth1;
Species input2 = new Species();
input2.name = Species2;
input2.population = Pop2;
input2.growthRate = Growth2;
if ((input1.predictPopulation(1) - input2.predictPopulation(1)) <=
(input1.predictPopulation(2) - input2.predictPopulation(2))){
System.out.printf(Species2 + " will never out-populate " +
Species1 + "\n");
}
else {
for (int i = 0; input2.predictPopulation(i) <=
input1.predictPopulation(i); i++) {
if (input2.predictPopulation(i) == input1.predictPopulation(i)) {
System.out.printf(" will out-populate \n");
}
}
}
}
}
This for the predictPopulation():
public int predictPopulation(int years)
{
int result = 0;
double populationAmount = population;
int count = years;
while ((count > 0) && (populationAmount > 0))
{
populationAmount = (populationAmount +
(growthRate / 100) * populationAmount);
count--;
}
if (populationAmount > 0)
result = (int)populationAmount;
return result;
}
This is because you never print anything after Species 2 overtakes Species 1, except in the very special case that Species 2 and Species 1 have exactly the same population in some year.
This is because, when you enter Species 1's growth rate, you enter an integer, and then press Enter. keyboard.nextInt() swallows the integer, but leaves the newline on the input-buffer, so the subsequent keyboard.nextLine() thinks there's an empty line there waiting for it.

Categories

Resources