Can i do multiple switch case in 1 method in java? - java

I'm trying to create a program for a competition using java where every participant gets 3 tries and the final result is the addition of all of those tries. In every try the participants may hit target 1-10 where target 1=100 points and target 10=10 points with the default value of 0.
The program will request for the target hit at the main class and insert that into the competition class where switch cases will happen to determine the points they get. The point i'm confused about it, how do i do switch cases for all 3 tries? I've tried making each of them individually within a method and then calling them from another method to get the total but it either displays 0 or the total of the target instead.
Here is what i've tried so far:
class Arrow {
private int test1;
private int test2;
private int test3;
private int end1;
public int nl1, nl2, nl3;
//constructor
public Arrow() {
}
public Arrow(int test1, int test2, int test3) {
this.test1 = test1;
this.test2 = test2;
this.test3 = test3;
this.end1 = setEnd1();
}
//setter
public void setScore(int test1, int test2, int test3) {
this.test1 = test1;
this.test2 = test2;
this.test3 = test3;
this.end1 = setEnd1();
}
public void setC1(int test1) {
this.test1 = test1;
}
public void setC2(int test2) {
this.test2 = test2;
}
public void setC3(int test3) {
this.test3 = test3;
}
public int setScore(int i, int test1, int test2, int test3) {
nl1 = switch (test1) {
case 1 -> 100;
case 2 -> 90;
case 3 -> 80;
case 4 -> 70;
case 5 -> 60;
case 6 -> 50;
case 7 -> 40;
case 8 -> 30;
case 9 -> 20;
case 10 -> 10;
default -> 0;
};
nl2 = switch (test2) {
case 1 -> 100;
case 2 -> 90;
case 3 -> 80;
case 4 -> 70;
case 5 -> 60;
case 6 -> 50;
case 7 -> 40;
case 8 -> 30;
case 9 -> 20;
case 10 -> 10;
default -> 0;
};
nl3 = switch (test3) {
case 1 -> 100;
case 2 -> 90;
case 3 -> 80;
case 4 -> 70;
case 5 -> 60;
case 6 -> 50;
case 7 -> 40;
case 8 -> 30;
case 9 -> 20;
case 10 -> 10;
default -> 0;
};
return 0;
}
private int setEnd1() {
return (nl1+nl2+nl3);
}
//getter
public int getC1() {
return test1;
}
public int getC2() {
return test2;
}
public int getC3() {
return test3;
}
//hitung nilai akhir
public int getEnd1() {
return end1;
}
}
class Arrow1 extends Arrow{
private Use ps;
private Arrow[] score;
public Arrow1() {
}
public Panah getScore(int i) {
Arrow nl = new Arrow();
nl.setScore(getC1(), getC2(), getC3());
return nl;
}
}
I tried changing the return (nl1+nl2+nl3); to return (getC1() + getC2() + getC3()) which resulted in the total amount of tries being displayed instead (for example if test1=1, test2=2, test3=3, displayed will be 6). From that i believe the main class is already fine as it has inserted the amount of tries and displayed the result correctly, it's just the switch cases that needs fixing. Can someone explain to me what i did wrong there? Or is this question still too vague?
static void Score1() {
System.out.println("Scores");
System.out.println("======================================================");
Scanner objN = new Scanner(System.in);
for (int i = 0; i < b; i++) {
for (int j = 0; j < a; j++) {
Use ps = lhs[j].getPs();
String name = ps.getName();
String nr = ps.getNr();
System.out.println("Name: " + name + " Number: " + nr);
System.out.print("Input for try 1 : ");
int test1= objN.nextInt();
System.out.print("Input for try 2 : ");
int test2= objN.nextInt();
System.out.print("Input for try 3 : ");
int test3= objN.nextInt();
lhs[j].setScore(test1, test2, test3);
System.out.println("======================================================");
}
}
}

