Java Programming String Array Trouble - java

import java.util.Scanner;
public class GradePointAverage {
public static void main(String[] args) {
Scanner peace = new Scanner(System.in);
System.out.print("How many subjects do you want to enter?: ");
int a=peace.nextInt();
String[] b = new String[a];
for(int i=0;i<a;i++) {
b[i]="";
System.out.print("Enter Subject No "+(i+1)+" ");
String c=peace.next();
}
for(i=0;i<b.length;i++) {
System.out.print(b[i]);
}
}
}
Greetings. :)
We have a programming experiment and well I was stuck in this part. I need to ask the user how many subjects he wants to enter and ask the user to input the subjects. I think I already entered the subjects on the array but when i want to see the content of the array it won't give me my desired output, the subjects i entered won't appear. Please help, I'm new here on this site and it's my first time to ask a question on a forum like this. Hoping that someone would reply. Thanks.

You never put the subject into the array.
import java.util.Scanner;
public class GradePointAverage
{
public static void main(String[] args)
{
int i;
Scanner peace=new Scanner(System.in);
System.out.print("How many subjects do you want to enter?: ");
int a=peace.nextInt();
String []b=new String [a];
for(i=0;i<a;i++)
{
System.out.print("Enter Subject No "+(i+1)+" ");
b[i]=peace.next();
}
for(i=0;i<b.length;i++)
{
System.out.print(b[i]);
}
}
}

You never assign the Strings to the array.
Change
String c=peace.next();
to
b[i] = peace.next();
In addition, you should probably add some separator (or new line) when printing the array :
public static void main(String[] args)
{
Scanner peace = new Scanner(System.in);
System.out.print("How many subjects do you want to enter?: ");
int a = peace.nextInt();
String[] b = new String[a];
for(int i = 0; i < a; i++) {
System.out.print("Enter Subject No " + (i + 1) + " ");
b[i] = peace.next();
}
for(i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
}
}

import java.util.Scanner;
public class GradePointAverage
{
public static double processAverage(int []SubjectGrades,int SubjectsNumber)
{
double sum=0;
double Ave=0;
for(int i=0;i<SubjectGrades.length;i++)
{
sum=SubjectGrades[i]+sum;
}
Ave=sum/SubjectsNumber;
return Ave;
}
public static int processNumericalValue(double Ave)
{
int Numeral;
if(Ave>=98.0&&Ave<100.0)
{
Numeral=4;
}
else if(Ave>=90.0&&Ave<98.0)
{
Numeral=3;
}
else if(Ave>=80.0&&Ave<90.0)
{
Numeral=2;
}
else if(Ave>=75.0&&Ave<80.0)
{
Numeral=1;
}
else
{
Numeral=0;
}
return Numeral;
}
public static void processLetterGrade(int Numeral)
{
if(Numeral==4)
{
System.out.println("Congratulations!");
}
else if(Numeral==3)
{
System.out.println("Your Letter Grade is B!");
}
else if(Numeral==2)
{
System.out.println("Your Letter Grade is C!");
}
else if(Numeral==1)
{
System.out.println("Your Letter Grade is D!");
}
else
{
System.out.println("You Failed!");
}
}
public static void main(String[] args)
{
double Ave=0;
Scanner peace=new Scanner(System.in);
System.out.print("How many subjects do you want to enter?: ");
int SubjectsNumber=peace.nextInt();
int []SubjectGrades=new int [SubjectsNumber];
String []Subjects=new String [SubjectsNumber];
for(int i=0;i<SubjectsNumber;i++)
{
Subjects[i]="";
System.out.print("Enter Subject No "+(i+1)+": ");
Subjects[i]=peace.next();
System.out.println("What is your grade in "+Subjects[i]+": ");
SubjectGrades[i]=peace.nextInt();
}
int Numeral;
Ave=processAverage(SubjectGrades,SubjectsNumber);
System.out.println("Your General Average is: "+Ave);
Numeral=processNumericalValue(Ave);
System.out.println("Numerical Value is: "+Numeral);
processLetterGrade(Numeral);
}
}

