for loop - looping more than its supposed to? - java

public static void choice( String arrayString[], double arrayReal[])
{
int choice;
Scanner sc = new Scanner(System.in);
System.out.println("1.display mark");
System.out.println("2.exit");
choice = sc.nextInt();
while (choice !=2 && choice != 1)
{
System.out.println("invalid input enter again");
choice = sc.nextInt();
}
switch (choice)
{
case 1:
output(arrayString, arrayReal);
break;
case 2:
System.out.println("exiting");
break;
default:
System.out.println("invalid choice choose between 1 and 2");
choice = sc.nextInt();
}
}
public static void output(String arrayString[], double arrayReal[])
{
String name;
Scanner sc = new Scanner(System.in);
for (int i=0;i<arrayString.length;i++)
{
System.out.println(arrayString[i]);
}
System.out.println("enter stident name");
name = sc.nextLine();
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString.equals(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
}
for (int j=0;j<arrayString.length;j++)
{
if (arrayString[j].equals(name))
{
System.out.println("mark of " + arrayString[j] + "is " + arrayReal[j]);
}
}
im trying to validate the student name and if it doesnt equal to any of the names in the array return back to the menu. it does go back to the menu but the problem is after going back to the menu even if i type the correct student name if keps going back to the menu. i thought for loops were supposed to loop set amount of times and pass to the next code?? is that right? also is my approach correct? ive tried putting if else in the last for loop but that didnt end up as i wanted it to as well. any help is appreciated thanks!
EDIT-
thanks for spotting the mistake. fixed !arrayString.equals(name) to !arrayString[k].equals(name) but still the same problem

Your problem ist here:
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString.equals(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
}
You are comparing an Array String[] arrayString with a String name. They are never going to be treated as equal and therefor your choice method is allways called.
Also the whole loop is totally pointless as you never use your loop index k for anything.
You don't need a loop here at all. Instead you can simply convert the String array to a temporary list and check if it contains your input:
if(!Arrays.asList(arrayString).contains(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
Edit:
here a short main Method that can be used for testing:
public static void main(final String[] args) {
final String[] test = { "Mark", "Peter" };
final double[] test2 = { 1, 2 };
choice(test, test2);
}
Input/Output:
OUTPUT: 1.display mark
OUTPUT:2.exit
INPUT: 1
OUTPUT: Mark
OUTPUT: Peter
OUTPUT: enter stident name
INPUT: Mark
OUTPUT: mark of Markis 1.0

The logic at this part, after adding the index, is still wrong:
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString[k].equals(name))
{
System.out.println("invalid name");
...
}
}
this will print "invalid name" for every name in the list that is not the given name. Example: if the first name in the array does not match, you will get a message (and choice called), no matter if the second entry matches.
One way is to search the whole array until you find the name and then act on the result:
boolean found = false;
for (int k=0;k<arrayString.length;k++)
{
if(arrayString[k].equals(name))
{
found = true;
break; // stop searching
}
}
if (!found)
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}

Related

How can I validate user input in Java

I am currently experimenting with Java, trying to get the user to input an integer. If the user doesn't enter an integer I want a message to appear saying "You need to enter an Integer: " with a completely new input field to the original one.
Code:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
int counter = 0;
boolean run = true;
int userInput = 0;
while (run) {
System.out.print("Enter an integer: ");
if (inputScanner.hasNextInt()) {
userInput = inputScanner.nextInt();
} else if (!inputScanner.hasNextInt()) {
while (!inputScanner.hasNextInt()) {
System.out.print("You need to enter an Integer: ");
userInput = inputScanner.nextInt();
}
}
System.out.println(userInput);
if (counter == 6) {
run = false;
}
counter++;
}
}
}
At the moment the code above gives an Exception error ("java.util.InputMismatchException"). I have tried to use a try/catch but this doesn't really work because I want the user to see the second message ("You need to enter an Integer") everytime they don't enter an integer and I don't want it to re-loop around the main run loop for the same reason. I'm sure there is a better way to do this, however I am not sure of it. Any help will be massively appreciated, thanks in advance.
In this case it would make more sense for the Scanner to use hasNextLine and then convert the String to an Integer. If that you could do something like this:
try {
new Integer(inputScanner.hasNextLine);
} catch (Exception e) {
System.out.println(“<error message>”)
}
In place of the if(inputScanner.hasNextInt()) due to the fact that the hasNextInt function will error out if there is not an Integer to be read.