There's many things wrong and I'm not entirely sure what kind of misunderstanding caused them, so I'll just list them as I see them:
your setScore and setEnd1 methods don't actually set anything. They should be called something like calculateScore or calculateEnd.
your setScore method takes test1, test2 and test3 as parameters even though those are already fields. Usually you want to do one or the other, doing both is confusing.
your setScore method is defined to return int but doesn't ever return anything other than 0
you call the setEnd1 method from your constructor, which adds nl1, nl2 and nl3, but those haven't been set at this point
Your Arrow1 class extends Arrow which seems wrong: there is no obvious reason to duplicate all those fields and it's probably a mistake.
You call getC1(), getC2() and getC3() in Arrow1.getScore() but the variables behind those methods have never been initialized (unless that happens in the code that we don't see).

Related

Outputs 2147483647 as a distance in final answer in Dijkstra

The user will be asked what path and what distance. Then it'll compute the shortest distance using Dijkstra's algorithm. The problem is some distance and paths are wrong. There are distances that has 2147483647 and its path is null. The algo works perfectly with zero as a starting point. How do i fix it?
If the user inputs
Enter first path: 0
Enter second path: 1
Enter distance: 1
Do you want to add path again? y
Enter first path: 1
Enter second path: 3
Enter distance: 2
Do you want to add path again? y
Enter first path: 3
Enter second path: 5
Enter distance: 4
Do you want to add path again? y
Enter first path: 1
Enter second path: 2
Enter distance: 3
Do you want to add path again? y
Enter first path: 0
Enter second path: 2
Enter distance: 8
Do you want to add path again? y
Enter first path: 0
Enter second path: 4
Enter distance: 9
Do you want to add path again? n
V D P
0 2147483647null //this part should be 1 and the path is 1-0
1 0null
2 31 - 2
3 21 - 3
4 2147483647null // this part should be 10 and the path is 0-4
5 63 - 5
=========================================================================
import java.util.*;
public class DijkstraAlgo {
final static int VERTICES = 6;
public static int minDistance(int distance[], Boolean shortestPath[]){
int minDist = Integer.MAX_VALUE;
int minIndex = -1;
for(int i = 0;i < VERTICES;i++){
if(shortestPath[i] == false && distance[i] <= minDist){
minDist = distance[i];
minIndex = i;
}
}
return minIndex;
}
public static void dijkstra(int path[][], int startingPoint){
int shortestDist[] = new int[VERTICES];
Boolean shortestPath[] = new Boolean[VERTICES];
String paths[] = new String[VERTICES];
for(int i = 0;i < VERTICES;i++){
shortestDist[i] = Integer.MAX_VALUE;
shortestPath[i] = false;
}
shortestDist[startingPoint] = 0;
for(int ctr = 0;ctr < VERTICES - 1;ctr++){
int index = minDistance(shortestDist, shortestPath);
shortestPath[index] = true;
for(int j = 0;j < VERTICES;j++){
if(!shortestPath[j] && path[index][j] != 0 && shortestDist[index] != Integer.MAX_VALUE && shortestDist[index] + path[index][j] < shortestDist[j]){
shortestDist[j] = shortestDist[index] + path[index][j];
paths[j] = Integer.toString(index) + " - " + " " + Integer.toString(j);
System.out.println(shortestDist[j]);
}
}
}
printAnswer(shortestDist, VERTICES, paths);
}
public static void printAnswer(int distance[], int vertices, String paths[]){
System.out.println("V D P");
for(int i = 0; i < VERTICES; i++)
System.out.println(i + " " + distance[i] + paths[i]);
}
public static void main(String args[]){
int start;
int end;
int path[][] = new int[6][6];
int distance;
Scanner input = new Scanner(System.in);
String choose;
boolean ans = true;
while(ans == true){
System.out.print("Enter first path: ");
start = input.nextInt();
System.out.print("Enter second path: ");
end = input.nextInt();
System.out.print("Enter distance: ");
distance = input.nextInt();
path[start][end] = distance;
System.out.print("Do you want to add path again? ");
choose = input.next();
if(choose.equals("y") || choose.equals("Y"))
ans = true;
else if(choose.equals("n") || choose.equals("N"))
ans = false;
else
System.out.println("Invalid input!");
}
dijkstra(path, 1);
}
}
I don't know what's wrong with your code, being honest. I don't plan to go through and try to debug it either; Eclipse can do that for you (as I linked in the comment).
What I will provide is a better means of approaching this, IMO. Storing your data in arrays of integers is a convoluted approach that's going to lead to confusion (as is evident here). One of the main benefits of using an object-oriented language like Java is that you can form your data in a coherent manner relevant to the context.
Consider creating two classes:
public class DijkstraNode {
private int label;
private List<DijkstraLink> links;
public DijkstraNode(int label) {
this.label = label;
links = new ArrayList<DijkstraLink>();
}
public int getLabel() {
return label;
}
public void addLink(DijkstraLink link) {
links.add(link);
}
public List<DijkstraLink> getLinks() {
return links;
}
}
...
public class DijkstraLink {
private DijkstraNode node;
private int distance;
public DijkstraLink(DijkstraNode node, int distance) {
this.node = node;
this.distance = distance;
}
public DijkstraNode getLinkedNode() {
return node;
}
public int getDistance() {
return distance;
}
}
Whenever you create a bi-directional link between nodes:
public void createTwoWayLink(DijkstraNode first, DijkstraNode second, int distance) {
first.addLink(new DijkstraLink(second, distance));
second.addLink(new DijkstraLink(first, distance));
}
Then evaluating Dijkstra's becomes a much simplier task:
public void computeDijkstras(DijkstraNode startNode, List<DijkstraNode> nodes) {
Map<DijkstraNode, Integer> distances = new HashMap<DijkstraNode, Integer>();
for (DijkstraNode node : nodes) {
if (node != startNode) {
distances.put(node, Integer.MAX_VALUE);
}
else {
distances.put(node, 0);
}
}
List<DijkstraNode> computedNodes = new ArrayList<DijkstraNode>();
DijkstraNode toEval = computeSmallestUncomputedNode(distances, computedNodes); // TODO
while (toEval != null) {
for (DijkstraLink link : toEval.getLinks()) {
if (computedNodes.contains(link.getLinkedNode()) {
continue;
}
int evalDist = link.getDistance() + distances.get(toEval);
if (evalDist < distances.get(link.getLinkedNode())) {
distances.put(link.getLinkedNode(), evalDist);
}
}
computedNodes.add(toEval);
toEval = computeSmallestUncomputedNode(distances, computedNodes);
}
// distances computed; do whatever.
}
This isn't a complete implementation. I didn't want to do your homework for you. However, I did want to include enough of an example of how capitalizing on object-oriented design and internal Java data structures (such as the List and Map objects used) make execution much more coherent, and, thus, easier to work with. Hope this helps.

Errors : Exception in thread "main" java.lang.Error: Unresolved compilation problems

I was watching a Java tutorial for beginners, and while writing the code I got a few errors:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error, 'for each' statements are only available if source level is 1.5 or greater
Arrays cannot be resolved
Arrays cannot be resolved
Arrays cannot be resolved
at Animal.main(Animal.java:389)
My code is:
Animal.Java:
import java.util.Scanner;
// A class defines the attributes (fields) and capabilities (methods) of a real world object
public class Animal {
// static means this number is shared by all objects of type Animal
// final means that this value can't be changed
public static final double FAVNUMBER = 1.6180;
// Variables (Fields) start with a letter, underscore or $
// Private fields can only be accessed by other methods in the class
// Strings are objects that hold a series of characters
private String name;
// An integer can hold values from -2 ^ 31 to (2 ^ 31) -1
private int weight;
// Booleans have a value of true or false
private boolean hasOwner = false;
// Bytes can hold the values between -128 to 127
private byte age;
// Longs can hold the values between -2 ^ 63 to (2 ^ 63) - 1
private long uniqueID;
// Chars are unsigned ints that represent UTF-16 codes from 0 to 65,535
private char favoriteChar;
// Doubles are 64 bit IEEE 754 floating points with decimal values
private double speed;
// Floats are 32 bit IEEE 754 floating points with decimal values
private float height;
// Static variables have the same value for every object
// Any variable or function that doesn't make sense for an object to have should be made static
// protected means that this value can only be accessed by other code in the same package
// or by subclasses in other packages
protected static int numberOfAnimals = 0;
// A Scanner object allows you to except user input from the keyboard
static Scanner userInput = new Scanner(System.in);
// Any time an Animal object is created this function called the constructor is called
// to initialize the object
public Animal(){
// Shorthand for numberOfAnimals = numberOfAnimals + 1;
numberOfAnimals++;
int sumOfNumbers = 5 + 1;
System.out.println("5 + 1 = " + sumOfNumbers);
int diffOfNumbers = 5 - 1;
System.out.println("5 - 1 = " + diffOfNumbers);
int multOfNumbers = 5 * 1;
System.out.println("5 * 1 = " + multOfNumbers);
int divOfNumbers = 5 / 1;
System.out.println("5 / 1 = " + divOfNumbers);
int modOfNumbers = 5 % 3;
System.out.println("5 % 3 = " + modOfNumbers);
// print is used to print to the screen, but it doesn't end with a newline \n
System.out.print("Enter the name: \n");
// The if statement performs the actions between the { } if the condition is true
// userInput.hasNextLine() returns true if a String was entered in the keyboard
if(userInput.hasNextLine()){
// this provides you with a way to refer to the object itself
// userInput.nextLine() returns the value that was entered at the keyboard
this.setName(userInput.nextLine());
// hasNextInt, hasNextFloat, hasNextDouble, hasNextBoolean, hasNextByte,
// hasNextLong, nextInt, nextDouble, nextFloat, nextBoolean, etc.
}
this.setFavoriteChar();
this.setUniqueID();
}
// It is good to use getter and setter methods so that you can protect your data
// In Eclipse Right Click -> Source -> Generate Getter and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public boolean isHasOwner() {
return hasOwner;
}
public void setHasOwner(boolean hasOwner) {
this.hasOwner = hasOwner;
}
public byte getAge() {
return age;
}
public void setAge(byte age) {
this.age = age;
}
public long getUniqueID() {
return uniqueID;
}
// Method overloading allows you to accept different input with the same method name
public void setUniqueID(long uniqueID) {
this.uniqueID = uniqueID;
System.out.println("Unique ID set to: " + this.uniqueID);
}
public void setUniqueID() {
long minNumber = 1;
long maxNumber = 1000000;
// Generates a random number between 1 and 1000000
this.uniqueID = minNumber + (long)(Math.random() * ((maxNumber - minNumber) + 1));
// You can cast from one primitive value into another by putting what you want between ( )
// (byte) (short) (long) (double)
// (float), (boolean) & (char) don't work.
// (char) stays as a number instead of a character
// You convert from a primitive to a string like this
String stringNumber = Long.toString(maxNumber);
// Byte.toString(bigByte); Short.toString(bigShort); Integer.toString(bigInt);
// Float.toString(bigFloat); Double.toString(bigDouble); Boolean.toString(trueOrFalse);
// You convert from a String to a primitive like this
int numberString = Integer.parseInt(stringNumber);
// parseShort, parseLong, parseByte, parseFloat, parseDouble, parseBoolean
System.out.println("Unique ID set to: " + this.uniqueID);
}
public char getFavoriteChar() {
return favoriteChar;
}
public void setFavoriteChar(char favoriteChar) {
this.favoriteChar = favoriteChar;
}
public void setFavoriteChar() {
int randomNumber = (int) (Math.random() * 126) + 1;
this.favoriteChar = (char) randomNumber;
// if then else statement
// > < == != >= <=
if(randomNumber == 32){
System.out.println("Favorite character set to: Space");
} else if(randomNumber == 10){
System.out.println("Favorite character set to: New Line");
} else {
System.out.println("Favorite character set to: " + this.favoriteChar);
}
// Logical operators
// ! : Converts the boolean value to its right to its opposite form ie. true to false
// & : Returns true if boolean value on the right and left are both true (Always evaluates both boolean values)
// && : Returns true if boolean value on the right and left are both true (Stops evaluating after first false)
// | : Returns true if either boolean value on the right or left are true (Always evaluates both boolean values)
// || : Returns true if either boolean value on the right or left are true (Stops evaluating after first true)
// ^ : Returns true if there is 1 true and 1 false boolean value on the right or left
if((randomNumber > 97) && (randomNumber < 122)){
System.out.println("Favorite character is a lowercase letter");
}
if(((randomNumber > 97) && (randomNumber < 122)) || ((randomNumber > 64) && (randomNumber < 91))){
System.out.println("Favorite character is a letter");
}
if(!false){
System.out.println("I turned false to " + !false);
}
// The ternary operator assigns one or another value based on a condition
int whichIsBigger = (50 > randomNumber) ? 50 : randomNumber;
System.out.println("The biggest number is " + whichIsBigger);
// The switch statement is great for when you have a limited number of values
// and the values are int, byte, or char unless you have Java 7 which allows Strings
switch(randomNumber){
case 8 :
System.out.println("Favorite character set to: Backspace");
break;
case 9 :
System.out.println("Favorite character set to: Horizontal Tab");
break;
case 10 :
case 11 :
case 12 :
System.out.println("Favorite character set to: Something else weird");
break;
default :
System.out.println("Favorite character set to: " + this.favoriteChar);
break;
}
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
protected static int getNumberOfAnimals() {
return numberOfAnimals;
}
// Since numberOfAnimals is Static you must set the value using the class name
public void setNumberOfAnimals(int numberOfAnimals) {
Animal.numberOfAnimals = numberOfAnimals;
}
protected static void countTo(int startingNumber){
for(int i = startingNumber; i <= 100; i++){
// continue is used to skip 1 iteration of the loop
if(i == 90) continue;
System.out.println(i);
}
}
protected static String printNumbers(int maxNumbers){
int i = 1;
while(i < (maxNumbers / 2)){
System.out.println(i);
i++;
// This isn't needed, but if you want to jump out of a loop use break
if(i == (maxNumbers/2)) break;
}
Animal.countTo(maxNumbers/2);
// You can return a value like this
return "End of printNumbers()";
}
protected static void guessMyNumber(){
int number;
// Do while loops are used when you want to execute the code in the braces at least once
do {
System.out.println("Guess my number up to 100");
// If what they entered isn't a number send a warning
while(!userInput.hasNextInt()){
String numberEntered = userInput.next();
System.out.printf("%s is not a number\n", numberEntered);
}
number = userInput.nextInt();
}while(number != 50);
System.out.println("Yes the number was 50");
}
// This will be used to demonstrate polymorphism
public String makeSound(){
return "Grrrr";
}
// With polymorphism we can refer to any Animal and yet use overridden methods
// in the specific animal type
public static void speakAnimal(Animal randAnimal){
System.out.println("Animal says " + randAnimal.makeSound());
}
// public allows other classes to use this method
// static means that only a class can call for this to execute
// void means it doesn't return a value when it finishes executing
// This method can except Strings that can be stored in the String array args when it is executed
public static void main(String[] args){
Animal theDog = new Animal();
System.out.println("The animal is named " + theDog.getName());
System.out.println(Animal.printNumbers(100));
Animal.countTo(100);
Animal.guessMyNumber();
// An array is a fixed series of boxes that contain multiple values of the same data type
// How you create arrays
// int[] favoriteNumbers;
// favoriteNumbers = new int[20];
int[] favoriteNumbers = new int[20];
favoriteNumbers[0] = 100;
String[] stringArray = {"Random", "Words", "Here"};
// for(dataType[] varForRow : arrayName)
for(String word : stringArray)
{
System.out.println(word);
}
// This is a multidimensional array
String[][][] arrayName = { { { "000" }, { "100" }, { "200" }, { "300" } },
{ { "010" }, { "110" }, { "210" }, { "310" } },
{ { "020" }, { "120" }, { "220" }, { "320" } }};
for(int i = 0; i < arrayName.length; i++)
{
for(int j = 0; j < arrayName[i].length; j++)
{
for(int k = 0; k < arrayName[i][j].length; k++)
{
System.out.print("| " + arrayName[i][j][k] + " ");
}
}
System.out.println("|");
}
// You can copy an array (stringToCopy, indexes to copy)
String[] cloneOfArray = Arrays.copyOf(stringArray, 3);
// You can print out the whole array
System.out.println(Arrays.toString(cloneOfArray));
// Returns the index or a negative number
System.out.println(Arrays.binarySearch(cloneOfArray, "Random"));
}
}
Dog.Java
public class Dog extends Animal{
public Dog() {
}
// You can override Animal methods
public String makeSound(){
return "Woof";
}
public static void main(String[] args) {
Dog fido = new Dog();
fido.setName("Fido");
System.out.println(fido.getName());
}
}
Cat.java
public static void main(String[] args) {
Animal fido = new Dog();
Animal fluffy = new Cat();
// We can have an array of Animals that contain more specific subclasses
// Any overridden methods are used instead because of polymorphism
Animal[] theAnimals = new Animal[10];
theAnimals[0] = fido;
theAnimals[1] = fluffy;
System.out.println("Fido says " + theAnimals[0].makeSound());
System.out.println("Fluffy says " + theAnimals[1].makeSound());
// We can also pass subclasses of Animal and they just work
speakAnimal(fluffy);
}
}
I saw a few other answers here and read that I had to add import java.util.Scanner;
Which i already had..
Please tell me the problem in the code...
Thanks!
The line for(String word : stringArray) is a so called "for each" loop - a convenience added in Java 1.5.
But it seems your compiler is configued below 1.5, so it does not support the for each loop.
So you can either:
change the compiler level
change the loop to be 1.4 compatible to
String[] stringArray = {"Random", "Words", "Here"};
String word;
for(int i = 0; i < stringArray.length; i++)
{
word = stringArray[i];
System.out.println(word);
}
(in fact this is what the compiler would do for you...)
The issue is clear from the error message -
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error, 'for each' statements are only available if source level is 1.5 or greater
You need java 1.5 or higher, You can download latest Java JDKs's from here
Or you can do as ultimate said, and make your loops compatible for lower versions of java (though I would suggest upgrading to above 1.5 , 1.5 is like very very old version anyway).

Adding data to a program if exist; else do generate random data in java

I have a math program that shows random math problems, when you click to see the next answer the next answer appears.
I have added a method which uploads a file called upload.txt
I want my program to run the math problems in this file instead of running the random
math problems if the file exist. If not I want the program to run the current way which is running the random math problems.
My current method for adding the text file is not 100 percent accurate.
I wont to just take the problems written in the file to be added. I got it working just uploading numbers to the command prompt by using code from another thread on StackOverflow.
random math problems class
import java.util.Random;
public class MathProblems {
private static final int MAX_NUMBER = 1000;
private static final Random random = new Random();
private double expected = 0;
private String question = "";
public void run() {
final int a = random.nextInt(MAX_NUMBER);
final int b = random.nextInt(MAX_NUMBER);
final int type = random.nextInt(4);
switch (type) {
case 0:
add(a, b);
break;
case 1:
subtract(a, b);
break;
case 2:
multiply(a, b);
break;
case 3:
divide(a, b);
break;
}
}
private void add(final int a, final int b) {
expected = a + b;
askQuestion(a + " + " + b + " = ");
}
private void subtract(final int a, final int b) {
expected = a - b;
askQuestion(a + " - " + b + " = ");
}
private void multiply(final int a, final int b) {
expected = a * b;
askQuestion(a + " * " + b + " = ");
}
private void divide(final int a, final int b) {
expected = (double)a / b;
askQuestion(a + " / " + b + " = ");
}
private void askQuestion(final String question) {
this.question = question;
}
public String getQuestion() {
return question;
}
#Override
public String toString(){
return Double.toString(expected);
}
}
Driver Class
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import javax.swing.*;
public class Driver extends MathProblems {
MathProblems problems = new MathProblems();
Scanner textfile;
String s = "Welcome Students!";
String b = "Start!";
private JFrame f;
private JPanel p;
JFrame frame = new JFrame();
JButton b1 = new JButton(b);
JLabel jl = new JLabel(s);
int i;
private int clicked;
public Driver() {
gui();
}
public void gui() {
f = new JFrame("Flash Card Program");
p = new JPanel();
f.setLayout(new GridLayout(2, 1));
f.add(jl);
f.add(p);
p.setLayout(new GridLayout(2, 1));
p.add(b1);
jl.setHorizontalAlignment(JLabel.CENTER);
// pack the frame for better cross platform support
f.pack();
// Make it visible
f.setVisible(true);
f.setSize(500, 400); // default size is 0,0
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (b1.getText().equals("Click For Answer")) {
jl.setText(problems.toString());
b = "Next Question";
b1.setText(b);
} else {
problems.run();
jl.setText(problems.getQuestion());
b = "Click For Answer";
b1.setText(b);
}
}
});
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (clicked++ == 10) {
Object[] options = { "No, thanks", "Yes, please" };
int response = JOptionPane.showOptionDialog(frame,
"Would you like more math questions? ",
"Math Questions", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options,
options[1]);
if (response == 1)
clicked = 0; // reset
else
System.exit(0);
}
}
});
}
static void filereader(Scanner textfile) {
int i = 0;
int sum = 0;
while(i <= 19)
{
int nextInt = textfile.nextInt();
System.out.println(nextInt);
sum = sum + nextInt;
i++;
}
}
public static void main(String[] args) throws IOException {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Driver();
Scanner textfile = null;
try {
textfile = new Scanner(new File("upload.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
filereader(textfile);
}
});
}
}
.txt file
1 + 1
2 + 2
3 + 3
4 + 4
5 + 5
6 + 6
7 + 7
8 + 8
9 + 9
10 + 10
You need to define a global vector of question values for each of a and b. A nicer way to do this is to define a class called "OneProblem" which has members for a, b, and op. You create a single 'Vector<OneProblem>' and as you read the file you create a OneProblem object for each line of the source. Then, at run time you either pick a random math problem, or loop through all the OneProblem objects, or you generate a completely random OneProblem from the random number generator. Something like:
class OneProblem {
public int a = 0;
public int b = 0;
public int op = 0;
public OneProblem(int _a, int _op, int _b) {
a =_a;
b = _b;
op = _op;
}
}
class MathProblems {
Vector<OneProblem> problems = new Vector<OneProblem>();
//...lot of your other code here as well....
workQuestion(OneProblem problem) {
switch (problem.op) {
case 0:
add(problem.a, problem.b);
break;
case 1:
subtract(problem.a, problem.b);
break;
case 2:
multiply(problem.a, problem.b);
break;
case 3:
divide(problem.a, problem.b);
break;
}
}
}
You file reader needs to read each line and parse the first and second values out of the line, as well as (I presume) the operand between them. Read the line, and search for the operand, and separate the integer before and the integer after. Then as you read each line, construct an instance of OneProblem to match each line. Now you are set to run.
When presenting the math questions, you loop through the values from i=0 to i<problems.size(). If there was no file read, those vectors will have no entries and so it will fall through. After you finish the vectors, or if the vectors are empty, present math questions with random values.
if (problems.size()>0) {
for (int i=0; i<problems.size(); i++) {
OneProblem selProblem = problems.get(i);
workQuestion(selProblem);
}
}
else {
workQuestion(new OneProblem({{random a}}, {{random op}}, {{random b}}));
}
Fill in the appropriate method for 'askQuestion'. This is represented above as a loop, but maybe you want to pick a random one of the test values for presentation? Then pick a reasonable random value for i in that range, and get the problem out of the vectors.
In your filereader method, you have this line, in a loop:
int nextInt = textfile.nextInt();
But the sample text that you show contains '+' characters between your numbers, and I see no code present to take that into account.
To fix, you can either define '+' as a delimiter on your Scanner object, or make sure your loop reads it as a string.

