Having an issue with my do while loop as it doesn't end when STOP is entered. Also I'm not sure if I need to add any exceptions or what not. I know doing toString would be more efficient but the requirement for the program is a for loop when extracting the output.
import java.util.*;
import java.util.ArrayList;
import java.lang.IndexOutOfBoundsException;
public class MyProj
{
public static void main(String[] args)
{
ArrayList <String> MyItems = new ArrayList <String>();
Scanner Scan = new Scanner(System.in);
String Temp;
System.out.println("Please enter the name of an object, repeat as needed, type STOP to end");
do
{
Temp = Scan.nextLine();
if(Temp != "STOP")
{
MyItems.add(Temp);
}
}
while(Temp == "STOP");
for(int x = 0; x <= MyItems.size() - 1; x++)
{
System.out.println(MyItems.get(x));
}
}
}
Try this code:
do
{
Temp = Scan.nextLine();
if(!Temp.equals("STOP"))
{
MyItems.add(Temp);
}
}
while(!Temp.equals("STOP"));
I'd recommend that you change that to equalsIgnoreCase() as #3kings suggested.
Related
I have been working on a project this past few days. I run in to some weird problems with scanners.
The goal is to run an infinite loop in scanning users input and passing those input as a parameter for a method.
What I know is that the code works if the items are defined explicitly without the use of scanners as per the code below:
import java.util.Scanner;
public class TrackerConsole {
public static void main(String args[]) {
int i = 0;
Scanner scanInput = new Scanner(System.in);
LifestyleTracker app = new LifestyleTracker();
do {
System.out.println("Enter a command");
String userInput = scanInput.next();
if (userInput.contains("food")) {
System.out.println(app.addFood("pasta", 2000));
}
else if (userInput.contains("eat")) {
System.out.println(app.eat("pasta", 20));
}
else if (userInput.contains("report")) {
System.out.println(app.report());
}
i++;
} while (i < 10);
}
}
But here's the weird part when I add scanners inside the if statement like the code below:
import java.util.Scanner;
public class TrackerConsole {
public static void main(String args[]) {
int i = 0;
Scanner scanInput = new Scanner(System.in);
LifestyleTracker app = new LifestyleTracker();
do {
System.out.println("Enter a command");
String userInput = scanInput.next();
if (userInput.contains("food")) {
System.out.println("Add new food?");
String getFood = scanInput.next();
System.out.println("How many calories");
double getCalories = scanInput.nextDouble();
System.out.println(app.addFood(getFood, getCalories));
}
else if (userInput.contains("eat")) {
System.out.println(app.eat("pasta", 20));
}
else if (userInput.contains("report")) {
System.out.println(app.report());
}
i++;
} while (i < 10);
}
}
Notice when I called the command 'eat' it throws me an error saying that its not in the collections while before that I called 'food' which says 'food is added successfully'. It seems that my method call is not saved when the loop resets. This is the out put of calling the same items in the terminal:
I hope someone can help me with this
i am newbee in java and trying to remove elements from list array. Have been tried many variants, but always get input error and nothing been deleted from list. Have tried take make condition like: if (list.contains(tch.getSurname()) or something like this, always get error that input error. Hope, you will help me to resolve this problem.
package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static Main main = new Main();
/*public static Teachers tch = new Teachers(surname, name);*/
public static List<Teachers> list = new ArrayList<Teachers>();
public static void io(){
Scanner sc = new Scanner(System.in);
String surname = "";
String name = "";
Teachers tch = new Teachers(surname, name);
for (int i=0; i<2; i++) {
surname = sc.nextLine();
name = sc.nextLine();
tch = new Teachers(surname, name);
list.add(tch);
}
for(Teachers nstr : list) {
System.out.println(nstr.toString());
}
for(Teachers t : list) {
String input = sc.nextLine();
if (input == tch.getSurname()) {
list.remove(input);
} else {
System.out.println("Wrong input");
}
}
for(Teachers nstr : list) {
System.out.println(nstr.toString());
}
}
public static void main(String[] args) {
main.io();
}
}
UPDATE:
So i'm tried to use iterator, i've added:
for (Iterator<Teachers> it = list.iterator(); it.hasNext();){
Teachers t = it.next();
if (t.equals(tch.getSurname())){
it.remove();
}
}
and delete:
for(Teachers t : list) {
String input = sc.nextLine();
if (input.equals(tch.getSurname())) {
list.remove(tch);
} else {
System.out.println("Wrong input");
}
}
But it also didn't help me to delete element from list array, it just duplicate my input for list.
Your error is if(input == tch.getSurname(). This compares the exact reference to see if it is the same. Instead, use if(input.equals(tch.getSurname())) to check the contents.
Also change the reference in that loop from tch to t. You are not using the current element in the list rather the one you created to add to the list. Finally change list.remove(input) to list.remove(t). This way the actual element is being removed, no just trying to remove the surname string.
Change your for loop to
Iterator<Teachers> i = list.iterator();
while(i.hasNext()){
Teachers t = i.next();
...
}
Then to remove it just use i.remove()
Now loop works perfectly.
for(Teachers t : list) {
String input = sc.nextLine();
if (input.equals(t.getSurname())) {
list.remove(t);
} else {
System.out.println("Wrong input");
}
}
I'm trying to bubble sort car make and year, where I would have the car year sorted and if two car makes are in the same year, then they are sorted alphabetically. My program works up to the point where I call BubbleSorted(). It's giving me an error java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 and I don't know why. My program seems to be correct. Below is my program. I have 3 classes(main, bubblesortCars, GetCarInfo).
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
public class TheMain {
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
int choice;
boolean done = false;
try{
String filename1 = "Demo.txt";
FileReader inputFile = new FileReader(filename1);
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
ArrayList<GetCarInfo> CarList = new ArrayList();
//Variable to hold the one line data
String line;
StringTokenizer st;
int i=0;
// Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null) {
st = new StringTokenizer(line, "\t");
st.nextToken();
st.nextToken();
String getMake = st.nextToken();
st.nextToken();
int getYear = Integer.parseInt(st.nextToken());
GetCarInfo temp;
temp = new GetCarInfo(getMake, getYear);
CarList.add(temp);
}
bufferReader.close();
BubbleSortCars Sorted = new BubbleSortCars();
Sorted.bubblesorted(CarList, 0, CarList.size());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
import java.util.ArrayList;
public class BubbleSortCars {
ArrayList <GetCarInfo> temp= new ArrayList();
public void bubblesorted(ArrayList <GetCarInfo> grabber, int began, int end){
for(int i =0; i<end-began-1; i++){
for(int j=began; j<(end-i-1); j++){
if(grabber.get(j).year > grabber.get(j+1).year){
temp.set(j, grabber.get(j));
grabber.set(j,grabber.get(j+1));
grabber.set(j+1, temp.get(j));
System.out.println("Success");
}
else if(grabber.get(j).year==grabber.get(j+1).year){
if((grabber.get(j).make).compareTo(grabber.get(j+1).make)>0){
temp.set(j, grabber.get(j));
grabber.set(j, grabber.get(j+1));
grabber.set(j+1, temp.get(j));
System.out.println("Success");
}
}
}
}
}
}
public class GetCarInfo {
int year;
String make;
public GetCarInfo(String newmake, int newyear){
make = newmake;
year = newyear;
}
}
Reason you get IndeOutOfBoundException is due to this line:
temp.set(j, grabber.get(j));
and your definition of arrayList.
ArrayList<GetCarInfo> temp = new ArrayList();
Here you are defining temp as arrayList without any element and you are trying to set an element at 0th location which is not defined. See this for your reference http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#set%28int,%20E%29
When you define temp as above it created with size 0 and jdk does check internally if index that you are trying to access is less than size then only it will allow you to access/set content.
So one way to avoid this, you define your temp arrayList in your method like:
ArrayList<GetCarInfo> temp = new ArrayList(grabber);
Or you could use grabber arrayList to do the sorting without any other data structure.
The problem is with the ArrayList temp. Please refer the Oracle documentation for the set method.
Here you don't need an ArrayList. User a simple GetCarInfo object as temp variable.
I would like to start off by saying that if this is common knowledge, please forgive me and have patience. I am somewhat new to Java.
I am trying to write a program that will store many values of variables in a sort of buffer. I was wondering if there was a way to have the program "create" its own variables, and assign them to values.
Here is an Example of what I am trying to avoid:
package test;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int inputCacheNumber = 0;
//Text File:
String userInputCache1 = null;
String userInputCache2 = null;
String userInputCache3 = null;
String userInputCache4 = null;
//Program
while (true) {
Scanner scan = new Scanner(System.in);
System.out.println("User Input: ");
String userInput;
userInput = scan.nextLine();
// This would be in the text file
if (inputCacheNumber == 0) {
userInputCache1 = userInput;
inputCacheNumber++;
System.out.println(userInputCache1);
} else if (inputCacheNumber == 1) {
userInputCache2 = userInput;
inputCacheNumber++;
} else if (inputCacheNumber == 2) {
userInputCache3 = userInput;
inputCacheNumber++;
} else if (inputCacheNumber == 3) {
userInputCache4 = userInput;
inputCacheNumber++;
}
// And so on
}
}
}
So just to try to summarize, I would like to know if there is a way for a program to set an unlimited number of user input values to String values. I am wondering if there is a way I can avoid predefining all the variables it may need.
Thanks for reading, and your patience and help!
~Rane
You can use Array List data structure.
The ArrayList class extends AbstractList and implements the List
interface. ArrayList supports dynamic arrays that can grow as needed.
For example:
List<String> userInputCache = new ArrayList<>();
and when you want to add each input into your array like
if (inputCacheNumber == 0) {
userInputCache.add(userInput); // <----- here
inputCacheNumber++;
}
If you want to traverse your array list you can do as follows:
for (int i = 0; i < userInputCache.size(); i++) {
System.out.println(" your user input is " + userInputCache.get(i));
}
or you can use enhanced for loop
for(String st : userInputCache) {
System.out.println("Your user input is " + st);
}
Note: it is better to put your Scanner in your try catch block with resource so you will not be worried if it is close or not at the end.
For example:
try(Scanner input = new Scanner(System.in)) {
/*
**whatever code you have you put here**
Good point for MadProgrammer:
Just beware of it, that's all. A lot of people have multiple stages in their
programs which may require them to create a new Scanner AFTER the try-block
*/
} catch(Exception e) {
}
For more info on ArrayList
http://www.tutorialspoint.com/java/java_arraylist_class.htm
I'm not sure why this isn't working. I'm not sure if it's a problem with the printing, or if it's a problem with the methods themselves.
I am making a program that takes a collection of songs and filters or sorts it according to a given user input. The user should be able to input multiple commands to further narrow down the list.
My filterRank and filterYear methods work perfectly fine, but the other methods end up printing a seemingly random selection of songs that do not change regardless of what is inputted as the title or artist to be filtered by, which generally appears only after an extremely long waiting period and a long series of spaces.
Even after this amalgam of songs is printed, the program does not terminate, and periodically outputs a space in the console, as in a System.out.println() statement were being continuously run.
If I remove the code that configures the output file, which is a requirement for the project, the methods fail to print entirely. Regardless of either of these changes, filterRank and filterYear continue to work perfectly.
This problem also occurs with my sort methods. No matter what sort method I run, it still prints out the spaces and the random songs, or nothing at all.
Is there something I'm missing? I've tried printing out variables and strategically inserting System.out.println("test") in my program to determine what the program is, but it seems as though it's parsing the input correctly, and the methods are indeed being successfully run.
I've been otherwise unable to isolate the problem.
Can I get assistance in determining what I'm missing? Despite poring over my code for two hours, I just can't figure out what the logical error on my part is.
Here is the relevant code:
The main class:
public static void main(String[] args) throws FileNotFoundException, IOException{
//user greeting statements and instructions
//scanning file, ArrayList declaration
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
int n = 0;
SongCollection collection = new SongCollection(songs);
String inputType = input.nextLine();
String delims = "[ ]";
String[] tokens = inputType.split(delims);
for (int i = 0; i < tokens.length; i++) {
n = 0;
if (n == 0) {
if ((tokens[i]).contains("year:")) {
collection.filterYear(Range.parse(tokens[i]));
n = 1;
}// end of year loop
if ((tokens[i]).contains("rank:")) {
collection.filterRank(Range.parse(tokens[i]));
n = 1;
}// end of rank
if ((tokens[i]).contains("artist:")) {
collection.filterArtist(tokens[i]);
n = 1;
}// end of artist
if ((tokens[i]).contains("title:")) {
collection.filterTitle(tokens[i]);
n = 1;
}// end of title
if ((tokens[i]).contains("sort:")) {
if ((tokens[i]).contains("title")) {
collection.sortTitle();
n = 1;
}// end of sort title
if ((tokens[i]).contains("artist")) {
collection.sortArtist();
n = 1;
}// end of sort artist
if ((tokens[i]).contains("rank")) {
collection.sortRank();
n = 1;
}// end of sort rank
if ((tokens[i]).contains("year")) {
collection.sortYear();
n = 1;
}// end of sort year
}//end of sort
}// end of for loop
}// end of input.hasNextline loop
/*final PrintStream console = System.out; //saves original System.out
File outputFile = new File("output.txt"); //output file
PrintStream out = new PrintStream(new FileOutputStream(outputFile)); //new FileOutputStream
System.setOut(out); //changes where data will be printed
*/ System.out.println(collection.toString());
/*System.setOut(console); //changes output to print back to console
Scanner outputFileScanner = new Scanner(outputFile); //inputs data from file
while ((outputFileScanner.hasNextLine())) { //while the file still has data
System.out.println(outputFileScanner.nextLine()); //print
}
outputFileScanner.close();
out.close();*/
}
}// end of main
}// end of class
The SongCollection Class, with all of its respective filter and sort methods:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class SongCollection {
ArrayList<Song> songs2;
ArrayList<Song> itemsToRemove = new ArrayList<Song>(); // second collection
// for items to
// remove
public SongCollection(ArrayList<Song> songs) { // constructor for SongCollection
System.out.println("Test");
this.songs2 = songs;
}
public void filterYear(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.year > (r.getMax()) || (song1.year) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
public void filterRank(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.rank > (r.getMax()) || (song1.rank) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
public void filterArtist(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.artist).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
public void filterTitle(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.title).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
public void sortTitle() {
Collections.sort(songs2, SongComparator.byTitle()); // now we have a sorted list
}
public void sortRank() {
Collections.sort(songs2, SongComparator.byRank()); // now we have a sorted list
}
public void sortArtist() {
Collections.sort(songs2, SongComparator.byArtist()); // now we have a sorted list
}
public void sortYear() {
Collections.sort(songs2, SongComparator.byYear()); // now we have a sorted list
}
public String toString() {
String result = "";
for (int i = 0; i < songs2.size(); i++) {
result += " " + songs2.get(i);
}
return result;
}
}
SongComparator Class:
import java.util.Comparator;
public class SongComparator implements Comparator<Song> {
public enum Order{
YEAR_SORT, RANK_SORT, ARTIST_SORT, TITLE_SORT
}
private Order sortingBy;
public SongComparator(Order sortingBy){
this.sortingBy = sortingBy;
}
public static SongComparator byTitle() {
return new SongComparator(SongComparator.Order.TITLE_SORT);
}
public static SongComparator byYear() {
return new SongComparator(SongComparator.Order.YEAR_SORT);
}
public static SongComparator byArtist() {
return new SongComparator(SongComparator.Order.ARTIST_SORT);
}
public static SongComparator byRank() {
return new SongComparator(SongComparator.Order.RANK_SORT);
}
#Override
public int compare(Song song1, Song song2) {
switch (sortingBy) {
case YEAR_SORT:
System.out.println("test");
return Integer.compare(song1.year, song2.year);
case RANK_SORT:
System.out.println("test");
return Integer.compare(song1.rank, song2.rank);
case ARTIST_SORT:
System.out.println("test");
return song1.artist.compareTo(song2.artist);
case TITLE_SORT:
System.out.println("test");
return song1.title.compareTo(song2.title);
}
throw new RuntimeException(
"Practically unreachable code, can't be thrown");
}
}
After you output the filtered collection, your program doesn't terminate because you are still in a while loop looking for the next user input line. This is basically what your program is doing:
while (input.hasNextLine()) {
// stuff happens here
System.out.println(collection.toString());
/*
* System.setOut(console); //changes output to print back to console Scanner outputFileScanner = new Scanner(outputFile); //inputs data from file while ((outputFileScanner.hasNextLine()))
* { //while the file still has data System.out.println(outputFileScanner.nextLine()); //print } outputFileScanner.close(); out.close();
*/
}