How do I set the conditional statement in this program? - java

So this code asks for a name and a number 1-20, but if you put in a number over 20 or below 1 the program still runs and I know I need a conditional statement right around figuring out the amount for "ano" to stop and re-ask the statement and re-run the segment but I don't know how to implement it into the code.
// library - for interactive input
import java.util.Scanner;
//---------------------------------
// program name header
public class feb24a
{
//--------FUNCTION CODING ---------------
// FUNCTION HEADER
public static void seeit(String msg, String aname, int ano)
{
// statement to accomplish the task of this function
System.out.print("\n The message is " + msg + "\t" + "Name is:" + aname + "\t" + "number is: " + ano);
// return statement without a variable name because it is a void
return;
}
//------------------- MAIN MODULE CODING TO CALL FUNCTIONS ----------------
// Main module header
public static void main (String[] args)
{
String msg, aname;
int ano, again, a, b;
msg = "Hello";
a = 1;
b = 20;
//Loop control variable
again = 2;
while(again == 2)
{
System.out.print("\n enter NAME: ");
Scanner username = new Scanner(System.in);
aname = username.nextLine();
System.out.print("\n enter number 1-20: ");
Scanner userno = new Scanner(System.in);
ano = userno.nextInt();
seeit(msg, aname, ano);
//ask user if they want to do it again, 2 for yes any other for no
System.out.print("\n do you want to do this again? 2 for yes ");
Scanner useragain = new Scanner(System.in);
again = useragain.nextInt();
} //terminate the while loop
}
}

Replace your while loop with this:
Scanner scanner = new Scanner(System.in);
while (again == 2) {
ano = 0;
System.out.print("\n enter NAME: ");
aname = scanner.nextLine();
while (ano < 1 || ano > 20) {
System.out.print("\n enter number 1-20: ");
ano = scanner.nextInt();
}
seeit(msg, aname, ano);
System.out.print("\n do you want to do this again? 2 for yes ");
again = scanner.nextInt();
}

Try to surround your ano = userno.nextInt() in a while loop. (i.e., while(ano < 1 || ano > 20)) and put a prompt inside that while loop. That way, it will keep reading a new number until it finally no longer fulfills the while loop and will break out.

Related

adding values to an array using counter