How can I check for previous elements and the elements added on to an arraylist in java and do error checks

I have a code that atm checks if the array list has reached the size or not, if no I want it to to perform checks before adding anything else to the list. I have attempted it but cannot figure out why it does not work. below is my method.
private static void addToArrayList(String fruit, double no1, int no2, int no3) throws Exception {
try {
if (arraysList.size() <= 5) {
int count = 0;
for (StoringArray item : arraysList)
if (item.equals("Apple")) {
++count;
if (count > 2)
throw new IllegalArgumentException( "You cannot add more than 2 apples." ); //Instead of this I want a Joption pane pop up to give this error if it applies, but at the moment I am not sure but this code with the current code I have is not working.
}
{
if ( arraysList.get( arraysList.size() - 1 ).equals("Banana") )
throw new IllegalArgumentException( "You have just added this please add something else and then add this if you want." ); }
arraysList.add(new StoringArray(fruit, no1, no2, no3));
}else{
JOptionPane.showMessageDialog(contentPane, "You cannot added mroe than 6 elements.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
I want the error messages to appear in a Joption Pane and I want to check the following errors;
Say the list includes Apples, Bananas, Oranges, PineApples, Grapes
1; I want to check whether the user given parameters no1, no2 and no3 meet the conditon I want i.e.
for (StoreCommands item : commandsList)
if (item.equals("Apple")) {
}no1 need to be greater then 0, no2 needs to be less than 10 and no 3 needs to be less than 15.
2; If user tries to add two apples together in any order it should not be allowed, directly after one another.
3; If the user adds 2 Oranges, they should not be allowed and error message saying this should come up in JOption Pane message box.
If all the conditions are the array values get added to the array list. Thanks I hope I explained myself properly, I have been working on this problem for ages and cannot figure it out for some reason. Thanks again.
----------------edited-----------------with class that stores the arrayList.
public class StoreCommands {
public String toString(){
return Name + " " + Number1 + " " + Number2 + " " + Number3;
}
private String Name;
private int Number1;
private int Number2;
private int Number3;
public String getCommand() {
return Name;
}
public double getcommandNOS() {
return Number1;
}
public int getcommandVLW() {
return Number2;
}
public int getcommandVRW() {
return Number3;
}
public StoringArray(String fruitsNames, double fno1, int fno2, int fno3) throws Exception{
Name = fruitsNames;
Number1 = (int) fno1;
Number2 = fno1;
Number3 = fno3;
}
}
There are also some problems in your StoreCommands (?StoringArray) class and it doesn't compile.
1) The constructor is called StoringArray while the class is called StoreCommands.
2) You shouldn't accept a double value as second parameter and cast it to an int.
3) "Number2 = fno1;" inside the constructor should be "Number2 = fno2;" instead
4) You cannot compare your StoreCommands instance to a String value using equals. You need to compare to the String returned from the getCommand() method:
if (item.getCommand().equals("Apple"))
no1 need to be greater then 0, no2 needs to be less than 10 and no 3 needs to be less than 15. 2; If user tries to add two apples together in any order it should not be allowed, directly after one another. 3; If the user adds 2 Oranges, they should not be allowed and error message saying this should come up in JOption Pane message box.
perhaps something like this would do the job:
public static String getErrorMessage(List<StoreCommands> commands, String fruitsName, int no1, int no2, int no3) {
if (no1 <= 0 || no2 >= 10 || no3 >= 15) {
return "Some Error message...";
}
String previous = null;
int orangeCount = 0;
for (StoreCommands c : commands) {
if (fruitsName.equals("Apple") && previous != null && previous.equals("Apple")) {
return "Some Error message...";
} else if (c.getCommand().equals("Orange")) {
orangeCount++;
}
previous = c.getCommand();
}
return fruitsName.equals("Orange") && orangeCount == 1 ? "Some Error message" : null;
}
your class name is StoreCommands
but you have declared constructor named StoringArray
public StoringArray(String fruitsNames, double fno1, int fno2, int fno3) throws Exception
{
Name = fruitsNames;
Number1 = (int) fno1;
Number2 = fno1;
Number3 = fno3;
}
replace this by
public StoreCommands(String fruitsNames, double fno1, int fno2, int fno3) throws Exception
{
Name = fruitsNames;
Number1 = fno1; //you do not need to cast int because both are int
Number2 = fno1;
Number3 = fno3;
}
in for loop change the conditional logic
for (StoringArray item : arraysList)
if (item.getCommand().equals("Apple"))
{
}
.. it should works now if your other logic and code is ok

