Cannot add a class field to ArrayList - java

I have no idea how to properly write line of code adding class field to an ArrayList
public class Main {
public static void main(String[] args) throws IOException
{
zapisz("BazaDanych.txt");
Scanner scanner = new Scanner(System.in);
FilmExtended filmExtended = new FilmExtended();
ArrayList<FilmExtended> bazaFilmow = new ArrayList<>();
int i = 0;
while(scanner.nextInt()!= 0)
{
boolean check = true;
do
{
System.out.println("Podaj tytuł fimu: ");
String temp = scanner.nextLine();
if (temp.matches("[a-zA-Z]{2,}"));
{
bazaFilmow.add(i,filmExtended.setTytul(temp));
check = false;
}
}while (check);
}
}

You don't increment your index i. It's always 0. You have to put i++; in your do while loop

public class Main {
public static void main(String[] args) throws IOException
{
zapisz("BazaDanych.txt");
Scanner scanner = new Scanner(System.in);
List<FilmExtended> bazaFilmow = new ArrayList<>();
//remove index
while(scanner.nextInt() != 0)
{
boolean check = true;
do
{
System.out.println("Podaj tytuł fimu: ");
String temp = scanner.nextLine();
if (temp.matches("[a-zA-Z]{2,}"));
{
FilmExtended filmExtended = new FilmExtended(); //create new instance
filmExtended.setTytul(temp);
bazaFilmow.add(filmExtended); //use add without index or else need to increment your index
check = false;
}
} while (check);
} }

You have to add i++; in the do while loop

Two ways to fix it:
filmExtended.setTytul(temp) should return this.
i++ or remove i

Related

What in my code would cause my for loop to terminate prematurely? Am I missing "i" somewhere within the loop?

I can't figure out what is causing my for loop to terminate. I just tried testing it and it only runs the print function. Then it just terminates. I can't see why it would do this.
import java.util.Scanner;
import java.util.ArrayList;
public class Test092 {
public static void main(String[] args) {
Scanner usersVal = new Scanner(System.in);
ArrayList<Integer> arrayList = new ArrayList<>();
int valAdd = 0;
System.out.println("Please provide a list of numbers");
for (int i = 0; i < arrayList.size(); i++) {
valAdd = Integer.valueOf(usersVal.nextInt());
if (valAdd == -1) {
break;
}else {
arrayList.add(valAdd);
}
}
}
}
The issue is that your arrayList doesn't have any elements in it. Therefore, when your loop checks i < arrayList.size() the loop does not run (since arrayList.size() is 0)
Try this:
public static void main(String [] args) {
try (Scanner usersVal = new Scanner(System.in)) {
List<Integer> arrayList = new ArrayList<>();
System.out.println("Please provide a list of numbers");
int valAdd = usersVal.nextInt();
while (valAdd != -1) {
arrayList.add(valAdd);
valAdd = usersVal.nextInt();
}
System.out.println(arrayList);
} catch (Exception e) {
e.printStackTrace();
}
}

How to check if word in ArrayList is substring of name in file, then increment the count of that word?

So if I'm trying to read a recipe file, the file is supposed to find words that match with the words on my ArrayList and if there is a match, the count of that word gets incremented. Here is what I have so far but I am stuck on what I should do in the loop.
public class Main {
private Scanner inp = new Scanner( System.in);
private ArrayList<String> foodList = new ArrayList<String>();
private int ingredientCount = 0;
public A1() {
foodList.add("baking powder");
foodList.add("baking soda");
foodList.add("cheese");
foodList.add("broth");
foodList.add("tomato paste");
foodList.add("tomato");
foodList.add("flour");
foodList.add("egg");
foodList.add("garlic");
foodList.add("cheese");
foodList.add("rice");
foodList.add("onion");
foodList.add("salt");
foodList.add("pepper");
foodList.add("vinegar");
foodList.add("carrot");
foodList.add("sweet potato");
foodList.add("potato");
foodList.add("cream");
foodList.add("milk");
foodList.add("bean");
foodList.add("green bean");
foodList.add("beef");
foodList.add("chicken");
foodList.add("cumin");
foodList.add("basil");
foodList.add("oregano");
foodList.add("oil");
foodList.add("fish");
}
private void readFile() {
while (inp.hasNext()) {
String nextLine = inp.next().toLowerCase();
if (nextLine.contains(foodList())) {
totalwordcount++; //This is the part I'm stuck on. How do I only
//incriment that food item from the list?
}
}
}
}
If you're not permitted to use a Map<String, Integer> to keep the counts you could just use an array:
private Scanner inp = new Scanner( System.in);
private ArrayList<String> foodList = new ArrayList<String>();
private int[] ingredientCount;
public A1() {
foodList.add("baking powder");
foodList.add("baking soda");
// ...
foodList.add("oil");
foodList.add("fish");
ingredientCount = new int[foodList.size()];
}
private void readFile() {
while (inp.hasNext()) {
String nextLine = inp.next().toLowerCase();
for(int i=0; i<foodList.size(); i++)
{
if (nextLine.contains(foodList.get(i))) {
ingredientCount[i] += 1;
}
}
}
for(int i=0; i<foodList.size(); i++)
{
System.out.printf("%s occured %d time(s)\n", foodList.get(i), ingredientCount[i]);
}
}

Make Array From Temporary Arrays

I have a file in where rows of random integers are divided by "::".
For example "1 2 3::4 5:: 6 7 8 9::10 11 12::13"
What I want to make is an array where the rows are combined as follows: take the second row and place at the back of the first row, then take the third row place it in front of the first row, take the fourth row and place it at the back etc.
At the moment I can fill a temporary array with one row and place it in the totalArray but this will get overwritten by with the next row.
I can not use ArrayList or multi dimensional arrays.
The code to make it more clear:
class1() {
in = new Scanner(System.in);
out = new PrintStream(System.out);
}
public void lineToArray (Scanner intScanner) {
int i = 0;
int[] tempArray = new int[100];
while (intScanner.hasNext()) {
tempArray[i] = intScanner.nextInt();
i++;
}
}
public void readFile() {
while (in.hasNext()) {
in.useDelimiter("::");
String line = in.next();
Scanner lineScanner = new Scanner(line);
lineToArray(lineScanner);
}
}
void start() {
readFile();
}
and
public class Class2 {
int[] totalArray = new int[1000];
Class2() {
}
public void addToFront(int[] tempArray, int i) {
//totalArray = tempArray + totalArray
}
public void addToBack(int[] tempArray, int i) {
//totalArray = totalArray + tempArray
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Bear in mind that I'm a beginner
public static void main(String args[]) throws IOException
{
Scanner in = new Scanner(System.in);
PrintWriter w = new PrintWriter(System.out);
String inp = in.nextLine();
String s[] = inp.split("::");
StringBuilder ans = new StringBuilder();
for(int i = 0; i < s.length; i++){
if(i == 0){
ans.append(s[i]);
}
else if(i%2 == 0){
ans.append("::"+s[i]);
} else{
ans.reverse();
StringBuilder add = new StringBuilder(s[i]);
add.reverse();
ans.append("::"+add);
ans.reverse();
}
}
w.println(ans);
w.close();
}
Output:
1 2 3::4 5:: 6 7 8 9::10 11 12::13
10 11 12::4 5::1 2 3:: 6 7 8 9::13

Why is this code getting a Java NoSuchElement exception?

I have traced through this code and can't figure out how to fix it. When running the code why wouldn't the user be prompted for input rather than Java determining that there is no input? Error trace below.
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
int array_size = GetArraySize();
//System.out.println(array_size);
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String next_string = GetNextString();
System.out.println(next_string);
}
}
//public static String[] SortInsert(String nextString){
//}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
input.close();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
input.close();
return next_string;
}
Here is the error --
How many items are you entering?: 2
Enter the next string:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at SortAsInserted.GetNextString(SortAsInserted.java:40)
at SortAsInserted.main(SortAsInserted.java:10)
The simple answer is when you close Scanner -- underlying input stream also closes:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()
To fix this create Scanner once in main:
public class SortAsInserted {
static Scanner input;
public static void main(String[] _) {
input = new Scanner(System.in);
....
input.close();
}
Remove input.close(); from the code
Removing the scanner.close() method from two functions will solve your problem.
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
int array_size = GetArraySize();
//System.out.println(array_size);
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String next_string = GetNextString();
System.out.println(next_string);
}
}
//public static String[] SortInsert(String nextString){
//}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
//input.close();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
// input.close();
return next_string;
}
}

