Java - error when creating arraylist - java

So I am a beginner to java (not to programming), and I encoutered a problem where it wont let me create an arrayList:
import java.io.*;
import java.util.ArrayList;
import java.util.*;
public class OrderingNumbers{
public static void main (String[] args)throws IOException{
boolean keepRunning = true;
List<String> numbers = new ArrayList<String>(); //<--this one does not work
ArrayList sortedNumbers = new ArrayList();//<-- This one works
while(keepRunning){
DataInputStream input = new DataInputStream(System.in);
System.out.print("Do you want to sort the numbers or add a number?");
String answer = input.readLine();
if(answer.equals("sort")){
for(int i = 0; i < numbers.size(); i++){
System.out.println(numbers.get(i));
}
System.out.println("Bye Bye.");
keepRunning = false;
}else if(answer.equals("add")){
System.out.print("What number to you want to add?");
numbers.add(input.readLine());
System.out.println("Added number.");
}else{
System.out.print("That is not an option.");
}
}
}
}
I have tried doing this as well, ArrayList<String> strArrayList = new ArrayList<String>(); but still does not work. I am trying to allow the user to add another number to the array if they want.

import java.io.*;
import java.util.*;
public class OrderingNumbers{
public static void main (String[] args)throws IOException{
boolean keepRunning = true;
// here is the corrected line
List numbers = new ArrayList();
ArrayList sortedNumbers = new ArrayList();//<-- This one works
// add data to sort
numbers.add(0, 1); // adds 1 at 0 index
numbers.add(1, 2); // adds 2 at 1 index
System.out.println(numbers);
while(keepRunning){
Scanner input = new Scanner(System.in);
System.out.print("Do you want to sort the numbers or add a number?");
String answer = input.nextLine();
if(answer.equalsIgnoreCase("sort")){
for(int i = 0; i < numbers.size(); i++){
System.out.println(numbers.get(i));
// note does not actually do any sorting
}
System.out.println("Bye Bye.");
keepRunning = false;
}else if(answer.equalsIgnoreCase("add")){
System.out.print("What number to you want to add?");
numbers.add(input.nextLine());
System.out.println("Added number.");
}else{
System.out.print("That is not an option.");
}
}
}
}

The normal usage is as follows:
import java.util.List;
List<String> numbers = new ArrayList<>();
List<String> sortedNumbers = new ArrayList<>();
So typically:
Most general type (List) for variables so implementation may be changed later, and all kind of Lists will fit.
Always typed List<...>.
Using the diamond <> operator.
The error might have been an import java.awt.List; which is an other class with the same name. Probably not here.
To sort (integer) numbers a List<Integer> would seem more logic, as 9 < 10, but "9" greater than "10" alphabetically.
For reading text better use Scanner as mentioned in an other answer. It has:
if (scanner.hasNextInt()) {
int number = scanner.nextInt();
numbers.add(number); // adds an Integer with number's value.
...
The real error is unclear however.

Related

So I'm trying to see if there is a way to count correct inputs and allow multiple inputs with boolean match. Am I able to do this?

So I've tried adding count ++ in multiple places in my code along with researching some way to allow multiple inputs to no avail. Am I missing something on placement or would I need to rewrite the code entirely for what I am wanting to accomplish? Is this not a boolean match situation? Very lost and sorry if this is a noob question. Appreciate the input.
Scanner scanner = new Scanner(System.in);
System.out.println("Insert any State Capital");
String currentInput = scanner.nextLine();
boolean match = false;
String [] capitals = stateCapitals[1];
for (String capital:capitals) {
if (capital.equalsIgnoreCase(currentInput)) {
match = true;
break;
}
}
if (match) {
System.out.println ("Correct");
}
else
System.out.println ("incorrect");
}
}
Problem and what I've tried is above. Also, apologies on formatting if it's messed up. First time using stack overflow.
Please see the below code and let me know if this solves your issue.
import java.util.Scanner;
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
ArrayList<String> inputList = new ArrayList<>();
ArrayList<String> capitalList = new ArrayList<>(List.of("Delhi","Kabul","Dhaka"));
for (int i = 0; i < 5; i++)
{
String currentInput = scanner.nextLine();
inputList.add(currentInput);
}
int correct_response_count = 0;
int wrong_response_count = 0;
for (int i = 0; i < inputList.size(); i++)
{
if (capitalList.contains(inputList.get(i)))
{
correct_response_count++;
}
else
{
wrong_response_count++;
}
}
System.out.println("The correct count of answers is: " + correct_response_count);
System.out.println("The wrong count of answers is: " + wrong_response_count);
}
}
Input
India
Delhi
Australia
Kabul
Bangladesh
Output
The correct count of answers is: 2
The wrong count of answers is: 3

Trying to sort user input into alphabetical order with Java, why won't this code work?

