I am writing a bank account program for my Comp Sci class, and need to search a .txt file for a account number a user enters (which is an int) and then pull out the next row which is the balance. i.e. the user enters the account #12345679 and i need to pull out the balance of it. Below is an example of the txt file
12345678
133.87
12345679
500.00
12345670
123.00
So far I have and I know that i'm going to have to put how to get the balance in the if statment
while (accountTries < 3)
{
System.out.println("Please enter your 8 digit account number");
accountNumber = console.next();
accountLength = accountNumber.length();
while (in.hasNextInt())
{
line = in.hasNextInt();
if (accountLength == 8 && line == accountNumber )
{
accountTries = 3;
}
}
System.out.println("INVALID ACCOUNT NUMBER.");
accountTries++;
}
}//End of while loop
Not sure what you're trying to do... but this doesn't seem right:
line = in.hasNextInt();
Shouldn't you be getting the value here? You're just testing to see if there's anything there, like you did in the "while" condition.
outer: while (accountTries < 3)
{
System.out.println("Please enter your 8 digit account number");
accountNumber = console.next();
accountLength = accountNumber.length();
while (in.hasNextLine())
{
line = in.nextLine();
result = in.nextLine();
if (accountLength == 8 && line.equals(accountNumber))
{
accountTries = 3;
break outer;
}
}
System.out.println("INVALID ACCOUNT NUMBER.");
accountTries++;
}
}//End of while loop
I used a labeled break to get out of the outer while (you can do the same with if statements and a done flag but I'm to lazy to do that here)
You can simply read file to String and split it by line separator(\n or \n\r).
For example :
String fileContent = //read String from file;
String[] elements = fileContent .split("\n");
for(int i =0; i< elements.length; i++){
if(i%2 ==0){
//get account number
}else{
//get balance
}
}
Related
I am attempting to validate multiple scanner inputs with paired If-Else blocks in a single while loop. The behavior that I am interested in achieving is to the current validation If-Statement request the user to re-enter input or move on to the subsequent input / selection blocks.
Right now, I am using the continue keyword which returns to the beginning of the While loop. Would using a do...while loop be better suited for this? Thank you.
while (count < numCars) {
System.out.println("Enter car type");
String name = scanner.next();
if (name.matches(".*\\d")) {
System.out.println("Name entry cannot contain numbers");
continue;
} else {
// re-enter name
}
System.out.println("Enter max speed");
int maxSpeed = scanner.nextInt();
if (maxSpeed == 100 || maxSpeed > 100) {
System.out.println("Max speed is not valid. Please re-enter");
continue;
} else {
// re-enter age
count++;
}
}
The functionality you want for every block can be achieved using while instead of if-else statements. I also structured your code in a nicer/more organized way:
int count = 0, numCars = 3; // Example value
String name;
int maxSpeed;
while (count < numCars) {
System.out.print("Enter car type: ");
name = scanner.next();
scanner.nextLine(); // Cleans the buffer
while (name.matches(".*\\d")) {
System.out.println("Name entry cannot contain numbers.");
System.out.print("Enter car type: ");
name = scanner.next();
scanner.nextLine(); // Cleans the buffer
}
System.out.print("Enter max speed: ");
maxSpeed = scanner.nextInt();
while (maxSpeed >= 100) {
System.out.println("Max speed is not valid. Please re-enter.");
System.out.print("Enter max speed: ");
maxSpeed = scanner.nextInt();
}
count++;
}
I am trying to solve a competitive programming practice set. I am only a beginner so please bear with me.
Here is the problem
The history teacher at your school needs help in grading a True/False test using his designed
scoring technique. Each correct answer is awarded two points, each wrong answer gets one
point deducted, and no answer gets a zero.
Your task is to help the teacher automate this task.
Input
The first entry in the file contains answers to the test in the form:
TFFTFTFTFFFTTTTFTFTF
The next line is the number test cases, i.e. number of students who took the test.
Every other entry in the file is the student ID, followed by a blank, followed by the student's
responses. For example, the entry:
S2013-1-1003 TFTFTFTT TFTFTFFTTFT
indicates that the student ID is S2013-1-1003 and the answer to question 1 is True, the
answer to question 2 is False, and so on. This student did not answer question 9. The exam, in
this example, has 20 questions.
Output
The output should be the student's ID, followed by the answers, followed by the test score,
followed by the test grade. Assume the following grade scale: 90%-100%, A; 80%-89.99%, B;
70%-79.99%, C; 60%-69.99%, D; and 0%-59.99%, F.
Sample Input
TTTTTFFFFF
3
S2013-1-2345 TTTTTFFFFF
S2013-1-1266 TFTFTFTFTF
S2012-2-0006 T T TF F F
Sample Output
S2013-1-2345 TTTTTFFFFF 20 A
S2013-1-1266 TFTFTFTFTF 8 F
S2012-2-0006 T T TF F F 12 D
*/
My code :
public class Score {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
//input answer to the test
String correctAnswer = sc.nextLine();
//input number of test cases
int numberOfStudents = sc.nextInt();
String studentID[] = new String[numberOfStudents];
String studentAnswer[] = new String[numberOfStudents];
int studentScore[] = new int[numberOfStudents];
char studentGrade[] = new char[numberOfStudents];
//ask user to input data
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter student details");
studentID[i] = sc.nextLine();
studentAnswer[i] = sc.nextLine();
}//end of first for loop
//checks whether the student has the correct score
for(int y = 0; y < correctAnswer.length(); y++) {
if(studentAnswer[y].charAt(y) == correctAnswer.charAt(y)) {
studentScore[y]++;
}//end of if
}//end of for
for(int y = 0; y < numberOfStudents; y ++) {
double percentage = (studentScore[y] / correctAnswer.length()) * 100 ;
//check the letter grade of the student
if(percentage >= 90) {
studentGrade[y] = 'A';
}//end of first if
else if(percentage >= 80 && percentage <= 89) {
studentGrade[y] = 'B';
}//end first else if
else if(percentage >= 70 && percentage <= 79) {
studentGrade[y] = 'C';
}//end of second else if
else if(percentage >= 60 && percentage <= 69) {
studentGrade[y] = 'D';
}//end of third else if
else {
studentGrade[y] = 'F';
}//end of last else
}//end of for
//close the scanner to avoid any memory leaks
//display the score
for(int i = 0; i < numberOfStudents; i++) {
System.out.printf("%d\t%d\t%d\t%d", studentID[i], studentAnswer[i], studentScore[i], studentGrade[i]);
}//end of first for
}//end of main
}//end of class
The program compiles and all however once I input my test data, i received an outofBounders error from my compiler. Then I realized that I had made a mistake in this code
System.out.println("Enter student details");
studentID[i] = sc.nextLine();
studentAnswer[i] = sc.nextLine();
}//end of first for loop
if StudentID and studentAnswer is an integer then I can seperate them by using space and enter my data in one line. However I forgot that when I use space as a seperator, it is not seperated as space is still considered a string. My main question here is how do I ask the user to input his student ID and his answer in one line seperated by a string so that I can store then into my arrays such as studentID array and studentAnswer array.
The format specifier that you use for display the score is wrong! you can can change it as below:
//display the score
for(int i = 0; i < numberOfStudents; i++) {
System.out.printf("%s\t%s\t%d\t%s", studentID[i], studentAnswer[i], studentScore[i], studentGrade[i])
}//end of first for
You are taking input using sc.nextLine(). What does nextLine() do is, it reads all character from input buffer until \n or newline character is found.
So you can ask user to give input something like this way:
StudentID \n studentAnswer
Another way you can modify your input taking array as like as this:
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter student details");
String line = sc.nextLine();
char[] chars = line.toCharArray();
String fs = "";
String sc = "";
boolean flag = false;
for(int j=0;j<chars.length;j++){
if(chars[j]==' ') {
flag = true;
continue;
}
if(flag ==false) fs += chars[j];
else sc += chars[j];
}
studentID[i] = fs;
studentAnswer[i] = sc;
}
I want to make it so that a user entering the wrong data type as figureNumber will see a message from me saying "Please enter an integer" instead of the normal error message, and will be given another chance to enter an integer. I started out trying to use try and catch, but I couldn't get it to work.
Sorry if this is a dumb question. It's my second week of an intro to java class.
import java. util.*;
public class Grades {
public static void main(String args []) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Please enter an integer: ");
int grade = stdin.nextInt();
method2 ();
if (grade % 2 == 0) {
grade -= 1;
}
for(int i = 1; i <=(grade/2); i++) {
method1 ();
method3 ();
}
}
}
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
while (!stdin.hasNextInt()) {
System.out.print("That's not a number! Please enter a number: ");
stdin.next();
}
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for (int i = 1; i <= (figureNumber / 2); i++) {
whale();
human();
}
}
You need to check the input. The hasNextInt() method is true if the input is an integer. So this while loop asks the user to enter a number until the input is a number. Calling next() method is important because it will remove the previous wrong input from the Scanner.
Scanner stdin = new Scanner(System.in);
try {
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for(int i = 1; i <=(figureNumber/2); i++) {
whale();
human();
}
}
catch (InputMismatchException e) {
System.out.print("Input must be an integer");
}
You probably want to do something like this. Don't forget to add import java.util.*; at the beginning of .java file.
You want something in the form:
Ask for input
If input incorrect, say so and go to step 1.
A good choice is:
Integer num = null; // define scope outside the loop
System.out.println("Please enter a number:"); // opening output, done once
do {
String str = scanner.nextLine(); // read anything
if (str.matches("[0-9]+")) // if it's all digits
num = Integer.parseInt(str);
else
System.out.println("That is not a number. Please try again:");
} while (num == null);
// if you get to here, num is a number for sure
A do while is a good choice because you always at least one iteration.
It's important to read the whole line as a String. If you try to read an int and one isn't there the call will explode.
You can actually test the value before you assign it. You don't need to do any matching.
...
int figureNumber = -1;
while (figureNumber < 0) {
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
if (stdin.hasNextInt()){
figureNumber = stdin.nextInt(); //will loop again if <0
} else {
std.next(); //discard the token
System.out.println("Hey! That wasn't an integer! Try again!");
}
}
...
I am trying to validate my code by error checking. I want to make sure the integer people enter does not contain a letter or more.
Here is my code. I am supposed to solve this problem using a one dimensional array. I got the code working but I am having problems with adding the error checking in.
Any help would be appreciated. Thanks
public void getNumbers() {
Scanner keyboard = new Scanner(System.in);
int array[] = new int[5];
int count = 0;
int entered = 0;
int k = -1;
while (entered < array.length) {
System.out.print("Enter a number ");
int number = keyboard.nextInt();
if (10 <= number && number <= 100) {
boolean containsNumber = false;
entered++;
for (int i = 0; i < count; i++) {
if (number == array[i]) // i Or j
{
containsNumber = true;
}
}
if (!containsNumber) {
array[count] = number;
count++;
} else {
System.out.println(number + " has already been entered");
}
} else {
System.out.println("number must be between 10 and 100");
}
//what does %d do?
for (int j = 0; j < count; j++) {
System.out.printf("%d ", array[j]);
}
System.out.println();
}
}
}
I'm assuming that you would want your program to ask the user to re-enter a number if they do not input a number the first time. In this scenario you might want to try something along the lines of this:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
while(!sc.hasNextInt()) {
//print some error statement
sc.nextLine();
}
int number = sc.nextInt();
System.out.println("Number is: " + number); // to show the value of number
// continue using number however you wish
Since hasNextInt() returns a boolean determining whether or not the input is an Integer, the program will never leave the while-loop until the program can confirm that the user has entered an integer.
keyboard.nextInt() will throw a InputMismatchException if you input a String.
If you want to check whether Scanner has an integer to read, you can use keyboard.hasNextInt().
Alternatively, you can read the input as
String s = keyboard.next() which will take the input as a String, and then use s.matches(".*\\d+.*") to detect whether or not it is an integer.
UPDATE: To answer questions -
keyboard.hasNextInt() will return a boolean. So for example, after System.out.print("Enter a number"), you could have an if statement checking to see if keyboard can receive numerical input, ie. if(keyboard.hasNextInt). If this is true, that means the user has entered numerical input, and you could continue with sayingint number = keyboard.nextInt(). If it is false, you would know that the user input is non-numerical.
im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 1; i >= 1; i--) {
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax < scores[j]) {
currentMax = scores[j];
currentMaxIndex = j;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}