Java - while loop not working as expected

I am working with a fairly basic programming task in Java. We are asked to create a chat-robot, where the robot is to answer randomly from a set of given strings until the user writes "Bye!", where the robot will simply reply with "Bye!" and end the program. I've written the following code:
import java.util.Scanner;
import java.util.Random;
public class Robot {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
String[] answer = new String[6];
answer[0] = "blabla1";
answer[1] = "blabla2";
answer[2] = "blabla3";
answer[3] = "blabla4";
answer[4] = "blabla5";
answer[5] = "blabla6";
boolean keepGoing = true;
System.out.println("Hello, how can I help you?");
while (keepGoing) {
String input = in.next();
int output = random.nextInt(6);
System.out.println(answer[output]);
if (input.equals("Bye!")){
keepGoing = false;
System.out.println("Bye!");
}
}
}
I have two issues with the program:
At times, seemingly at random, the program will answer with multiple strings.
When writing "Bye!", the program throws in another string before writing "Bye!". I do know that this may be resolved by adding "break;", but I'd consider this bad practice seeing as I am already using a boolean. (I'd like to keep using it.)
I have no idea as to why these errors occur.
Check the condition for exit before printing anything. That will resolve the 2nd issue
while (true) {
String input = in.next();
if (input.equals("Bye!")){
System.out.println("Bye!");
break;
}
int output = random.nextInt(6);
System.out.println(answer[output]);
}
Change your program like this
import java.util.Scanner;
import java.util.Random;
public class Robot {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
String[] answer = new String[6];
answer[0] = "blabla1";
answer[1] = "blabla2";
answer[2] = "blabla3";
answer[3] = "blabla4";
answer[4] = "blabla5";
answer[5] = "blabla6";
boolean continue1 = true;
System.out.println("Hello, how can I help you?");
while (continue1) {
String input = in.next();
int output = random.nextInt(6);
if (input.equals("Bye!")){
continue1 = false;
System.out.println("Bye!");
}else
{
System.out.println(answer[output]);
}
}
}
}
Use below code snappet to solve Issue2:
while (keepGoing) {
String input = in.next();
int output = random.nextInt(6);
if(!input.equals("Bye!"))
System.out.println(answer[output]);
if (input.equals("Bye!")){
keepGoing = false;
System.out.println("Bye!");
}
}
Scanner in = new Scanner(System.in);
Random random = new Random();
String[] answer = new String[6];
answer[0] = "blabla1";
answer[1] = "blabla2";
answer[2] = "blabla3";
answer[3] = "blabla4";
answer[4] = "blabla5";
answer[5] = "blabla6";
boolean keepGoing = true;
System.out.println("Hello, how can I help you?");
while (keepGoing) {
String input = in.next();
if ("Bye!".equals(input)) {
keepGoing = false;
System.out.println("Bye!");
} else {
int output = random.nextInt(6);
System.out.println(answer[output]);
}
}
import java.util.Scanner;
import java.util.Random;
public class Robot
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Random random = new Random();
String[] answer = new String[6];
answer[0] = "blabla1";
answer[1] = "blabla2";
answer[2] = "blabla3";
answer[3] = "blabla4";
answer[4] = "blabla5";
answer[5] = "blabla6";
boolean keepGoing = true;
System.out.println("Hello, how can I help you?");
while (keepGoing)
{
String input = in.next();
int output = random.nextInt(6);
System.out.println(answer[output]);
if (input.equals("Bye!"))
{
keepGoing = false;
System.out.println("Bye!");
} //This bracket is the only thing missing in your code.
}// End of while loop
} // End of main method
}// End of class

Categories

Resources