Wondering if anyone can help me, I'm trying to create a program that adds up the total amount of all the prices entered for each book, for as long as the do/while loop keeps looping, but all I have so far is that every time the loop restarts it deletes the previous assigned variable value! Can anybody steer me in the right direction? I'm just beginning with java so my knowledge pool is pretty low.
String surname, firstname, email, cfn, btitle, finished;
double pno, nochild, cage, noboks, costbook=0, totalcost, averagecost, price;
k = new Scanner(System.in);
System.out.print("Welcome - What is your Family surname?");
surname = k.next();
System.out.print("What is your own first name?");
firstname=k.next();
System.out.print("What is your email address?");
email=k.next();
System.out.print("What is your phone number?");
pno=k.nextInt();
System.out.print("How many children do you have?");
nochild=k.nextInt();
System.out.print("You are Alan " + surname);
System.out.println();
int childcounter=1;
do{
System.out.print("What is your childs first name "+childcounter+" of " +nochild+"?");
cfn=k.next();
System.out.print("What is "+cfn+"'s age?");
cage=k.nextInt();
System.out.println();
do {
System.out.print("What is the title of the book "+cfn+" would like?");
btitle=k.next();
System.out.print("Price of '"+btitle+"' ?");
price=k.nextDouble();
System.out.println();
System.out.print("Do you want to finish? y/n ");
finished=k.next();
}
while (finished.equalsIgnoreCase("n"));
if (finished.equalsIgnoreCase("y"))
{
}
childcounter++;
}
while (childcounter <= nochild);
System.out.print("Heres the book price €"+price);
}
use like this
String[][] data = new String[numberOfLoops][numberOfVariable];
so you can use
data[nthIteration][variable] = scanner.next();
To have variables persist through a loop, you need to define them before the loop begins. If a variable is defined inside of a loop, it will be deleted once the loop is finished.
int test;
for (int i=0; i < 10; i++)
{
test = test * i;
}
//test's value will persist
Tutorial: Java >> Variable Scope
If you want to store multiple values into a variable, you should look at Arrays
Tutorial: Java >> Arrays
Probably you need to define a class that contains those variables/fields:
public class MyInfo {
String surname, firstname, email, cfn, btitle, finished;
double pno, nochild, cage, noboks, costbook=0, totalcost, averagecost, price;
}
then create new instance of the class on each iteration of the while loop and store each new object in a list/ArrayList
Related
I created a simple console based student system where basically the program will ask if you want to input name of students or view the list of names you inputted. The flow of the output is as shown below:
*******CONSOLE BASED STUDENT SYSTEM************
1. Input Student Name
2. List of students
Enter the number of choice: 1
Enter number of students to input: 3
****************************************
Student No. 1
Enter full name: Alpha Jones
****************************************
Student No. 2
Enter full name: Beta Jones
****************************************
Student No. 3
Enter full name: Gamma Jones
Do you wish to proceed back to menu?(y/n): y
*******CONSOLE BASED STUDENT SYSTEM************
1. Input Student Name
2. List of students
Enter the number of choice: 2
******LIST OF STUDENTS******
NULL
NULL
NULL
Firstly, I input three new students names Alpha Jones, Beta Jones and Gamma Jones but when I chose to view all names, everything is null. The three names should appear.
Here is the code for Student Class:
public class Student {
private String[] names;
private int numInput;
public Student(){
}
public Student(String[] fullName, int nI){
numInput = nI;
names = new String[nI];
for(int index = 0; index < nI; index++){
names[index] = fullName[index];
}
}
public String[] getList(){
return names;
}
public int getNumStudents(){
return numInput;
}
}
This is where I setup the values that will be passed on from the PracticeOne class, and later on, I will return that value back for display in PracticeOne Class.
Here is the PracticeOne Class(This is where the main method is located):
import java.util.Scanner;
public class PracticeOne {
public static void main(String[]args){
Scanner hold = new Scanner(System.in);
int menuNumChoice;
String response;
do{
System.out.println("******CONSOLE BASED STUDENT SYSTEM******");
System.out.println("1. Input Student Name");
System.out.println("2. List of Students");
System.out.print("Enter the number of choice: ");
menuNumChoice = hold.nextInt();
switch(menuNumChoice){
case 1:
inputStudentName(hold);
break;
case 2:
listStudents();
break;
default:
System.out.println("ERROR 101");
break;
}
System.out.print("Do you wish to proceed?(y/n): ");
response = hold.nextLine();
}while(response.equalsIgnoreCase("y"));
}
public static void inputStudentName(Scanner hold){
int numInput;
System.out.print("Enter number of students to input: ");
numInput = hold.nextInt();
hold.nextLine();
String[] fullName = new String[numInput];
for(int x = 0; x < numInput; x++){
System.out.println("***************************");
System.out.println("Student No. " + (x + 1));
System.out.print("Enter full name: ");
fullName[x] = hold.nextLine();
System.out.println();
}
Student s = new Student(fullName,numInput);
}
public static void listStudents(){
Student s = new Student();
System.out.println("******LIST OF STUDENTS******");
for(int y = 0; y < s.getNumStudents();y++){
System.out.println(s.getList());
}
}
}
Firstly I called an instance of Student in inputStudentName() method, which passes an argument for the fullname and the number of arrays being used, and tries to transfer it to Student class constructor, to get the values from there later on.
In the listStudents method, I tried displaying it by calling the getList() method from Student class to supposedly get back the names that was inputted earlier but everything was NULL. I also tried getting back the number of arrays through the getNumStudents() method but it also failed.
Kindly share some advice on how to work around with this problem or if theres a better way, suggest new things to achieve my goal.
public static void listStudents(){
**Student s = new Student();**
System.out.println("******LIST OF STUDENTS******");
for(int y = 0; y < s.getNumStudents();y++){
System.out.println(s.getList());
}
}
This is your listStudents logic. Instead of using the data you already created, you just create a new instance of Student. It's quite normal that this doesn't contain any information.
In your input method, you also only save the data in a local variable. This means, that once the method is finished, the data is lost.
Add a static List<Student> students = new ArrayList<>(); to your class. At the end of each input method, add the Student object to this list.
In listStudents, don't create a local student, but print the ones you stored in this List.
Based on your current system,first you can create a global variable Student[] or List then at the end of ' input Student Name()' method to save your dat.
Another Way you can use database to save your data,But this is not necessary for your system.
I'm writing a program that gathers a first name, a last name, and the sales figure of an employee. I have all the basics working perfectly but I have 1 issue. In my while loop I have programmed it so if the user enters "add" then it will call a method I made in a different class and add whatever number they entered to the employees current sales total. The code works, but for some reason when I test it I have to enter "add" twice before it runs; is there anyway I can fix this?(I left out a bunch of code in the middle as I feel it wasn't important to this question.)
//local constants
final int QUIT = -1;
final String ADD = "add";
final String SUBTRACT = "subtract";
//local variables
int soldItems;
String addition;
String subtraction;
String nameFirst;
String nameLast;
//while the input is not QUIT
while(soldItems != QUIT)
{
//Clear screen then prompt the user to add or subtract
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.print(Util.setLeft(35, "Add or Subtract: "));
addition = Keyboard.readString();
subtraction = Keyboard.readString();
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
//if the user enters add the program will add to the employee total
if(addition.equals(ADD))
{
info.addition(soldItems);
}
//else the program will subtract from the employee total
else
{
info.subtraction(soldItems);
}
//Displays the employee information and prompts the user for the next sales figure
System.out.println(info.toString());
System.out.println();
System.out.print(Util.setLeft(40, "Input the next Sales Figure: "));
soldItems = Keyboard.readInt();
}//end while
//clear screen
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
//End of program message and Final employee information
System.out.print(Util.setLeft(45, "Final Employee Information"));
System.out.println(info.toString());
addition = Keyboard.readString();
subtraction = Keyboard.readString();
You dont need to use two of them, just use input = Keyboard.readString(); and then check the input and process it accordingly.
I am currently trying to search through a linked list and update the data in a certain node given a String name. I don understand where I am going wrong. I do not receive any error when I run the program but the data that I "update" never changes.
My updateGpa method in my linkedlist class
public void updateGpa(String name, double gpa){
Node<Student> temp = head;
double foundData;
boolean exists = false;
for(int i = 0; (i < size) && !exists; i++){
if(temp.data.getName().equals(name)){
foundData =gpa;
temp.data.setGpa(foundData);
exists = true;
}
temp = getNode(i);
}
}
My main method where I call the updateGpa method
System.out.println("Update a students GPA by entering their name: ");
student = in2.next();
System.out.println("Enter " + student + "'s new GPA: ");
gpa = in1.nextDouble();
studentList.updateGpa(student, gpa);
break;
Student list is my linked list.
I have solved my own problem, unfortunately I have to chalk it up to user error in my main method I have student = in2.next where it should have been in2.nextLine It was only reading in the first name rather than the first and last name so when it was comparing the string in the updateGpa method it would never find a match because the string wasn't exactly equal. Sorry to waste your time but thank you for your input
User input from scanner method to array of 5 indexes also gives user ability to delete any index matching with string from one of the index.
ALL I want to achieve in this is in this while loop I would like to settle city (option 1), which means creating one as you can probably see from my code. This is where user will type any name they like no restrictions. once they settle the city loops starts again. However it does remember that user created a city earlier. I can have upto 5 cities. There is cost associate with settling new city. I know how to do those conditionals. I am just not sure about this string array.
ArrayList or Array class is not allowed.
where as, option 2 I can demolish any of the city i have created by giving user lists of city they have made earlier. I have to keep minimum of at least one city.
IF you are wondering then this is based on Civilization game.
Please ask for clarification as this may not be
straight forward. thanks
while (playing) {
System.out.println("\nPlease make your selection!");
System.out.println("\n1. Settle a City"
+ "\n2. Demolish a City"
+ "\n3. Build Militia"
+ "\n4. Research Technology"
+ "\n5. Attack Enemy City"
+ "\n6. End Turn\n");
String gameChoice = userinput.nextLine();
if (gameChoice.equals("1")) {
System.out.println("\nWhat would you like to"
+ " name your city?");
String cityname = userinput.nextLine();
cityname = cityNames[0];
} else if (gameChoice.equals("2")) {
System.out.println("What city would you like to demolish?");
for (int i = 0; i < 5 ; i++) {
System.out.print(cityNames[i]);
System.out.print("");
}
} else if (gameChoice.equals("3")) {
System.out.println("You have military points");
} else if (gameChoice.equals("4")) {
System.out.println("You have Research Technology points");
} else if (gameChoice.equals("5")) {
System.out.println("You have zero points");
} else {
System.out.println(" Thanks for playing ");
}
playing = false;
}
First, here:
String cityname = userinput.nextLine();
cityname = cityNames[0];
You are assigning cityname to user input and then you are assigning it to something in cityNames array, that doesn't make sense, maybe you pasted wrong or something, but just in case, this should be the other way around, like this:
cityNames[0] = cityname;
You have playing = false at the end so the loop is gonna just end when user types the city name, you need to either remove this playing = false or use continue; after cityNames[0] = cityName;, that's gonna go to the next iteration of a loop, without going all the way down to playing = false.
I'm trying to write a program that needs to stop when the target of £500 has been met. I have to use a DO WHILE loop to do this.
It needs to record how many donations it receives before it reaches £500, also it needs to record the name of the person with the highest donation given and what the largest donation was.
I cannot get the program to update the name of the person with the highest donation. The code I have so far is below. Please tell me where I am going wrong.
I have a red line coming up under 'namemax' when I try to call it at the end outside of the loop, saying 'not initialized'
enter codeimport java.util.Scanner;
/**
* Created by IntelliJ IDEA.
* Date: 11/02/2015
* Time: 15:45
* UPDATE COMMENT ABOUT PROGRAM HERE
*/
public class DoWhile
{
public static void main(String[] args)
{
Scanner keyboard= new Scanner(System.in);
final double TOTAL=500;
String name,namemax;
double donation, donationTotal=0,currentMax=0;
int howManyDonation=0;
do
{
System.out.println("Please enter your name below");
name = keyboard.next();
System.out.println("");
System.out.println("Please enter the amount you would like to donate below");
donation = keyboard.nextDouble();
howManyDonation++;
donationTotal = donationTotal+donation;
if(donation>currentMax)
{
currentMax=donation;
namemax=name;
}//if
}//doWhile
while(donationTotal!=TOTAL);
System.out.println("The total number of donations is " + howManyDonation);
System.out.println("The largest donation was " + currentMax);
System.out.println("The name of the person with the largest donation is " + namemax);
}//main
}//class
here
Just change this line
String name,namemax;
into this:
String name,namemax = null;
Furthermore, change this
while(donationTotal != TOTAL);
into this:
while(donationTotal < TOTAL);
You have a pretty simple problem here. You are updating namemax inside of an if loop only. That means that as far as the code is concerned, there is a possible situation in which it could never be assigned. In practice, because of what you are doing, that can't actually happen but the compiler doesn't understand that.
To fix it,
change
string name,namemax;
to
string name;
string namemax = "";
That should take care of it.
it gives at least one sutuation where namemax not will be set. So you have to initialize the string.
Simply change
String name,namemax ;
To
String name,namemax = null;
or
String name,namemax = "";
The compiler can't guarantee that you'll actually set the namemax before you exit the loop. You should initialize namemax to the empty string to fix this problem.