Want only one warning after complete iteration over lists. Not one warner per iteration

The entirety of my programs are below.
The problem I am having is that my stdout gets flooded by the error messages produced by this particular line of code.
for(int x = 0; x < 3; x++)
{
for(int xx = 0; xx < 6; xx++)
{
if(toppings[x].equalsIgnoreCase(validToppings[xx]))
{price += 0.75;} else {System.out.println("Error in Pizza class: Attempt to set invalid pizza topping " + toppings[x]);};
}
}
I would rather not re-write my code that I spent lots of time perfecting, but if I must use a switch statement or something of the like to get a concise error message I will. Although I think my current method is best.
The following is the test for the class,
public class TestPizza
{
public static void main(String args[])
{
int x;
String t1[] = {"Mushrooms", "Onions", ""};
String t2[] = {"Pepperoni", "Mushrooms", ""};
String t3[] = {"Pepperoni", "Mushrooms", "Onions"};
String t4[] = {"Sausage", "", ""};
Pizza one = new Pizza();
Pizza two = new Pizza();
Pizza three = new Pizza();
Pizza four = new Pizza();
one.setSize(12);
one.addTopping(t1);
one.showValues();
two.setSize(8);
two.addTopping(t2);
two.showValues();
three.setSize(16);
three.addTopping(t3);
three.showValues();
four.setSize(20);
four.addTopping(t4);
four.showValues();
}
}
This is the class.
// This custom class is used to create Pie objects
// It stores the data about the Pie in four variables:
// size, price, type and baked
// It lets the program that creates the Pie object set these values using four methods:
// setSize, setPrice, setType and bake
public class Pizza
{
// Declare four variables that can store the values for each pie
// Each Pie object will have their own, separate copy of these variables 12.
private int size;
private double price;
private boolean baked;
private int x;
private int xx;
private String validToppings[] = {"mushrooms", "pepperonis", "onions", "mushroom", "pepperoni", "onion"};
private String toppings[] = new String[3];
// The "constructor" method is called when a new pie
// object is first created. We use it to set "default" values.
// Our typical pie is 10 inches, costs $8 and is not baked yet
// We don't yet know what the pie filling will be
Pizza()
{
size = 999;
price = 999;
baked = false;
}
// showValues() is a void method that displays the values of the
// current Pie
public void showValues()
{
System.out.println("Pie Size: " + size);
for(int x = 0; x < 3; x++) {if(toppings[x] != ("")) {System.out.println("With " + toppings[x]);}};
System.out.println("Price of Pie: $" + price + "\n\n");
}
// getSize() returns the size of the pie
public int getSize()
{
return size;
}
// getPrice() returns the price of the pie
public double getPrice()
{
return price;
}
// baked() returns whether or not the pie is baked
public boolean getBaked()
{
return baked;
}
// setSize() assigns a size to the pie
public void setSize(int thisSize)
{
size = thisSize;
switch(size)
{
case 8: price = 10.00; break;
case 12: price = 14.00; break;
case 16: price = 18.00; break;
default: System.out.println("Error in Pizza class: Attempt to set invalid Pizza size."); break;
}
}
// setPrice() assigns a price to the pie
public void addTopping(String programToppings[])
{
for(int x = 0; x < 3; x++)
{
toppings[x] = programToppings[x];
}
for(int x = 0; x < 3; x++)
{
toppings[x] = toppings[x].toLowerCase();
}
for(int x = 0; x < 3; x++)
{
for(int xx = 0; xx < 6; xx++)
{
if(toppings[x].equalsIgnoreCase(validToppings[xx]))
{price += 0.75;} else {System.out.println("Error in Pizza class: Attempt to set invalid pizza topping " + toppings[x]);};
}
}
}
public void bake()
{
baked = true;
};
}
You should use a boolean variable isValid, which is initially set to false. As soon as you find a match, set it to true. After all the iterations are complete, ifisValid is still false, then print the error message.
boolean error = false;
for(int x = 0; x < 3; x++)
{
for(int xx = 0; xx < 6; xx++)
{
if(toppings[x].equalsIgnoreCase(validToppings[xx]))
{price += 0.75;} else {error = true;};
}
}
if(error){
System.out.println("Error in Pizza class: Attempt to set invalid pizza topping");
}
If you want to keep the topping information aswell, you need to store each topping in a list (just add each time error is set to true), then iterate over that list in the if(error) statement.
You may not want to keep looping if there has been an error. I would also use a Set for valid toppings.
// set globally.
Set<String> validTopppingSet = new HashSet<String>();
for(String t: validToppings) validToppingSet.add(t.toLowerCase());
// when checking the toppings.
for(String topping: topping) {
if (validToppings.contains(topping.toLowerCase())) {
price += 0.75;
} else {
price = Double.NaN;
System.out.println("Error in Pizza class: Attempt to set invalid pizza topping: " + topping); // it useful to know what was invalid.
break;
}
}

Categories