For some reason when I try to ask a user for names so I can add them to a list and sort them alphabetically, this code will not print anything out. It will not even get past the while loop, does anyone have any idea what the problem is? Also another question; how can you execute some code if the user presses the enter button when asked for input value, would it just be null? Thanks!
import java.util.Scanner;
import java.util.*;
public class project16u
{
public static void main(String[] args)
{
int n;
String input = "nothing";
String temp;
ArrayList<String> names = new ArrayList<String>();
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
while(!input.equals("done")){
input = s1.nextLine();
names.add(input);
}
for (int i = 0; i < names.size()-1; i++)
{
if (names.get(i).compareTo(names.get(i+1))>0)
{
temp = names.get(i);
names.add(i, names.get(i+1));
names.add(i+1, temp);
i=0;
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < names.size() - 1; i++)
{
System.out.print(names.get(i).toString() + ",");
}
System.out.print(names.get(names.size()-1));
}
}
add inserts the name at the requested index. Thus, in your case, you will have two copies of the same name in the list, rather than the one you intended.
You probably want to use set instead.
You may need to change the loop condition to
s1.hasNextLine() && !input.equals("done")

Java sort lines from text file

I need to read players from text file, and then output top 3, 5 or 10 players depends on users choice.
Format of data in text file is:
Name, date, correct answerws, points
John, 21.8.2016, 4/5, 80
Edy, 21.8.2016, 5/5, 100
I need to sort them by points and then output best 3,5 or 10 players as i already write.
Here is what i done so far:
public static void topPlayers(){
File f=new File("results.txt");
Scanner scf=new Scanner(f);
Scanner sc=new Scanner(System.in);
Scanner sc2=new Scanner(f);
while(sc2.hasNextLine()){
String p1=scf.nextLine();
String[] niz=p1.split(", ");
}
sc2.close();
System.out.println("Choose an option: ");
System.out.println("1. Top 3 players");
System.out.println("2. Top 5 players");
System.out.println("3. Top 10 players");
int op=sc.nextInt();
if(op==1){
System.out.println("Top 3 players: ");
for(int i=0; i<3; i++){
//System.out.println(....);
}
}
else if(op==2){
System.out.println("Top 5 players: ");
for(int i=0; i<5; i++){
//System.out.println(....);
}
}
else if(op==3){
System.out.println("Top 10 players: ");
for(int i=0; i<10; i++){
//System.out.println(....);
}
}
else{
System.out.println("Wrong option!");
}
}
How to sort this lines from text file by players point?
I highly recommend that you approach this using BufferedReader rather than having three scanners. This snippet will cause you infinite headaches:
File f=new File("results.txt");
Scanner scf=new Scanner(f);
Scanner sc=new Scanner(System.in);
Scanner sc2=new Scanner(f);
Instead, use something resembling this:
File f = new File("results.txt");
FileReader fileIn = new FileReader(f);
BufferedReader reader = new BufferedReader(fileIn);
Using this approach, you can read line by line or segment by segment using ", " and "\n" as delimeters or whatever else you need.
Use the array niz to recreate instances of the player class..
(yes, you will need if not already, to create a player class)
then from every line create a player and add it to a java.util.list
ther sort them with a given criteria... correctAnswers or totalPoints
up to your needs.
Example:
List<Player> myPlayers = new ArrayList<>();
while(sc2.hasNextLine()){
String p1=scf.nextLine();
String[] niz=p1.split(", ");
myPlayers.add(new Player(niz));
}
Collections.sort(myPlayers, new Comparator<Player>() {
#Override
public int compare(Player o1, Player o2) {
return Integer.compare(o1.getTotalPoints(), o2.getTotalPoints());
}
});
after this, a sublist can give you the players you need
i.e
myPlayers.subList(0, 2);
will give the 1st 3 players...
where foo is an instance or an anonymous comparator implementor...
How about old good Stream API?
Customize sortingKeyIndex, separator, neededLines to fit special needs.
import java.nio.file.*;
import java.util.Comparator;
import java.util.stream.Stream;
public class FileSortWithStreams {
public static void main(String[] args) throws Exception {
Path initialFile = Paths.get("files/initial.txt");
Path sortedFile = Paths.get("files/sorted.txt");
int sortingKeyIndex = 3;
String separator = ", ";
int neededLines = 5;
Comparator<String[]> reversedPointsComparator =
Comparator
.<String[], Integer>comparing(s -> extractAsInt(s, sortingKeyIndex))
.reversed();
Stream<CharSequence> sortedLines =
Files.lines(initialFile)
.map(s -> s.split(separator))
.sorted(reversedPointsComparator)
.limit(neededLines)
.map(s -> String.join(separator, s));
Files.write(sortedFile, sortedLines::iterator, StandardOpenOption.CREATE);
}
static int extractAsInt(String[] items, int index) {
return Integer.parseInt(items[index]);
}
}

Using If to break Java statement and displaying input backwards

I need to incorporate an IF statement to break the script when the user enters the letter Q.
I also need to display their input backwards to them - I am unsure on how I would do this, here is my code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListOfNames {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> list = new ArrayList<String>();
Scanner Scan = new Scanner (System.in);
String name;
System.out.println("Please enter some words (You may press Q to finish): ");
while (Scan.hasNext())
{
name = Scan.nextLine();
list.add(name);
}
Scan.close();
}
}
To check against Q:
while(Scan.hasNext())
{
name = Scan.nextLine();
if(name.equals("Q") || name.equals("q"))
{
break;
}
list.add(name);
}
To show list in the reverse order:
for(int i = list.size() - 1; i >= 0; i--)
{
System.out.println(list[i]);
}
How about this.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListOfNames {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> list = new ArrayList<String>();
Scanner Scan = new Scanner (System.in);
String name;
System.out.println("Please enter some words (You may press Q to finish): ");
while (Scan.hasNext())
{
name = Scan.nextLine();
if( name.equals("Q") ) {
break;
}
list.add(name);
}
Scan.close();
}
}
To display input backward put this code after loop that scans input.
for(int i = list.size()-1; i>=0; i--)
System.out.println(list.get(i));
while (Scan.hasNext())
{
name = Scan.nextLine();
//Input is stored to name, so you need to compare input with Q
if("Q".equals(name)
{
//You need to exit the loop
break;
}
list.add(name);
}
//You have what ever user entered in list. So use iterator (or) for-each to print them out again.
As I suspect this is homework, there are probably extra marks for using the Stack class.
Get the data in the loop and push it onto the Stack. Then when you need to print it pop results from the Stack.
From a Software Engineering standpoint, we try to stay away from using break; statements in loops. Instead, it's recommended to use a terminator
final String TERMINATOR = "Q";
boolean terminated = false;
while (scanner.hasNext() && !terminated)
{
String line = scanner.next();
if (!line.equals(TERMINATOR))
{
list.add(line);
}
else
{
terminated = true;
}
}
Also note how we do !line.equals(TERMINATOR) instead of line.equals(TERMINATOR) and do the normal list appending. This is because list appending is the nominal case and as such we want to do the least amount of checks and jumping to get to it.
As for printing out your list in reverse, you can do a simple backwards iterative for-loop
for (int i = list.size()-1; i >= 0; i--)
{
System.out.print(list.get(i) + " ");
}

Cannot Store Data into ArrayLists?

thanks for all the help guys but now the nature of the question has changed using Patrick's suggestion below loop is running but it dise not seem to be storing the input to respective arrays data keeps hetting replaced into the ArrayLists rather than going to the next position into the ArrayList any suggestions?
import java.util.ArrayList;
import java.util.Scanner;
public class Arrray {
public static void main(String [] args){
ArrayList<String> names;
ArrayList<String> addr;
do {
names = new ArrayList<String>();
addr = new ArrayList<String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Name and Adreess are: " + names.size() + "**"
+ addr.size());
System.out.println("please Enter Your Name :");
names.add(userInput.next());
System.out.println("please enter your Address :");
addr.add(userInput.next());
System.out.println("Do you want to add another entry? :(y/n)" );
String ans =userInput.next(); // get the value from the user using scanner class
if(ans.equals("n") || ans.equals("N"))
break;
} while (true);
int n = names.size();
int a = addr.size();
for(int i =0; i<n && i<a; i++ )
System.out.println("Name and address are as below: "+ names.get(i)+"**"+ addr.get(i));
}
}
Use a while(true) in conjunction with a break statement:
do {
if(input.next() == 'n'){
break;
}
} while(true);
get value from the user and if user enter n then break otherwise nothing
System.out.println("Do you want to add another entry? :(y/n)" );
String ans = .... // get the value from the user using scanner class
if(ans.equalsIgnoreCase("n"))
break;
Try to capture this user's input
System.out.println("Do you want to add another entry? :(y/n)");
and use that info in the while.
You have to do something like this:
String choice = "";
do {
.
.
.
.
System.out.println("Do you want to add another entry? :(y/n)" );
choice = userInput.next();
} while (!(choice.equals("n") || choice.equals("N")));
The line
choice = userInput.next();
will read user input, and the String classes equals method for comparing the input. The loop will continue until the choice is either N or n.
import java.util.ArrayList;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> phone = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Please enter your name: ");
name.add(scanner.next());
System.out.println("Please enter your number: ");
phone.add(scanner.nextInt());
System.out.println("Do you want to add a directory y/n?");
answer = scanner.next();
} while (answer.equals("y") || answer.equals("Y"));
if (answer.equals("y") || answer.equals("Y")); //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the directory");
for (int i = 0; i < name.size(); i++) {
System.out.print(name.get(i) + "\t");
System.out.print(phone.get(i));
System.out.println("");
}
}
}
}

Categories