I'm trying to do as the picture shows here:
This is my code:
import java.util.Scanner;
public class IcsProject
{
public static void main(String [] args)
{
Scanner keyboard= new Scanner (System.in);
int menuNum,ID,semNum,semCode,semCourses;
do{
System.out.println("Please Enter your Choice from the menu:");
System.out.println("1. Enter Student Sanscript");
System.out.println("2. Display Transcript Summary");
System.out.println("3. Read Student Franscript from a File");
System.out.println("4. Write Transcript Summary to a File");
System.out.println("5. Exit");
menuNum = keyboard.nextInt();
if (menuNum == 2 || menuNum == 3 || menuNum == 4)
System.out.println("Not working");
} while (menuNum > 1 && menuNum < 5);
//// Option 1: Enter student transcript
if (menuNum == 1)
System.out.println("Please enter your student's FIRST and LAST name:");
String stuName = keyboard.nextLine();
System.out.println("Please enter the ID number for " + stuName);
ID = keyboard.nextInt();
System.out.println("Please enter the number of semesters");
semNum = keyboard.nextInt();
for(int i=1 ; i < semNum ; i++)
{System.out.println("Please enter semester code for semester n# " + semNum);
semCode = keyboard.nextInt();
System.out.println("Please enter the number of courses taken in " + semCode );
semCourses = keyboard.nextInt();}
System.out.println("Enter course code, credit hours, and letter grade ")
///I stopped here
}
Do I have to use array starting from the semester code? show me an example please.
After entering all the values The program should show the Menu again so I can choose from it. How to do that?
I'm having a problem at the first question "entering the student first and last name"
The program just skip it and move to next question. Is there a mistake with my keyboard.nextLine();
I would use a list of objects which have all the fields you want to record.
For examples, just use google.
http://www.google.com/search?q=java+list+examples 27.9 million result
http://www.google.com/search?q=java+object+examples 18 million results.
http://www.google.com/search?q=java+array+examples 15 million results.
Regarding issue #2 - put the menu in a separate method. use a loop that it's condition is the menu or something similar to process according to the result from menu (this is abstract, I think you can figure it out from here):
while(doAnotherLoop)
{
switch(showMenu())
{
case 1:
...
case 2:
...
case 5: // Exit
doAnotherLoop = false;
}
}
Regarding issue #3. You read an int: menuNum = keyboard.nextInt(); but the line is not over, so the next nextLine (String stuName = keyboard.nextLine();) takes the rest of the line. use nextLine() and parse the integers instead.
Related
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> game = new ArrayList<String>();
ArrayList<Integer> score = new ArrayList<Integer>();
ArrayList<Integer> time = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "yes";
{
do {
System.out.print("Please enter your username: ");
name.add(scanner.nextLine());
System.out.println("Please enter the game: ");
game.add(scanner.nextLine());
System.out.println("Please Enter Achievement Score: ");
score.add(scanner.nextInt());
System.out.println("Please Enter Playtime: ");
time.add(scanner.nextInt());
System.out.print("Any letter to continue alternatively type quit to Quit.");
answer = scanner.next();
} while (!answer.equals("quit"));
if (answer.equals("quit")); //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the database.");
for (int i = 0; i < name.size(); i++) {
System.out.print("Username:" +name.get(i)+"\n");
System.out.print("~~~~~~~~~~~~" +"\n");
System.out.print("Game:" +game.get(i)+"\t");
System.out.print("Score:" +score.get(i)+"\n");
System.out.print("Minutes played:"+time.get(i));
System.out.println("");
}
}
}
}
}
The problem with this is that the program is not quitting upon typing Quit but it is continuing and placing two questions on one line, shown below. how can I solve this problem?
Please enter your username: abc123
Please enter the game:
GTA V
Please Enter Achievement Score:
1200
Please Enter Playtime:
120
Any letter to continue alternatively type quit to Quit.Quit
Please enter your username: Please enter the game:
The issue is that you are comparing upper and lower case values of quit. You need to set them to the same case type for them to be equal and quit the program.
change your check to
while (!answer.toLowerCase().equals("quit"));
if (answer.toLowerCase().equals("quit"));
and that will change your input to lowercase which is what your are comparing it to.
I don't see any problem except that you have not closed the scanner. You can run this and you can see that the scanner is closed and go to normal execution after word quit.
import java.util.ArrayList;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> game = new ArrayList<String>();
ArrayList<Integer> score = new ArrayList<Integer>();
ArrayList<Integer> time = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "yes";
{
do {
System.out.print("Please enter your username: ");
name.add(scanner.nextLine());
System.out.println("Please enter the game: ");
game.add(scanner.nextLine());
System.out.println("Please Enter Achievement Score: ");
score.add(scanner.nextInt());
System.out.println("Please Enter Playtime: ");
time.add(scanner.nextInt());
System.out.print("Any letter to continue alternatively type quit to Quit.");
answer = scanner.next();
} while (!answer.equals("quit"));
if(answer.equals("quit")){
System.out.println("you have just quit");
scanner.close();
} //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the database.");
for (int i = 0; i < name.size(); i++) {
System.out.print("Username:" +name.get(i)+"\n");
System.out.print("~~~~~~~~~~~~" +"\n");
System.out.print("Game:" +game.get(i)+"\t");
System.out.print("Score:" +score.get(i)+"\n");
System.out.print("Minutes played:"+time.get(i));
System.out.println("");
}
}
System.out.print("You are done with scanner");
}
}
}
I just tried your program and it does quit if you type "quit" (all lowercase) like your command line instruction suggest:
System.out.print("Any letter to continue alternatively type quit to Quit.");
If you want your quit instruction to be case-insensitive you should replace this line:
} while (!answer.equals("quit"));
with this:
} while (!answer.equalsIgnoreCase("quit"));
I hope that helped!
Your quit information System.out.print("Any letter to continue alternatively type quit to Quit."); says that you need to put quit all lowercase word to end.
Also change answer = scanner.next(); to answer = scanner.nextLine();
EDIT:
As you don't have any error control you can consider this code:
do {
System.out.print("Please enter your username: ");
name.add(scanner.nextLine());
System.out.println("Please enter the game: ");
game.add(scanner.nextLine());
System.out.println("Please Enter Achievement Score: ");
score.add(Integer.valueOf(scanner.nextLine()));
System.out.println("Please Enter Playtime: ");
time.add(Integer.valueOf(scanner.nextLine()));
System.out.print("Any letter to continue alternatively type quit to Quit.");
answer = scanner.nextLine();
} while (!answer.equals("quit"));
I changed scanner.nextInt() to Integer.valueOf(scanner.nextLine()). Using nextLine() helps scanner to flush all data before your code goes to the next line.
I am trying my hand a few basic do-while codes, and am running into a couple of problems.
I want the code to ask the user to input 1 of 3 options (choosing which group they would like to add a number to, or to exit and total), give an error if they input an irrelevant option, and then total all ints at the end for each group.
public static void main(String[] args) {
String answer = "default";
int grp1 = 0;
int grp2 = 0;
int input1 = 0;
int input2 = 0;
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (answer.equals("A") || answer.equals("B"));
grp1 += input1;
grp2 += input2;
keyboard.close();
System.out.println("Group 1's total is: + grp1);
System.out.println("Group 2's total is: + grp2);
}
I need the to add a qualifier for if the user does not input a valid option, I tried using else:
else {
System.out.println("Invalid option - Try again.")
}
but this just skips to printing the totals, and does not ask the user for another input. How would I best achieve this?
Also,
grp1 += input1;
grp2 += input2;
Only counts the lasted entered int, is there a way to have it add all the entered ints?
Any help would be greatly appreciated, even outside of the questions I asked.
I think you have two confusions.
1) The "while" line in your code applies to the "do" block above it. That means that based on where the grp1 += and grp2 += lines are, they will only ever be run once. I suggest moving those calls to the end of the loop. You could move each line inside the relevant if block so that the code is run every time the user successfully enters a number after A or B.
2) The while condition is asking if the user entered "A" or "B". It's saying if they did, continue looping by going back to "do". If they entered literally anything else (any invalid answer), it will stop and run the code after the "while" line. I think what you really want is while (!answer.equals("X")), which will continue the loop until the user correctly enters an "X" character.
You'll also want to move those grp += lines up a bit.
Just change the condition inside while And also shift the totalling logic
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
grp1 += input1;
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
grp2 += input2;
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (!answer.equals("X"));
keyboard.close();
This will make your do while loop running i.e showing options to user until they wishes to exit. And also group total would be updated properly. I have updated answer based on answer by #Devin Howard
For some reason, my code will not accept input on the last line "What would you like to order: "
Could anyone tell me what my error is here? It is compiling correctly and everything. I am only a beginner so please tell me in basic terms.
import java.util.Scanner;
import java.util.*;
class RestaurantMain {
public static void main(String[] args)
{
//Create an array list
ArrayList menu = new ArrayList();
//Variables//
int choice;
int customerChoice;
boolean trueFalse;
int restart = 0;
String choice2;
String addItems = "";
int menuCount = 0;
int indexCount = 0;
String item = "";
//Import input device
Scanner in = new Scanner(System.in);
ArrayList theMenu = new ArrayList();
System.out.println("Welcome to the Cooper's restaurant system!");
System.out.println("How can I help?");
System.out.println("");
System.out.println("1. Customer System");
System.out.println("2. Management System");
System.out.println("");
System.out.println("");
System.out.print("Which option do you choose: ");
choice = in.nextInt();
if (choice == 1) {
System.out.println("Our menu's are as follows:");
System.out.println("");
System.out.println("1. Drinks");
System.out.println("2. Starters");
System.out.println("3. Mains");
System.out.println("4. Desserts");
System.out.println("");
System.out.println("Please note - You MUST order 5 items.");
System.out.println("");
System.out.print("What menu would you like to follow? ");
customerChoice = in.nextInt();
if (customerChoice == 1) {
System.out.println("Drinks Menu");
System.out.println("Would you like to order? ");
choice2 = in.nextLine();
if (choice2 == "yes") {
System.out.println("Please enter the amount of items you want to order: ");
while (indexCount <= menuCount);
System.out.println("Please enter your item: ");
item = in.nextLine(); {
theMenu.add(item);
}
}
}
if (customerChoice == 2) {
System.out.println("Starters Menu");
}
if (customerChoice == 3) {
System.out.println("Mains menu");
}
if (customerChoice == 4) {
System.out.println("Desserts Menu");
}
You need to call in.nextLine() right after the line where you call in.nextInt()
The reason is that just asking for the next integer doesn't consume the entire line from the input, and so you need skip ahead to the next new-line character in the input by calling in.nextLine()
customerChoice = in.nextInt();
in.nextLine();
This pretty much has to be done each time you need to get a new line after calling a method that doesn't consume the entire line. Consider using a BufferedReader object instead!
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int integer = Integer.parseInt(reader.readLine());
This will throw the same errors that Scanner.nextInt() does if the input can't be parsed as an integer.
Regarding your comment about errors, there is one:
while (indexCount <= menuCount);
System.out.println("Please enter your item: ");
item = in.nextLine(); {
theMenu.add(item);
}
}
Should instead be like the following:
while(indexCount <= menuCount){
System.out.println("Please enter your item: ");
item = in.nextLine();
theMenu.add(item);
}
Also, it isn't strictly necessary, but I suggest that you do declare the ArrayList's generic type when instantiating the list, so that further calls to theMenu.get() don't need to be casted to a String.
ArrayList<String> theMenu = new ArrayList<String>();
When comparing strings, ensure that you use the str.equals("string to compare with") method, instead of the equality operator (==). Therefore for example, choice2 == "yes" should instead be choice2.equals("yes"). Using equalsIgnoreCase instead of equals would ignore case differences, which may be useful in this situation.
insted of in.nextLine(); function you just try another scanner functions like 'in.next()'. just R&D with the methods that already give the JVM itself.
you just use correct the logic and use equal() or equlIgnoreCase() methods insted of "=" operator.
Create a java file in NetBeans, name it Catalog.java.
Create one String array to store 3 products for a catalogue
Create the appropriate variables to store the product name, product code and product price.
At the start of the program display the catalogue for the user by looping through the array and outputting it to the screen with a number listing for each product, as shown above
Create an infinite loop to enter orders; to stop the loop the user should enter 0.
Keep a running total (accumulator) of all products amount total and sub-total (multiple accumulators)
Write a method to calculate the taxes and return a grand total
Write another method to print out the order as listed above
its supposed to be entered like this
I would like to know how to have the user input like this and be stored in an array.
Enter Order Number (0 to stop): M3487
Enter Quantity: 2
Enter Order Number (0 to stop): W3876
Enter Quantity: 3
Enter Order Number (0 to stop): R9983
Enter Quantity: 3
Enter Order Number (0 to stop): 0
when i enter the code "M3487" its not going to the quantity, its ending the program.
This is the code I have so far. I'm a beginner, so please bear with me.
package catalog;
import java.util.*;
public class Catalog {
static String products[] = new String[3];
static int answer;
public static void main(String[] args) {
System.out.println("------------------");
System.out.println("Shopping Catalog");
System.out.println("------------------");
String[] pCode = new String[3];
float pPrice[] = new float[3];
int orderNum = 0;
int quantity=0;
Scanner s = new Scanner(System.in);
System.out.println("------------------------------------------");
System.out.println("condensed milk [M3487], $9.50 per can.");
System.out.println("");
System.out.println("Distilled Water [W3876], $3.00 a bottle.");
System.out.println("");
System.out.println("Pack Rice [R9983], $12.75 for 5lbs.");
System.out.println("------------------------------------------");
do{
System.out.println("Please enter order number (0 to stop)");
pCode[orderNum] = s.nextLine();
orderNum++;
if(pCode[orderNum] == ("M3487")){
System.out.println("condensed milk $9.50");
System.out.println("Enter Quantity");
quantity = s.nextInt();
}//close if statement
if(answer == 0){
break;
}//close if
}while(true);//close while loop
}//close main method
}//close class
System.out.println("Please enter order number (0 to stop)");
pCode[orderNum] = s.nextLine();
orderNum++; //This is the problem
if(pCode[orderNum] == ("M3487"))//It will not work because you have change the index
Remove
orderNum++;
because You have inserted string at pCode[0] zero index and searching at pCode[1].
Change you code to:
System.out.println("Please enter order number (0 to stop)");
pCode[orderNum] = s.nextLine();
if(pCode[orderNum].equals("M3487")){
System.out.println("condensed milk $9.50");
System.out.println("Enter Quantity");
quantity = s.nextInt();
}
orderNum++;
newbie here. So i'm testing out arrays, it's the next topic in the tutorial that i have been reading. I made a simple program to specify how many numbers to get or to input. The problem is on the getArray() method, i can't seem to display it. It's giving me an exception in thread error. Any help and advice is much appreciated. :) Sorry for the newbie question. :))
So here's the code.
import java.util.Scanner;
public class ArrayNumbers {
Scanner input = new Scanner(System.in);
int totalNum, counter, count = 0, display;
double arrayNum[];
public void setArrayNum() {
System.out.print("How many numbers?: ");
totalNum = input.nextInt();
double arrayNum[] = new double[totalNum];
for (counter = 0 ; counter < arrayNum.length ; counter++) {
System.out.print("Num "+(count = counter + 1)+": ");
arrayNum[counter] = input.nextInt();
}
}
public void getArray() {
System.out.print("What number to display?: ");
display = input.nextInt();
System.out.print(arrayNum[display]);
}
}
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Numbers NumbersObject = new Numbers();
ArrayNumbers ArrayNumbersObject = new ArrayNumbers();
String name;
int choice;
System.out.print("Enter name: ");
name = input.nextLine();
System.out.println("Menu");
System.out.println("1. Math Operations");
System.out.println("2. Grade Computation");
System.out.println("3. Counting Numbers");
System.out.println("4. Array Numbers");
System.out.print("Enter choice: ");
choice = input.nextInt();
switch(choice) {
case 1:
System.out.println("Choose Operation");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.print("Enter choice: ");
choice = input.nextInt();
NumbersObject.setNum();
if (choice == 1)
System.out.println("The answers is "+(NumbersObject.getNum1() + NumbersObject.getNum2()));
else if (choice == 2)
System.out.println("The answers is "+(NumbersObject.getNum1() - NumbersObject.getNum2()));
else if (choice == 3)
System.out.println("The answers is "+(NumbersObject.getNum1() * NumbersObject.getNum2()));
else if (choice == 4)
System.out.println("The answers is "+(NumbersObject.getNum1() / NumbersObject.getNum2()));
else
System.out.print("Invalid Input!");
break;
case 2:
NumbersObject.setNum();
System.out.println("Your average grade is "+((NumbersObject.getNum2() + NumbersObject.getNum2()) / 2));
break;
case 3:
System.out.println("Welcome to Counting Numbers!");
System.out.println("Enter 2 numbers to start and end!");
NumbersObject.setNum();
for (int counter = (int) NumbersObject.getNum1() ; counter <= NumbersObject.getNum2() ; counter++) {
System.out.println(counter);
}
System.out.println("End!");
break;
case 4:
ArrayNumbersObject.setArrayNum();
ArrayNumbersObject.getArray();
break;
default:
System.out.println("Mr/Ms "+name+" you entered an Invalid Choice!");
break;
}//end of switch
}// end of main
}// end of class
Sorry about that, for not including the main.
And here's the error:
Exception in thread "main" java.lang.NullPointerException
at ArrayNumbers.getArray(ArrayNumbers.java:23)
at MainProgram.main(MainProgram.java:67)
Guys, the only i problem i have is in the getArray()
It asks for what number in the array i want to see but when i input it, it gives an exception in the thread error. The only problem is how am i going to display the array[number i specified]? Sorry for the newbie questions.
It throws an exception because you create an array of size display and you try to print the element at the display position but arrays are 0 base indexed in Java.
This figure should be useful :
So imagine that display = 10 :
double arrayNum[] = new double[display]; //create an array that can holds 10 elements
System.out.print(arrayNum[display]); //try to access at the 10th element of the array but it doesn't exists !
You don't have to create a new array because you want to display the number in the arrayNum you created in your class.
public void getArray() {
System.out.print("What number to display?: ");
display = input.nextInt();
System.out.print(arrayNum[display]);
}
Also you need to check if display is in the correct bounds range [0,...,displayNum.length-1] before trying to access its elements.
Edit :
In setArrayNum() replace double arrayNum[] = new double[totalNum]; by arrayNum = new double[totalNum];
Arrays are 0-based. So if you create an array of size display you can access indexes 0..display-1
You are creating local array double arrayNum[] = new double[display]; within getArray() method.
You need to remove double arrayNum[] = new double[display]; from getArray() method.
After that your method like below.
public void getArray() {
System.out.print("What number to display?: ");
display = input.nextInt();
if(display >0 && display <=arrayNum.length){
System.out.print(arrayNum[display-1]);
}else{
System.out.print(display + " is out of range");
}
}