for loop with ArrayList in java - java

i got a Productclass stored in ArrayList myValues.
I want to go trough each xth ( for example each 3th) element and have the user
add some Integer values to that class.
In my for(...) he tells me: The left-hand side of an assignment must be a variable. I wonder if i messed up some of the .get(j) or if i have to synchronize my methods so that the size wont change ( there is no multi-threading but maybe thats why i get an error?
) or the solution is more simple.
Thx
public void prioPerProduct (){
System.out.println("");
System.out.println("Please enter storing and upgrading cost:");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int storingCost = 0;
int ruestCost = 0;
int countRes = countRessources;
int sizemyValues = myValues.size();
for(int j = 0; j < sizemyValues; j = j+countRes){
System.out.println("Please enter storingcost " + myValues.get(j).getProduct() +":" );
try {
storingCost = Integer.valueOf(br.readLine());
} catch (NumberFormatException e) {
System.out.println("No number entered");
e.printStackTrace();
} catch (IOException e) {
System.out.println("No number entered");
e.printStackTrace();
}
System.out.println("Please enter upgradingcost " + myValues.get(j).getProduct() +":" );
try {
ruestCost = Integer.valueOf(br.readLine());
} catch (NumberFormatException e) {
System.out.println("No number entered");
e.printStackTrace();
} catch (IOException e) {
System.out.println("No number entered");
e.printStackTrace();
}
myValues.get(j).setstoringCost(storingCost);
myValues.get(j).setupgradingCost(ruestCost);
}
}

The left-hand side of an assignment must be a variable is generally caused by something like this:
methodCall() = somvalue...
The left hand side must be a variable rather than a method call. Your code looks fine in this regard.
The code where you declare your model class and a full stack trace are more helpful.

Use the set method to change the value of an object inside of an ArrayList.
myValues.set(j,myValues.get().setstoringCost(storingCost));
myValues.set(j,myValues.get().setupgradingCost(ruestCost));

Related

how to implement a linked list properly using java