How can I get a multidimensional array to loop with string input?

Basically I'm making a program that reads from a multidimensional array to display it's corresponding information. What I want to do is make it so the while loop will continue to tell me I'm putting in the wrong class ID's until you put in a correct Class ID.
do
{
System.out.println("Please enter the name of your course to display it's information");
name = input.nextLine();
for(int x = 0; x <= classes.length; ++x)
{
if(name.equals(classes[x][0]))
{
i = true;
System.out.println("Course info: " + classes [x][0]);
System.out.println(classes[x][1]);
System.out.println(classes[x][2]);
x = classes.length;
}
else{
System.out.println("Wrong course id");
i = false;
input.next();
}
}
}
while (!(i));
System.out.println("This is the end of the program!");
System.exit(0);
First of all, try to keep good naming conventions. i is bad name for a flag variable. Name it boolean found or something. It will not only help other people read and understand your code, but it will help you in order find the logic you have to use as well.
Now, since you have input.next(); in else part, i guess you want to ask again for user input, until a something is found. So, a name = input.nextLine(); is required again in order to take new input. But in your case the else part can be removed completely and let the do-while do the work.
An example:
public class Classes {
private static final String[][] CLASSES = { { "Maths", "info" }, { "History", "info" }, { "Biology", "info" } };
public static void main(String[] args) {
boolean found = false;
String name;
Scanner input = new Scanner(System.in);
do {
System.out.println("Please enter the name of your course to display it's information");
name = input.nextLine();
for (int i = 0; i < CLASSES.length; i++) {
if (name.equals(CLASSES[i][0])) {
found = true;
System.out.println("Course info: " + CLASSES[i][0]);
System.out.println(CLASSES[i][1]);
// System.out.println(CLASSES[i][2]); //My CLASSES array, does not have 3 columns
break;// exit for loop
}
}
if (!found)
System.out.println("Wrong course id");
} while (!found);
input.close();
System.out.println("This is the end of the program!");
}
}

How to do repeated sequence check