Related

How do you connect a single scanner to two arrays?

Basically, I'm trying to ask the user's input and the input should store in two arrays using a single scanner. Using two would ask the user twice and that would be impractical. The code looks like this
int record = 0;
Scanner midOrFinal = new Scanner(System.in);
Scanner scansubjects = new Scanner(System.in);
Scanner scangrades = new Scanner(System.in);
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
record = midOrFinal.nextInt();
int midterm[] = new int[8];
int grades[] = new int[8];
{
if ( record == 1 )
System.out.println("Enter 8 subjects and their corresponding grades:");
System.out.println();
int i = 0;
for( i = 0; i < 8; i++ )
{
System.out.println(subjects[i]);
System.out.print("Enter Grade: ");
grades[i] = scangrades.nextInt();
if( i == ( subjects.length) )
System.out.println();
}
System.out.println("Enter Grade Successful");
}
If the user chooses option 1, the user will be given some subjects in an array (which I didn't include) and asked to input the grades. The input shall then proceed to the midterm OR finalterm array but I can't seem to do it by using one scanner.
If there are better ideas than my proposed idea, then please share. I'm still very new in Java and my first time using stackoverflow. Thanks!
Break out the grade collection into a new function, and pass along the array you want to collect the grades into.
public static void main(String[] args) throws IOException {
int gradeType = 0;
// Use a single scanner for all input
Scanner aScanner = new Scanner(System.in);
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
gradeType = aScanner.nextInt();
String[] subjects = { "Subject A", "Subject B" };
int[] midtermGrades = new int[subjects.length];
int[] finalGrades = new int[subjects.length];
int[] gradesToCollect;
// Use gradesToCollect to reference the array you want to
// collect into.
//
// Alternatively, we could call collectGrades() in both the if/else
// condition
if (gradeType == 1) {
gradesToCollect = midtermGrades;
} else {
gradesToCollect = finalGrades;
}
collectGrades(subjects, gradesToCollect, aScanner);
System.out.println("\n\nThese are the collected grades");
System.out.println("Mid Final");
for (int i = 0; i < subjects.length; i++) {
System.out.format("%3d %3d\n", midtermGrades[i], finalGrades[i]);
}
}
// Collect a grade for each subject into the given grades array.
public static void collectGrades(final String[] subjects, final int[] grades, Scanner scn) {
System.out.format("Enter %s subjects and their corresponding grades:",
subjects.length);
System.out.println();
for (int i = 0; i < subjects.length; i++) {
System.out.format("Enter Grade for %s : ", subjects[i]);
grades[i] = scn.nextInt();
if (i == (subjects.length))
System.out.println();
}
System.out.println("Enter Grade Successful");
}
class Main {
public static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
in.useDelimiter("\r?\n");
Student student = new Student();
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
int record = in.nextInt();
if (record == 1) {
student.setTerm(TermType.MID);
System.out.println("Enter 8 subjects and their corresponding grades:");
System.out.println("Enter Subject and grades space separated. Example - \nMaths 79");
System.out.println();
for (int i = 0; i < 8; i++) {
System.out.println("Enter Subject " + (i + 1) + " details");
String subjectAndGrade = in.next();
int index = subjectAndGrade.lastIndexOf(" ");
String subject = subjectAndGrade.substring(0, index);
int grade = Integer.parseInt(subjectAndGrade.substring(index + 1));
student.getSubjects().add(new Subject(grade, subject));
}
System.out.println("Enter Grade Successful");
System.out.println("========================================================");
System.out.println("Details: ");
System.out.println("Term Type " + student.getTerm());
for(int i = 0; i< student.getSubjects().size(); i++) {
System.out.println("Subject: " + student.getSubjects().get(i).getSubjectName() + ", Grade: " + student.getSubjects().get(i).getGradeScore());
}
}
}
}
class Student {
private List<Subject> subjects = new ArrayList<>();
private TermType term;
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
public TermType getTerm() {
return term;
}
public void setTerm(TermType term) {
this.term = term;
}
}
class Subject {
private int gradeScore;
private String subjectName;
public Subject(int gradeScore, String subjectName) {
this.gradeScore = gradeScore;
this.subjectName = subjectName;
}
public double getGradeScore() {
return gradeScore;
}
public void setGradeScore(int gradeScore) {
this.gradeScore = gradeScore;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
}
scanners work by separating the input into a sequence of 'tokens' and 'delimiters'. Out of the box, 'one or more whitespace characters' is the delimiter.

Why won't my array pass to the other class?

I have looked at similar examples or other programs that call array from another class and it seems like I have done it the correct way but I am still getting errors.
This is where the arrarys are stored:
import java.util.Scanner;
public class DriverProgram {
public static int[] IDs = new int[10];
public static String[] names = new String[10];
public static double[] grades = new double[10];
public static int i = 0;
static Student call = new Student();
public static void main(String[] args){
call = new Student();
Scanner command = new Scanner(System.in);
System.out.println("Please Enter a command(i, r, s, or d): ");
while(command.hasNext()){
char command1 = command.next().charAt(0);
if(command1 == 'i'){
call.AddToArray(IDs[], names[] , grades[], i);
}else if(command1 == 'r'){
call.RemoveFromArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 's'){
call.SortArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'd'){
call.DisplayArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'z') {
break;
}
else System.out.println("Invalid command enter a valid command next time.");
System.out.println("Please Enter a command(i, r, s, or d) or z to finish: ");
}
}
And this is what I am tryign to call the arrays to:
import java.util.Scanner;
public class Student {
public static void AddToArray(int[] IDs, String[] names, double[] grades, int i) {
if (i >= 10) {
System.out.println("You have already inputted 10 students please delete one first.");
} else {
Scanner readin = new Scanner(System.in);
Scanner readinname = new Scanner(System.in);
Scanner readingrade = new Scanner(System.in);
System.out.println("Please enter student ID: ");
IDs[i] = readin.nextInt();
System.out.println("Please enter student name: ");
names[i] = readinname.nextLine();
System.out.println("Please enter student grade: ");
grades[i] = readingrade.nextDouble();
System.out.println(IDs[i] + " " + names[i] + " " + grades[i]);
i++;
for (int j = 0; j < i; j++) {
if (IDs[j] == IDs[i]) {
System.out.println("This student has already been entered.");
}else{
System.out.println("The student has been added");
break;
}
}
}
}
I am not sure what else I need or what I am missing in order to call those arrays.
call.AddToArray(IDs[], names[] , grades[], i);
should be replaced with
call.AddToArray(IDs, names , grades, i);
P.S. Design notes
Student has only static method, so this is utilitly class and should not allowed an instance creation
call.AddToArray() and others static methods should be called as Student.AddToArray()
array is not correct data strucutre where you can add or remove elements. There're more suitable data structures like List or Map.
It's better to use only one instance of Scanner.
This is how you DriverProgram could look like.
public class DriverProgram {
public static void main(String[] args) {
Map<Integer, Student> students = new HashMap<>();
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.println("Please Enter a command [1-5]:");
System.out.println("1. add new student");
System.out.println("2. remove existed student");
System.out.println("3. sort existed students by grades desc");
System.out.println("4. show existed students");
System.out.println("5. exit");
System.out.print("> ");
int menu = scan.nextInt();
if (menu == 1)
addStudent(scan, students);
else if (menu == 2)
removeStudent(scan, students);
else if (menu == 3)
sortStudents(students);
else if (menu == 4)
showStudents(students);
else if (menu == 5)
break;
System.err.println("Unknown command. Try again");
}
}
private static void addStudent(Scanner scan, Map<Integer, Student> students) {
if (students.size() == 10) {
System.err.println("You have already inputted 10 students please delete one first.");
return;
}
System.out.print("Please enter student ID: ");
int id = scan.nextInt();
if (students.containsKey(id)) {
System.err.println("This student with this id has already been entered.");
return;
}
System.out.print("Please enter student name: ");
String name = scan.nextLine();
System.out.print("Please enter student grade: ");
double grade = scan.nextDouble();
students.put(id, new Student(id, name, grade));
}
private static void removeStudent(Scanner scan, Map<Integer, Student> students) {
}
private static void sortStudents(Map<Integer, Student> students) {
}
private static void showStudents(Map<Integer, Student> students) {
}
public static final class Student {
private final int id;
private final String name;
private final double grade;
public Student(int id, String name, double grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
}
}

Pizza toppings with array

I'm suppose to write a program, Pizza.java, that lets the user enter up to 15 toppings for a pizza, then prints out the toppings in alphabetical order. Also, the toppings should be listed with numbers.
A sample output would be like this
The code I wrote is as follows:
import java.util.*;
public class Pizza {
public static final int numbers=15;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String []toppings;
System.out.println("Enter a toping (or type quit): ");
String a= input.nextLine();
// how do I add String a to the array toppings?
int count=1;
while (!a.equals("quit")&&count<numbers){
System.out.println("Enter a topping (or type quit): ");
a= input.nextLine();
if(!a.equals("quit"))
// how do I add String a to the array toppings?
count++;
}
if(count==numbers)
System.out.println("No more toppings allowed.");
int i=1;
Arrays.sort(toppings); //sorts the array in alphabetical order
while (int i<=count){
System.out.println(i+". "+Arrays.toString(toppings));
}
if(a.equals("quit")){
Arrays.sort(toppings); //sorts the array in alphabetical order
while (int j<=count){
System.out.println(j+". "+Arrays.toString(toppings));
}
}
}
}
How do I complete this code?
Any help would be appreciated
You can make it simpler using List instead of arrays:
import java.util.*;
public class Pizza {
public static final int numbers = 15;
public static void main(String[] args) {
List<String> toppings = new ArrayList<>();
Scanner input = new Scanner(System.in);
int attempt;
for (attempt = 0; attempt < numbers; attempt++) {
System.out.print("Enter topping topping (or type quit): ");
String topping = input.nextLine();
if (topping.equals("quit")) {
break;
}
toppings.add(topping);
}
if (attempt == numbers) {
System.out.println("No more toppings allowed.");
}
Collections.sort(toppings);
for (int position = 0; position < toppings.size(); position++) {
System.out.println((position + 1) + ". " + element);
}
}
}
or using arrays:
import java.util.*;
public class Pizza {
public static final int numbers = 15;
public static void main(String[] args) {
String[] toppings = new String[numbers];
Scanner input = new Scanner(System.in);
int attempt;
for (attempt = 0; attempt < numbers; attempt++) {
System.out.print("Enter topping topping (or type quit): ");
String topping = input.nextLine();
if (topping.equals("quit")) {
break;
}
toppings[attempt] = topping;
}
if (attempt == numbers - 1) {
System.out.println("No more toppings allowed.");
} else {
// Remove "null" elements from "toppings" array
String[] temp = new String[attempt];
for (int position = 0; position < attempt; position++) {
temp[position] = toppings[position];
}
toppings = temp;
}
Arrays.sort(toppings);
for (int position = 0; position < toppings.length; position++) {
String element = toppings[position];
System.out.println((position + 1) + ". " + element);
}
}
}
As you said, you are not allowed to use an ArrayList. Here is my approach on how to do it using a String array. The most interesting part for you should be the Arrays.copyOfRange method, which you could also substitute with a System.arraycopy(...) call.
import java.util.*;
public class Pizza {
private static final int MAX_TOPINGS = 15;
private final String QUIT_KEYWORD = "quit";
public static void main(String[] args) {
new Pizza().printToppings(MAX_TOPINGS);
}
public void printToppings(int maxTopings){
Scanner input = new Scanner(System.in);
String[] toppings = new String[maxTopings];
int count;
for (count = 0; count < maxTopings; count++) {
System.out.printf("Enter topping topping (or type %s): ", QUIT_KEYWORD);
String topping = input.nextLine();
if (topping.toLowerCase().equals(QUIT_KEYWORD)) {
break;
}
toppings[count] = topping;
}
if (count+1 == maxTopings) {
System.out.println("No more toppings allowed.");
} else {
toppings = Arrays.copyOfRange(toppings, 0, count);
}
Arrays.sort(toppings);
for (int i = 0; i < count; i++) {
System.out.println(i+1 + ". " + toppings[i]);
}
}
}
For the following input:
Enter topping topping (or type quit): Cheese
Enter topping topping (or type quit): Onions
Enter topping topping (or type quit): Tuna
Enter topping topping (or type quit): quit
You would receive this output:
1. Cheese
2. Onions
3. Tuna
Don't bother with while loops. If you are dealing with arrays, you should use a for loop.
As far adding a string to the array is concerned, you should really learn about arrays before trying to use them. You did not even initialize your array before using it.
You can use a break statement to exit the loop when the user enters "quit".
import java.util.Arrays;
import java.util.Scanner;
public class Pizza {
//If actually want the user to be able to enter 15 toppings, then set numbers to 16.
public static final int numbers = 16;
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Initialize the array
String[] toppings = new String[numbers];
int count;
//Use a for loop
for (count = 0; count < numbers; count++) {
System.out.println("Enter a toping (or type quit):");
toppings[count] = input.nextLine();
if (toppings[count].equalsIgnoreCase("quit")) {
//If they enter quit, break from the loop
break;
}
}
if (count == numbers)
System.out.println("No more toppings allowed.");
//If they do not fill all 15 indices of the array, trim out the empty indices.
if (count < numbers)
toppings = Arrays.copyOfRange(toppings, 0, count);
Arrays.sort(toppings);
//Use another for to print them
for (int i = 0; i < count; i++) {
System.out.println(i + ". " + toppings[i]);
}
}
}

How do i use user input for a string array that is in a while loop?

I'm trying to convert the user input from the question of students name and score into a array.
I also need help to printout the array.
The while loop is using boolean loopNaming as its condition, and i is updated everytime the loop occurs.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
String[] name = new String[i];
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
name[i] = keyboard.next();
if(name[i].equals("done"))
{
loopNaming = false;
}
else
{
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
i=i+1;
}
System.out.println(name[i]);
}
}
You can simplify the logic of your program and write something like this,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
List<String> nameList = new ArrayList<String>();
List<Double> scoreList = new ArrayList<Double>();
while (true) {
System.out.printf("Enter first name of student or done to finish: ");
String fname = keyboard.next();
if (fname.equals("done")) {
break;
}
System.out.printf("Enter last name of student: ");
String lname = keyboard.next();
nameList.add(fname + " " + lname);
System.out.println("Enter score: ");
scoreList.add(keyboard.nextDouble());
}
keyboard.close();
System.out.println("Names: " + nameList);
System.out.println("scores: " + scoreList);
}
I have changed the array to an arraylist and moved i=i+1; to inside else segment. Also changed the final print statement to print the list.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
ArrayList<String> name = new ArrayList<String>();
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
name.add(keyboard.next());
if(name.get(i).equals("done"))
{
loopNaming = false;
}
else
{
System.out.println("Enter score: ");
score = keyboard.nextDouble();
i=i+1;
}
}
System.out.println(name);
}
I would firstly recommend using a List data structure:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming = true;
List<String> name = new ArrayList<>();
while (loopNaming) {
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if (input.equals("done")) {
loopNaming = false;
} else {
name.add(input);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
}
System.out.println(name.toString());
}
However, if you very much would like to use an array, you could make your own method to increase the size of your array each time a new name is added:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double score;
int i = 0;
boolean loopNaming = true;
String[] name = {};
while (loopNaming) {
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if (input.equals("done")) {
loopNaming = false;
} else {
name = increaseArray(name);
name[i] = input;
System.out.println("Enter score: ");
score = keyboard.nextDouble();
i++;
}
}
System.out.println(Arrays.toString(name));
}
public static String[] increaseArray(String[] arr) {
String[] temp = new String[arr.length + 1];
for (int i = 0; i < arr.length; i++) {
temp[i] = arr[i];
}
return temp;
}
I was unsure what your plan was with your score variable, but this would be two ways to achieve your desired result.
I hope this helps.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
ArrayList<String> name = new ArrayList<>();
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if(input.equals("done"))
{
loopNaming = false;
}
else
{ name.add(input);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
i=i+1; //no need to use
}
System.out.println(name);
}
You should use a dynamic list because You can't resize an array in Java. The second point when the user gives "done", you should not put it in the list so check it before the insertion.
You declared your String array with size 0. that's why you cant add elements in to it.
import java.util.Scanner;
public class NameArray {
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
double score[] = new double[10];
boolean loopNaming=true;
int i=0;
String namae;
String[] name = new String[10];
int count = 0;
while(loopNaming==true){
System.out.printf("Enter name of student or done to finish: ");
name[i] = keyboard.next();
if(name[i].equals("done")){
loopNaming = false;
}
else{
System.out.println("Enter score: ");
score[i] = keyboard.nextDouble();
count++;
}
i=i+1;
}
for(int j = 0; j < count; j++) {
System.out.println(name[j]+" "+score[j]);
}
}
}
Try this code or you can go for any other data structures.