I've been learning java for the last 1.5 month. Now the instructor has asked us to create a program that take the name and phone number (but in a method) from the user until the user enters "E". The program should then print all the information stored in the all the arrays.
The program has a main menu and the user will enter "1" to create an account (name and phone number) and then the main menu appears again and the user create another account and so on and so forth... until he chooses another option from the menu or enter "E" to exist and print the summary for all the accounts.
My problem is that I tried to create a counter as a references to each account spot in the arrays(index in array); so after each time the user enters a name and a number the counter add 1 and the arrays index add 1 and moves to the next spot… but that didn't work.
I didn't complete the code, stopped at choice 1 to test the create account method
public static void addDonor(String[] a1, String[] a2, char[] a3, int[] a4, int [] a5){
Scanner input = new Scanner(System.in);
System.out.print(" Enter the name (first and last):" + " ");
String name = input.nextLine();
System.out.print(" Enter Mobile No.:" + " ");
String phone = input.next();
if (phone.length() < 10 && phone.startsWith("0") == false){
while (true){
System.out.println("Wrong Mobile NO... try again!");
System.out.print(" Enter Mobile No.:" + " ");
phone = input.next();
if (phone.length() > 10 || phone.startsWith("0") == true)
break;
}
}
System.out.print(" Enter Blood Group Type (A, B or O):" + " ");
char blood = input.next().charAt(0);
while (blood != 'a' || blood != 'b' || blood != 'c'){
System.out.println("Wrong Blood Group Type... try again!");
System.out.println(" Enter Blood Group Type (A, B or O):" + " ");
blood = input.next().charAt(0);
if (blood == 'A' || blood == 'B' || blood == 'O')
break;
}
int counter = 0;
a1[counter] = name;
a2[counter] = phone;
a3[counter] = blood;
a4[counter] = 1;
a5[counter] = 1;
counter++;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] Name = new String[20];
String[] Mobile = new String[20];
char[] Blood_Gp = new char[20];
int[] Count_o_Donation = new int[20];
int[] Blood_Stock = new int[20];
while (true){
displayMainMenu();
readAndVerify();
String choice = readAndVerify();
switch (choice){
case "1":
addDonor(Name, Mobile, Blood_Gp, Count_o_Donation, Blood_Stock);
break;
}
if (choice.equals("e"))
break;
}
System.out.println(Name[0]);
System.out.println(Name[1]);
}
The problem is thar you are creating the variable index inside the addDonor method. So everytime the method is invoked a new variable with value 0 is going to be created, that's why it's not moving. You should create the varible outside the method and pass it as parameter.
Something like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] Name = new String[20];
String[] Mobile = new String[20];
char[] Blood_Gp = new char[20];
int[] Count_o_Donation = new int[20];
int[] Blood_Stock = new int[20];
int index = 0;
while (true){
displayMainMenu();
readAndVerify();
String choice = readAndVerify();
switch (choice){
case "1":
addDonor(Name, Mobile, Blood_Gp, Count_o_Donation, Blood_Stock, index);
index++
break;
}
if (choice.equals("e"))
break;
}
System.out.println(Name[0]);
System.out.println(Name[1]);
}
public static void addDonor(String[] a1, String[] a2, char[] a3, int[] a4, int [] a5), int index{
Scanner input = new Scanner(System.in);
System.out.print(" Enter the name (first and last):" + " ");
String name = input.nextLine();
System.out.print(" Enter Mobile No.:" + " ");
String phone = input.next();
if (phone.length() < 10 && phone.startsWith("0") == false){
while (true){
System.out.println("Wrong Mobile NO... try again!");
System.out.print(" Enter Mobile No.:" + " ");
phone = input.next();
if (phone.length() > 10 || phone.startsWith("0") == true)
break;
}
}
System.out.print(" Enter Blood Group Type (A, B or O):" + " ");
char blood = input.next().charAt(0);
while (blood != 'a' || blood != 'b' || blood != 'c'){
System.out.println("Wrong Blood Group Type... try again!");
System.out.println(" Enter Blood Group Type (A, B or O):" + " ");
blood = input.next().charAt(0);
if (blood == 'A' || blood == 'B' || blood == 'O')
break;
}
a1[index] = name;
a2[index] = phone;
a3[index] = blood;
a4[index] = 1;
a5[index] = 1;
This isn't really a java question as much as it is a debug question. Your counter is local to the method it is in, so every time the method gets called the counter gets reset.
A variable has a scope. The scope of a variable depends on where you define it. Inside a method block (or inside the parameter section) a variable will live as long as the method block. If defined inside a class as non-static it will live as long as the instance. If defined as static inside a class it will live as long as the class (most of the time this means forever)
In your case you have 2 options: Either you make the variable static, define it outside of your addDonor method and pass it down into the addDonor method by value (so you cannot increment it inside addDonor, do this whereever you call addDonor).
If you go with the static variable then your code remains unchanged. Static variables generally are defined at the top of the class.
If you go with the passing variable down into addDonor then the main method becomes responsible for keeping and incrementing the counter variable. Make sure it only gets incremented on a succesful iteration.
There are other things you can do but they need you to know about Objects.
There are many mistakes here.
First of you should really gather all the information you need in a class. That way you could easily store it all in one array.
public class donor{
String name;
String mobile
...
}
Secondly since you don't know how many inputs you are getting and array is really a stupid way of storing it. If you use a list you can simply do:
List<Donor> donors = new ArrayList<>();
donors.add(donor);
If you need to use an array you could try to use a counter. I would probably do it something like this:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String[] name = new String[20];
String[] mobile = new String[20];
char[] bloodGroup = new char[20];
int[] countODonation = new int[20];
int[] bloodStock = new int[20];
int counter = 0;
boolean continue = true;
while (continue){
displayMainMenu();
String choice = readAndVerify();
switch (choice){
case "1":
name[counter] = readName();
...
counter++;
break;
}
if (choice.equals("e"))
continue = false;
}
}
But once again you should really use a class for the donor stuff. And a list.

Java iterate through array [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I am trying to write a java program with 2 arrays 1 for name (String) and the other representing age (integer) the program should iterate and ask for a max of 10 names and ages of each, then display all array items as well as max and min ages of each, or unless the user enters 'done' or 'DONE' mid-way through.
I have the following code although struggling to loop around and ask user for names and ages x10.
Any suggestions?
Thank you.
import java.util.Scanner;
public class AgeName {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int numTried = 1;
int ageTried = 1;
boolean stop = false;
String name = "";
String[] num = new String[10];
int[] age = new int[10];
while(numTried <= 10 && ageTried <=10 && !stop){
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
if(name.toUpperCase().equals("DONE")){
stop = true;
}else{
num[numTried - 1] = name;
age[ageTried -1] = userAge;
}
numTried ++;
ageTried ++;
}
for(String output : num){
if(!(output == null)){
System.out.print(output + "," );
}
}
input.close();
}
}
You can use a Map<String,Integer>:
HashMap<String, Integer> map = new HashMap<String, Integer>();
String[] num = new String[10];
for (int i = 0; i < 10; i++) {
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
num[i] = name;
map.put(name, userAge);
}
for (String output : num) {
if (!(output == null)) {
System.out.print(output + ","+ map.get(output));
}
}
Map as its name suggests allows you to map one object type to another. the .put() method adds a record that contains a pair of String and an integer and maps the string to the int. The String has to be UNIQUE!!
You should ask in any iteration if the user is done. For example you could set a string variable as answer = "NO", and ask the user at the end of any iteration if he is done. If you try this remember to replace stop variable with answer at your iteration block condition.
System.out.println("Are you done: Choose -> YES or NO?");
answer = input.nextLine();
if (answer == "YES")
break;