Question: Repeated Sequence Check
The program should enter a string (possibly containing blanks), and determine whether the characters are in
lexicographic order.
For example:
“12AABab” is in order since each character is less than or equal to the one following it (‘1’ < ‘2’, ‘2’ <
‘A’, ‘B’ < ‘a’, etc.) according to the Unicode character sequence.
“abCDef” is out of order, because ‘b’ > ‘C’ (lower-case letters come after upper-case letters in the
Unicode sequence).
If the string is in order, the program should display “The input is in order”; otherwise, it should display
“The input is out of order”
The program should repeat this process until the user enters the string “quit”, regardless of case. It should
not check the sequence of “quit”.
Finally, the program should display “Goodbye”.
Notes:
This program will require nested loops. The inner loop will check the sequence of the input, while
the outer loop will repeat the input and check process.
Be sure to reinitialize all variables at the start of the outer loop.
A string of length 0 or 1 is considered to be in order by definition.
what I could do best is: (I tried with 2 other different methods I could send it too if you like)
package homelab03;
import java.util.Scanner;
public class Quest3deneme3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String whole,remain,d,e;
char h1,h2;
int lenght,b,c,sayac;
//int[] a;
String[] a;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
whole=whole.replaceAll("\\s+","");
lenght=(int)whole.length();
//System.out.println(+lenght);
remain=whole;
sayac=0;
c=0;
b=0;
a= new String[lenght];
//boolean cem = d.compareTo(e);
while(b<lenght)
{
a[b]=remain.substring(b,b+1);
remain=remain.substring(b+1);
System.out.println(a[b]);
d=a[b];
e=a[c];
while(a[b]<a[c] )
{
sayac=sayac+1;
h1=h2;
}
}
if(sayac==lenght)
{
System.out.println("oley");
}
else
{
System.out.println("nooo");
}
}
//a[b]=remain.substring(b,b+1);
//remain=whole.substring(b+1);
//System.out.println(a[b]);
}
note we haven't learned a[b] <= this thing yet but I find it online if the solution won't require that that would be better.
note 2: we haven't learned regex either I think that might be dissalowed (I found some answers with that online but I think I won't get credit for that)
You could check this code. Maybe it will inspire you :)
import java.util.Scanner;
public class howToDoRepeatedSequanceCheck {
public void repeatedTests() {
String whole;
int inputLength,i;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
while(!whole.equals("quit")) {
whole=whole.replaceAll("\\s+","");
inputLength = whole.length();
boolean isInOrder = true;
i = 0;
while(isInOrder && i<inputLength-1 ) {
if(whole.charAt(i)<whole.charAt(i+1)) {
// System.out.println("ok " + whole.charAt(i)+ " < " +whole.charAt(i+1));
}else {
// System.out.println("error");
isInOrder = false;
}
i++;
}
if(isInOrder == true) {
System.out.println("The input is in order");
}else {
System.out.println("The input is out of order");
}
System.out.println();
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
}
System.out.println("Goodbye");
}
}

Java search if a string exists

I am trying to determine if the user entered value already exists in the current array, how to do that?
User entered value to check the variable is
accno and the array to compare to is accnums
This is what i am currently working on
public class Randomtopic {
static BigDecimal[] accbal = new BigDecimal[20];
static Integer[] accnums = new Integer[20];
public static void main(String[] args) {
displayMenu();
}
public static void displayMenu() {
int option, accno;
double accbal;
Scanner sc = new Scanner(System.in);
System.out.println(" Add an account");
System.out.println("Search an account with the given account number");
System.out.print("Enter Your Choice: ");
option = sc.nextInt();
switch (option) {
case 1:
System.out.println("You have choosen to add account");
addAccount();
break;
case 2:
System.out.println("You have choosen to search for an account");
System.out.print("Enter the Account Number: ");
accno = sc.nextInt();
System.out.println(search(accno, accnums));
break;
default:
System.out.println("Please choose an appropriate option as displayed");
}
displayMenu();
}
public static void addAccount() {
//String accno;
int i = 0;
int accno, input;
BigDecimal accbala;
DecimalFormat df = new DecimalFormat("0.00");
//BigDecimal[] accbal= new BigDecimal[20];
Scanner sc = new Scanner(System.in);
//String[] accnums = new String[20];
int j;
System.out.print("Enter the account number: ");
accno = sc.nextInt();
if (String.valueOf(accno).matches("[0-9]{7}")) {
System.out.print("Enter account balance: ");
accbala = sc.nextBigDecimal();
for (j = 0; j < accnums.length; j++) {
if (accnums[j] == null )
break;
else if(accnums[j].equals(accno))
{
System.out.println("Account already exists");
}
}
//System.out.print(j);
if (j == accnums.length) {
System.out.print("Account storage limit has reached.");
} else {
accnums[j] = accno;
accbala = accbala.setScale(2, RoundingMode.HALF_UP);
accbal[j] = accbala;
}
input = accnums[0];
System.out.println("The value: " + input + " witha a balance of " + accbal[0].toString());
} else {
System.out.println("Wrong NRIC");
}
displayMenu();
}
public static String search(int accnum, Integer[] numbers) {
// Integer[] numbers;
//int key;
//numbers = accnums;
// System.out.print("Enter the Account Number: ");
for (int index = 0; index < numbers.length; index++) {
if (numbers[index].equals(accnum)) {
return String.valueOf(index);
// System.out.println("The account number exists in this array index :"+index);//We found it!!!
}
break;
}
return "-1";
}
}
So my problem?
When i enter the accnum for the first time itself i am getting NullPointerException. Tks
When you instantiate or create an array, the values are by default set to null; whenever you iterate over an array of possibly null values, it is required you skip these. For example,
for(loop conditions)
if (numbers[index] != null && (numbers[index].equals(accnum))) {
return String.valueOf(index);
//your text goes here;
}
break;//I suggest you take this line out of your original code. Your for loop will end this once you have iterated through the entire array, or you will automatically break out if you find the value.
}
If you must use an array, then this is the best way to iterate through it. The parenthesis and the && in the if clause prevent you from performing the .equals check if the value of numbers[index] == null - in turn, preventing the null error from being thrown. your only alternative would be to set every value in the numbers[ ] to 0, or some other value, and than skip that value when you iterate. Such would be done with a static final int. However, this is not ideal coding.
Ideally, you should use an ArrayList - you can then not only make this more efficient, but also, much more readable.
Your accnums is filled with null values. Check if they are not null. I suppose your NullPointerException is thrown from search method.
If I understood your code correctly you have a number of accounts with associated balance identified by an account number. In this case I would use a Map instead of fiddling with arrays.
when you run your method search first time, yours array accnums is filled with null value so when you call line if ( numbers[index].equals(accnum)) you are trying call equal method on null object
what you can do is change your accnums from array to list, and then size will depends on number elements, so it wont have fixed size like your arrays
The problem in your code without adding anything in your accnum you are searching.So your accnum contains NULL values.if you change your accnum array into list/hashmap the exception would not arise.