How to compare user input in array?

Hi guys sorry I'm a newbie to Java, this is one of the exercise in my class.
I supposed to ask user input 5 numbers, then compare them if they are the same number that entered before.
These are my code so far, but I can't get it work.
Thanks.
import java.util.Scanner;
public class Source {
private static int num = 0;
private static int[] enterednum = new int[5];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for(int count = 0; count < enterednum.length; count++) {
System.out.println("Enter a number.");
num = input.nextInt();
compare(enterednum);
}
System.out.println("These are the number you have entered: ");
System.out.println(enterednum);
}
public static void compare(int[] enterednum) {
for(int count = 0; count < 6; count++)
if(num == enterednum[count])
System.out.println("The number has been entered before.");
}
}
You may want something like this:
import java.util.Scanner;
public class Source
{
private static int enterednum[]=new int[5];
public static void main(String args[])
{
int num=0; // make this local variable since this need not be class property
Scanner input = new Scanner(System.in);
for(int count=0;count<enterednum.length;count++)
{
System.out.println("Enter a number.");
num = input.nextInt();
compare(num, count);
enterednum[count] = num; // store the input
}
System.out.println("These are the number you have entered: ");
// print numbers in array instead the array
for(int count=0;count<enterednum.length;count++)
{
System.out.println(enterednum[count]);
}
}
// change the method signature to let it get the number of input
public static void compare(int num, int inputcount)
{
for(int count=0;count<inputcount;count++)
{
if(num==enterednum[count])
System.out.println("The number has been entered before.");
}
}
}
You can do this way if you need.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Source {
public static void main(String[] args) throws IOException {
// I used buffered reader because I am familiar with it :)
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create a Set to store numbers
Set<Integer> numbers = new HashSet<>();
for (int i = 0; i < 5; i++) {
System.out.print("Enter a number: ");
String line = in.readLine();
int intValue = Integer.parseInt(line);
// You can check you number is in the set or not
if (numbers.contains(intValue)) {
System.out.println("You have entered " + intValue + " before");
} else {
numbers.add(intValue);
}
}
}
}

Categories