reading input with Scanner; output is printed twice [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I have following class
import java.util.Scanner;
public class Album{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("How many songs do your CD contain?");
int songs = sc.nextInt();
String[] songNames = new String[songs];
for (int i = 0; i < songs; i++) {
System.out.println("Please enter song nr " + (i+1) + ": ");
songNames[i] = sc.nextLine();
// What is wrong here? (See result for this line of code)
// It is working when I use "sc.next();"
// but then I can't type a song with 2 or more words.
// Takes every word for a new song name.
}
System.out.println();
System.out.println("Your CD contains:");
System.out.println("=================");
System.out.println();
for (int i = 0; i < songNames.length; i++) {
System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
}
}
}
I can't type song name nr 1 because it Always shows first two together.
Like this if I type 3:
How many songs do your CD contain?
3
Please enter song nr 1:
Please enter song nr 2:
Change
int songs = sc.nextInt();
to:
int songs = Integer.parseInt(sc.nextLine().trim());
and it will work fine.
You should not mix usages of nextInt with nextLine.
add sc.nextLine(); after int songs = sc.nextInt();
Once you enter a number and read it using a scanner ( as a number) using sc.nextInt();, the newline character will be present in the input stream which will be read when you do sc.nextLine(). So,to skip(over) it, you need call sc.nextLine() after sc.nextInt();
Add a sc.nextLine() after sc.nextInt() and your code works fine.
The reason is the end of line after you type the nomber of songs.
Either use nextInt or nextLine, I would opt for nextLine:
import java.util.Scanner;
public class Album{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("How many songs do your CD contain?");
int songs = Integer.parseInt(sc.nextLine()); // instead of nextInt()
String[] songNames = new String[songs];
for (int i = 0; i < songs; i++) {
System.out.println("Please enter song nr " + (i+1) + ": ");
songNames[i] = sc.nextLine();
// What is wrong here? (See result for this line of code)
// It is working when I use "sc.next();"
// but then I can't type a song with 2 or more words.
// Takes every word for a new song name.
}
System.out.println();
System.out.println("Your CD contains:");
System.out.println("=================");
System.out.println();
for (int i = 0; i < songNames.length; i++) {
System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
}
}
}
put a sc.nextLine(); after int songs = sc.nextInt();

How to take multiple user inputs using if-else statements in java.

import java.util.Scanner;
public class Assignment6 {
public static void commandList()
{
System.out.println("Command Options------------");
System.out.println("a: Create a new table");
System.out.println("b: Change the row sizes");
System.out.println("c: Change the column sizes");
System.out.println("d: Change the data types");
System.out.println("e: Change the formats");
System.out.println("f: Display the table");
System.out.println("g: Display the log data");
System.out.println("?: Display this menu");
System.out.println("q: Quit the program");
System.out.println("---------------------------");
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Command Options------------");
System.out.println("a: Create a new table");
System.out.println("b: Change the row sizes");
System.out.println("c: Change the column sizes");
System.out.println("d: Change the data types");
System.out.println("e: Change the formats");
System.out.println("f: Display the table");
System.out.println("g: Display the log data");
System.out.println("?: Display this menu");
System.out.println("q: Quit the program");
System.out.println("---------------------------");
String input = "";
System.out.println("Please input a command:");
input = in.nextLine();
do
{
if (input.equals("a"))
{
System.out.println("a [Input three integers to ititialze a table:] ");
int newTable = in.nextInt();
}
else if (input.equals("b"))
{
System.out.println("Change the row sizes");
int newRow = in.nextInt();
}
else if (input.equals("c"))
{
System.out.println("c [Type an integer to update the table column]: ");
int newColumn = in.nextInt();
}
else if (input.equals("d"))
{
System.out.println("d [Type an integer to update the data type]: ");
int newDataType = in.nextInt();
}
else if (input.equals("e"))
{
System.out.println("e [Type and integer to update printf format]: ");
int newPrintf = in.nextInt();
}
else if (input.equals("f"))
{
System.out.println("f [Display the table]");
}
else if (input.equals("g"))
{
System.out.println("g [Display the log data]");
}
else if (input.equals("?"))
{
commandList();
}
else
{
System.out.println("Invalid ***Type ? to get commands***");
}
}
while (!input.equals("q"));
{
}
}
}
I created a menu and I am asking the user to input a letter and the program will show a command option they choose. Right now I have it so if the user inputs "a" then "Input three integers to initialize the table" will print. I need it to then print "Please input a command" next but it just keeps printing "Input three integer to itialize the table" I have been trying different methods for a while now and I have no idea what to do. Any help?
Look at the bottom of your do-while loop:
do
{
if (input.equals("a"))
{
System.out.println("a [Input three integers to ititialze a table:] ");
int newTable = in.nextInt();
}
// … more if-else statements
} while (!input.equals("q"));
It keeps printing that statement because after the if-else statement finishes, the value of input still equals "a" since you haven't changed the value of input.
Perhaps you want the user to enter new input before the while loop checks again.
// … more if-else statements
input = in.nextLine(); // <-- add new user input
} while (!input.equals("q"));
And as Juned Ahsan has already said you need to add more code within that first if statement to print the other commands that you mentioned.
You need to loop to ask for three integers. Better use array to capture the values. Somethign like this:
if (input.equals("a"))
{
System.out.println("a [Input three integers to ititialze a table:] ");
int newTable[] = new int[3];
for (int i = 0; i < 3 ; i++) {
System.out.println("Input " + (i+1) + "table value: ");
newTable[i] = in.nextInt();
}
}
Since depending on the command entered by the user, the number of inputs you accept from the user changes, try using loops inside the if or else conditions. A do while loop will just keep going the same number of times for any of the commands entered. Try something like this:
String input = "";
do {
System.out.println("Please input a command:");
input = in.nextLine();
if (input.equals('a')) {
System.out.println("a [Input three integers to ititialze a table:] ");
int newTable[] = new int[3];
for (int i = 0; i < 3 ; i++) {
System.out.println("Input " + (i+1) + "table value: ");
newTable[i] = in.nextInt();
}
}
else if(input.equals('b')) {
// Accept as many inputs you want for command 'b'
}
} while (!input.equals('q'))
The outer do while loop will ensure that you can accept as many commands from the user till the user enters 'q'.