I am working in a project with linked list (JAVA) but I am not being able to figure out how to insert the person. How could I get the switch to work? Or should I use something else? I also thought about creating a class outside the main method and just call it but it did not work as well. Any help will be much appreciate
public void listOfPeople() { // Beginning of the method listOfPeople where shows the employees
// *** instance the person object ad loading your variables
Personqueue p1 = new Personqueue(); //saving the employee in a variable???
p1.setFname("John");
p1.setLname("Smith");
p1.setDOA(15);
p1.setPassportN(306589);
p1.setNumber(1);
vectorObj.add(p1); // add the employee in a vector
Personqueue p2 = new Personqueue(); //saving the employee in a variable???
p1.setFname("Paul");
p1.setLname("Clooney");
p1.setDOA(5);
p1.setPassportN(30614584);
p1.setNumber(2);
vectorObj.add(p2); // add the employee in a vector
}
public void ascendingOrder(Vector<Personqueue> vector) { // bubble sort method to order the vector
int j;
boolean flag = true; // set flag to true to begin first pass
Personqueue temp; // holding the variable temporarily
while (flag) {
flag = false; // set flag to false awaiting a possible swap
for (j = 0; j < vector.size() - 1; j++) {
if (vector.get(j).getNumber() > vector.get(j + 1).getNumber()) {
temp = vector.get(j); // swap elements
vector.set(j, vector.get(j + 1));
vector.set(j + 1, temp);
flag = true; // shows a swap occurred
}
}
}
}
public void newPerson(int positionPerson) { // beginning of newPerson method
String Option = null; // declaration of local variables that are used only in this method and don't use too much space
Personqueue p = new Personqueue(); //instead of setting it to null, here we are calling
// a constructor which was declared in Personqueue class.
// switch (positionPerson) {
// case 1: // insert a person at the start of the queue
// // p = new QueueStart();
// break; // executes in order to end the switch in case one of the options is valid
// case 2: // insert a person at a chosen point in the queue
// // p = new ChoosePosition();
// case 3: // insert a person at the end of the queue
// // p = new EndQueue();
// break;
// default:
// System.out.println("Invalid Option!!!"); // in case the option is not one of the cases above, print this...
// return; // return to the do/while loop in Principal method
// }
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Name:"); // user input
try {
Option = br.readLine();
String name = Option;
p.setFname(name);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Surname:"); // user input
try {
Option = br.readLine();
String lname = Option;
p.setLname(lname);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Date Of Arrival: "); // user input
try {
Option = br.readLine();
int doa = Integer.parseInt(Option); // use parseInt in order to convert Integer to String to be read by BufferedReader.
p.setDOA(doa);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Passport Number:"); // user input
try {
Option = br.readLine();
int pn = Integer.parseInt(Option);
p.setPassportN(pn);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Number:"); // user input
try {
Option = br.readLine();
int no = Integer.parseInt(Option);
p.setNumber(no);
} catch (IOException e) {
System.out.println(e);
}
vectorObj.addElement(p); // save all the data in the vector
System.out.print("Saving Person :" + p.getFname()); // print to the user the name's been saved
try {
for (int i = 0; i < 6; i++) {
System.out.print(".");
Thread.sleep(300); // suspend the "." execution for a specified period.
}
} catch (InterruptedException e) { // exception p o method thread // catch for thread above
e.printStackTrace();
}
System.out.println();
System.out.println("Person: " + p.getFname() + " is saved!!!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} // end of the Method newPerson
Check your variables in listOfPeople(...), p2 was not used correctly.
Take a look at Example of LinkedList in Java

Appending text on a character interval

I am trying to write a program where the participant communicates with the program (I/O) via a console. Trick is, the console is part of a GUI, because I need the program to run off of a executable jar file. I append text with a scrollable text field, like so
textArea.append(printChar);
I give the method a String to work with, and it uses a nested for loop to take it, char by char, and append each Char (using string.substring()).
My problem is that it freezes up the entire time its supposed to be printing, then just displays it all. I don't know why, because I tested it using System.out.print, and it worked exactly as I wanted. So something is different about appending and printing. Any ideas?
Also, I am using Thread.Sleep(100) for my wait time.
public void actionPerformed(ActionEvent evt) {
if (!preforming){
preforming = true;
String input = textField.getText(); //Text from Input
textArea.append(dungeon.name + ": " + input + newline); //Add "text" to bottom of console
String[] output = dungeon.action(input);
//print everything in array output, char by char, with 2-3 seconds after each
for (int i = 0; i < output.length; i++){
String printThis = output[i];
if (printThis.length() > 0){
for (int j = 0; j < printThis.length(); j++){
String printChar = printThis.substring(j, j+1);
textArea.append(printChar);
//System.out.print(printChar);
try{
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.print("Error ");
}
/*try { //useless
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
textArea.append("" + newline);
}
//cleaning up input bar
textField.setText("");
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
preforming = false;
}
}
I've edited my answer as you are showing more of your codes. Since, there is an outer loop in your code, I just included it inside the run method of timer in this new edit. And also I don't have the code for the dungeon so I just temporarily replace it with constant values so the program can run in my test.
public void actionPerformed(ActionEvent evt) {
java.util.Timer timer = new java.util.Timer();
timer.schedule(new java.util.TimerTask() {
public void run() {
if (!preforming){
preforming = true;
String newline = "\n";
String dungeonName = "Star Light";
String input = textField.getText(); //Text from Input
textArea.append(dungeonName + ": " + input + newline); //Add "text" to bottom of console
String[] output = {
"Twinkle twinkle little star.",
"How I wonder what you are.",
"Up above the world so high."
};
//print everything in array output, char by char, with 2-3 seconds after each
for (int i = 0; i < output.length; i++){
String printThis = output[i];
if (printThis.length() > 0){
for (int j = 0; j < printThis.length(); j++){
String printChar = printThis.substring(j, j+1);
textArea.append(printChar);
//System.out.print(printChar);
try{
Thread.sleep(25);
} catch (InterruptedException e) {
System.out.print("Error ");
}
/*try { //useless
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
textArea.append("" + newline);
}
//cleaning up input bar
textField.setText("");
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
preforming = false;
}
}
}, 1);
}

Trying to implement a score system while using if/else. [JAVA]

I'm a beginner at java and I'm trying to have a score system that uses my if/else statements to either increment or decrement according to right or wrong answers. The program should increment if the user matches the text that is found in the text file and decrement if incorrect. Right now, the program will display "-1" if incorrect and "1" if correct, regardless of how many times it goes through the loop. It should change the value of result but it keeps resetting to "0". I have tried already but I believe I had an issue with scope. If anyone could help I'd be very grateful.
package typetrain;
import java.util.*;
import java.io.*;
import javax.swing.*;
/**
*
* #author Haf
*/
public class Game1 {
public void Game () {
JOptionPane.showMessageDialog(null, "Please answer in the correct line of text. \n" +
"each line of text will grant you one point. "
+ "\nIncorrect answers will lead to a point being subtracted");
String fileName = "test.txt";
String line;
ArrayList aList = new ArrayList();
try {
BufferedReader input = new BufferedReader (new FileReader(fileName));
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) !=null) {
aList.add(line);
}
input.close();
} catch (IOException e) {
System.out.println(e);
}
int sz = aList.size();
for (int i = 0; i< sz; i++) {
int result = 0;
String correctAnswer = aList.get(i).toString();
String userAnswer = JOptionPane.showInputDialog(null, "Copy this line of text! \n" + aList.get(i).toString());
if (correctAnswer.equals(userAnswer)) {
JOptionPane.showMessageDialog(null, "Correct!");
result++;
}
else if (!correctAnswer.equals(userAnswer)) {
JOptionPane.showMessageDialog(null, "Incorrect!");
result--;
}
JOptionPane.showMessageDialog(null, result);
}
}
}
You just need to move your int result = 0; to the line before your for loop. Otherwise, it will get reset to 0 each time.

What is the most efficient way to print all query results with column names?

I have a result set ResultSet rs=stmt.executeQuery(); I wrote a method to print query results as following
public void printResults(ResultSet rs) {
// Getting column names
int j = 1;
while (true) {
try {
System.out.print(rs.getMetaData().getColumnName(j)+" ");
j++;
}
catch (Exception e) {
System.out.println("\n");
break;
}
}
// Getting results
while(rs.next()) {
int i = 1;
while (true) {
try {
System.out.print(rs.getString(i)+" ");
i++;
}
catch (Exception e) {
System.out.println("\n");
break;
}
}
}
}
My issue is : is it a good idea to use try && catch ... I feel that it is not? Does it impact speed? What is a better way?
Thank You
You can get column number by
ResultSetMetaData meta= rs.getMetaData();
int columnNum=meta.getColumnCount();
Loop with this columnNum to get the result as well as column name.
for(int i=1;i<=columnNum;i++){
System.out.print(meta.getColumnName(i)+" ");
}
//Get the data
while(rs.next){
for(int i=1;i<=columnNum;i++){
System.out.print(rs.getString(i)+" ");
}
}

how to reset program to main string args?

I am writing a program and if it catches an Exception I want to reset the whole program is there anyway please tell me I really need to finish it tonight ?
public static void readinfile(ArrayList<ArrayList> table,
int numberOfColumns,ArrayList<String> header,
ArrayList<ArrayList<String>> original,
ArrayList<String> sntypes, ArrayList<Integer> displaySize,
ArrayList<String> writeOut, Scanner inputStream) {
//System.out.print("enter data file: ");
Scanner keyboard = new Scanner(System.in);
System.out.print("enter data file: ");
String fileName = keyboard.nextLine();
try {
System.out.println("try " + fileName);
inputStream = new Scanner(new FileInputStream(fileName));
System.out.println(inputStream);
} catch (FileNotFoundException E) {
System.out.println("Error in opening file ");
//readinfile(table, numberOfColumns, header,
//original, sntypes,displaySize, writeOut, inputStream );
}
// file is now open and input scanner attached
if (inputStream.hasNextLine()) {
String Line = inputStream.nextLine();
Scanner lineparse = new Scanner(Line);
lineparse.useDelimiter(",");
ArrayList<String> rowOne = new ArrayList<String>();
while (lineparse.hasNext()) {
String temp = lineparse.next();
String originaltemp = temp;
writeOut.add(temp);
temp = temp + "(" + (++numberOfColumns) + ")";
displaySize.add(temp.length());
// row.add(lineparse.next());
if (temp.trim().substring(0, 2).equalsIgnoreCase("S ")
|| temp.trim().substring(0, 2).equalsIgnoreCase("N ")) {
rowOne.add(originaltemp);
header.add(temp.substring(2));
sntypes.add(temp.toUpperCase().substring(0, 2).trim());
} else {
System.out.println("Invalid file please enter a new file: ");
//readinfile(table, numberOfColumns, header, original, sntypes,displaySize,writeOut,Name);
readinfile(table, numberOfColumns, header,
original, sntypes, displaySize, writeOut, inputStream);
}
}
// add table here it gives problem later on...
original.add(rowOne);
}
while (inputStream.hasNextLine()) {
String Line = inputStream.nextLine();
Scanner lineparse = new Scanner(Line);
lineparse.useDelimiter(",");
ArrayList row = new ArrayList();
int j = 0;
while (lineparse.hasNextLine()) {
String temp = lineparse.next().trim();
int sizeOfrow = temp.trim().length();
if (sizeOfrow > displaySize.get(j)) {
displaySize.set(j, sizeOfrow);
}
if (j < numberOfColumns && sntypes.get(j).equalsIgnoreCase("N")) {
try {
if (temp.equalsIgnoreCase("")) {
row.add(new Double(0.0));
} else {
row.add(new Double(temp.trim()));
}
} catch (NumberFormatException E) {
System.out.println("Opps there is a mistake "
+ "I was expecting a number and I found: " + temp);
System.out.println("This row will be ignored");
// break;
}
} else {
if (temp.equalsIgnoreCase("")) {
row.add((" "));
} else {
row.add(temp);
}
}
j++;
}
if (row.size() == numberOfColumns) {
table.add(row);
}
}// close for while
inputStream.close();
}
homework?
Here's a clue on how to think about it:
main:
start loop
start
do stuff
set ok to end
catch exception
set not ok to end
loop if not ok to end
I'm not sure if you meant this, but the following code will run again and again until it succeeds (as in: doesn't throw an exception):
public static void main(String[] args){
while(true){
try{
// execute your code
break; // if successful, exit loop
}catch(SomeException e){
// handle exception
}catch(SomeOtherException e){
// handle exception
}finally{
// clean up, if necessary
}
}
}
Note: while(true) is an awful construct that I'm sure your teachers won't like. Perhaps you'll find a better way to rephrase that.
This is a bit of a hack but you could try calling the main method again, passing the arguments. As long as you didn't modify the string array of arguments, just call main(args); from a try/catch block in the main routine. Of course, if the exception keeps happening you'll loop infinitely and blow the stack:P

Categories