Validate user input against ArrayList

I am having issues with the following part of my code.
when "nn" is entered i get invalid code.
when valid code is entered i get invalid code however this only happens once.
program doesn't seem to work as intended. Please assist.
System.out.println("ENTER CODE (nn to Stop) : ");
ArrayList<Product> list = new ArrayList<Product>();
.
.
.
.
ArrayList<Code> codeList = new ArrayList<Code>();
for (Product product : list) {
System.out.print("CODE : ");
String pcode = scan.next();
if (pcode.equalsIgnoreCase("nn")) {
break;
}
if (!(code.equalsIgnoreCase(product.getCode()))) {
System.out.println("Invalid code, please enter valid code.");
System.out.print("CODE : ");
pcode = scan.next();
}
System.out.print("QUANTITY : ");
int quan = scan.nextInt();
while (quan > 20) {
System.out.println("Purchase of more than 20 items are not allowed, please enter lower amount.");
System.out.print("QUANTITY : ");
quan = scan.nextInt();
}
codeList.add(new Code(pcode, quan));
}
You want continue instead of break.
Also, you should only call code = scan.next() once inside the loop; otherwise you'll skip over some items.
String code = scan.next();
boolean match = false;
for (Product product : list) {
if (code.equalsIgnoreCase(product.getCode())) {
match = true;
break;
}
}
// now only if match is false do you have an invalid product code.
Update:
I still can't get this to work. What I am trying to do is test user
input to make sure that product code exists, if not prompt that the
product code entered is invalid and asks for correct code. I also need
to have the condition to stop order when "nn" is entered. I have tried
while loops, do-while loops etc. i can't seem to get it right. Please
assist. My problem is with writing code for multiple conditions. When
one is working correctly the other isn't.
while (true) {
final String code = scan.next();
if (isExitCode(code)) {
break;
}
if (!isValidCode(code)) {
System.out.println("Invalid code, please enter valid code.");
continue;
}
int quantity = -1;
while (true) {
quantity = scan.nextInt();
if (!isValidQuantity(quantity)) {
System.out.println("bad quantity");
continue;
}
break;
}
// if you've got here, you have a valid code and a valid
// quantity; deal with it as you see fit.
}
Now you just need to write the methods isExitCode(), isValidCode(), and isValidQuantity().

Categories