问题
This program asks the user to input a number and then brings back the details from an list. how do I do this?
do {
Scanner in = new Scanner(System.in);
System.out.println("Enter Number <terminated by 1>");
} while (!input.equals("-1"));
System.out.println("Session Over");
} catch (Exception e) {
System.out.println(e);
}
}
}
output:
Enter Number <terminated by 1>
123456
Person Number: 12
回答1:
while (input != -1);
would be the right way to compare two integer values.
回答2:
In java you can't test variables in do-while loop when variable is inside loop:
do {
int i = 10;
} while (i > 5);
will not compile.
Also, int input;
doesn't have equals
method as int
type is primitive.
回答3:
Pro Tip: use an IDE.
Your code is incorrect for at least two reasons:
- your
int input
is defined inside thedo
block, so it is not visible after it closes - you use
.equals
on a primitive type
Correct your code as follows:
public class Client {
public static void main(String[] arg) {
Client c = new Client();
c.run();
}
private void run() {
StudentData p = new StudentData();
List<StudentDetailsType> personDetailsList = (List<StudentDetailsType>) p.getList();
// input defined outside the do block so it is visible in while clause
int input;
// declare the scanner just one time here, so it will be closed automatically as the try/catch block ends
try(Scanner in = new Scanner(System.in)) {
do {
System.out.println("Enter 6 digit Student Number <terminated by -1>");
input = in.nextInt();
for (StudentDetailsType q : personDetailsList) {
if (q.getStudentNumber() == input) {
System.out.println("Student Number: " + q.getStudentNumber() + "\n" + "Student Name: "
+ q.getStudentName() + "\n" + "Result 1: " + q.getResult1() + "\n" + "Result 2: "
+ q.getResult2() + "\n" + "Result 3: " + q.getResult3());
break;
}
}
} while (input != -1); // use an int comparison (!= that means not equals)
System.out.println("Session Over");
} catch (Exception e) {
System.out.println(e);
}
}
}
回答4:
First remove the Scanner initialization from the loop and put it in the try block, as Pshemo pointed out.
try {
Scanner in = new Scanner(System.in);
do {
yada yada yada
}
Then try wrapping your negation in your while loop as in:
while (!(input.equals("-1")));
来源:https://stackoverflow.com/questions/35992464/java-do-while-termination