Using Objects in Method

I am trying to use a menu system that can delete a customer from my array myHotel[], this is built from an object.
if(menu.charAt(0) == 'D')deleteCustomer(myHotel[]);
...
public void deleteCustomer(String myHotel[]){
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Room Number to Delete Customer");
roomNum=input.nextInt();
myHotel[roomNum].setName("e");
}
I get the errors, cannot find symbol?
Here is the Full Code
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int roomNum=0;
Room[] myHotel = new Room[10];
for (int x =0; x<10; x++){
myHotel[x] = new Room();
}
String roomName;
String menu;
do {
System.out.println("Please Select an Option from the Menu:");
System.out.println("Enter V to View all Rooms");
System.out.println("Enter A to Add Customer to Room");
System.out.println("Enter D to Delete Customer from Room");
System.out.println("Enter Q to Quit");
menu=input.next();
//if(menu.charAt(0) == 'V')viewAllRooms();
//if(menu.charAt(0) == 'A')addCustomer();
if(menu.charAt(0) == 'D')deleteCustomer(myHotel[]);
} while (menu.charAt(0) != 'Q');
while (roomNum < 10) {
for (int x = 0; x < 10; x++ )
if (myHotel[x].getName().equals("e"))System.out.println("room " + x + " is empty");
System.out.println("Enter room number (0-9) or 10 to stop:");
roomNum = input.nextInt();
System.out.println("Enter name for room " + roomNum + " :");
roomName = input.next();
myHotel[roomNum].setName(roomName);
for (int x = 0; x < 10; x++) {
//System.out.println("room " + x + " occupied by " + myHotel[x].mainName);
System.out.println("room " + x + " occupied by " + myHotel[x].getName());
}
}
}
public void deleteCustomer(String myHotelRef){
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Room Number to Delete Customer");
int deleteRoom=input.nextInt();
myHotelRef[deleteRoom].setName("e");
}
}
You get multiple errors. What is myHotel[]? roomNum is not defined, etc.
Please use your compiler.
Also: please read https://stackoverflow.com/help/how-to-ask :-)
First you need declare myHotel array and pass it with out [].
deleteCustomer(myHotel);
Second, there is not such a method setName(String name) in String class
myHotel[roomNum].setName("e");// no such a method
Third, you need to declare the roomNum variable like:
int roomNum = input.nextInt();
Your main problem is that you've included [] in your call to deleteCustomer. It should be:
if (menu.charAt(0) == 'D') {
deleteCustomer(myHotel);
}
When you reference an array object as a whole you don't include square brackets. Square brackets are for the declaration, initialisation and for accessing individual elements within the array.
I'd also recommend that you get into the habit of always using curly braces with your if, for and while constructs, as not including them is often the cause of bugs. It also makes it easier to read when you come back to it, and you're clearly indicating to others what should be part of the loop and what shouldn't.

Categories

Resources