How to assign each column of an array to a specific variable? - java

Is this the right way of assigning each column in my data file to a particular variable?
public static void main(String[] args) {
//specifying the path to file
String datafile = " C:\\Users\\rez\\Desktop\\sol_2.mcmc";
//reading the file
double[][] mydata = FileReadingTools.getDoubleArray(datafile);
double P_0; //days
double M_0; // in days
double e_0;
double w_0 = Math.toRadians(0);
double[][] list = new double[3000][50];
for (int sol = 0; sol < 3000; sol++) {
list[sol][0] = P_0;
list[sol][2] = M_0;
list[sol][3] = e_0;
list[sol][4] = w_0;
System.out.println(P_0 + " " + M_0);
}

I believe you have swapped the left and right with your variable assignments. You want to assign the values from the array. Also, please use more descriptive variable names. I think you wanted something like,
for (int sol = 0; sol < mydata.length; sol++) {
P_0 = mydata[sol][0]; // mydata v-- as noted in the comments. ---v
M_0 = mydata[sol][2];
e_0 = mydata[sol][3];
w_0 = mydata[sol][4];
Alternatively, you could use printf and access the array directly with something like
System.out.printf("%.2f %.2f", mydata[sol][0], mydata[sol][2]);

Related

Java - How can I print out a value as a word after BubbleSorting?

I used integer so that I can write out Numbers as an input, but now i would like the programm to output the number as Words again.
public class KartenSort {
private int zwei = 2;
private int drei = 3;
private int vier = 4;
private int fuenf = 5;
public int[] liste ={drei,zwei,fuenf,vier};
public int[] sortieren(){
int unsortiert;
for(int sortiert = 0; sortiert < liste.length -1; sortiert++){
if(liste[sortiert] < liste[sortiert+1]){
continue;
}
unsortiert = liste[sortiert];
liste[sortiert] = liste[sortiert+1];
liste[sortiert+1] = unsortiert;
sortieren();
}
return liste;
}
public static void main (String[] args){
KartenSort bs = new KartenSort();
int[] array = bs.sortieren();
for (int sortiert=0;sortiert < array.length; sortiert++){
System.out.println(sortiert + 1 +":" + array[sortiert]);
}
}
}
thank you in advance
In your case you could use Map
Map<Integer,String> numbers = new HashMap<>();
numbers.put(2, "zwei");
numbers.put(3, "drei");
numbers.put(4, "vier");
numbers.put(5, "funf");
for (int sortiert=0;sortiert < array.length; sortiert++){
System.out.println(numbers.get(array[sorted]));
}
The array liste does not contain Strings (what you probably mean by "words").
I think, you wanted to have something like
String[] liste = ...
Your version of liste is
int[] liste = ...
This means it contains integer numbers, not strings. Although you write
int[] liste = {drei,zwei, ...}
the content of the array are still integer numbers. drei is a variable and you will get the value of the variable into the list. The value of drei is the integer value 1.
When you have the value 1 there is no reference back to the name of the variable that had hold it some time ago.

Error: NoSuchElementException when trying to read values from file to array

Okay. So this is the last HW assignment of the semester, I am leaving out a big part of the program because this is the only thing I can't seem to fix. I am setting up my FileInputStream and using a for loop to read values into the array as I have done in the past without problems. For some reason I am getting this exception and can't figure it out. I have looked at plenty of other threads around this exception but likewise, cant seem to figure it out. Please halp.
Here is the code, it compiles;
import java.util.*;
import java.io.*;
public class CollinDunn_1_10 {
// Declare constants
static final int MAX_EMPLOY = 30;
static final String TAB = "\t";
static final String NL = "\n";
static final double IRA_INVEST = .08;
static final double FEDERAL_WITH = .18;
static final double STATE_WITH = .045;
static final double SAVINGS = .10;
public static void main (String [] args) throws Exception {
// I/O String references
final String INPUT = "CollinDunn_1_10_Input.txt";
final String OUTPUT = "CollinDunn_1_10_Output.txt";
// Declare variables
// One-dimensional array for storing employee names
String [] names = new String [MAX_EMPLOY];
// Two-dimensional array for storing employee pay data
// [0] hours worked [1] pay rate [2] gross pay [3] net pay
// [4] savings amount [5] IRA amount [6] taxs withheld
double [][] payInfo = new double [MAX_EMPLOY][6];
// Set up I/O
FileInputStream inputDataFile = new FileInputStream(INPUT);
Scanner inputFile = new Scanner(inputDataFile);
FileWriter outputDataFile = new FileWriter(OUTPUT);
PrintWriter outputFile = new PrintWriter(outputDataFile);
// Read data from the file
readData(inputFile, payInfo, names);
// Test printing to see if values are stored - REMOVE
for (int i = 0; i < MAX_EMPLOY; i++) {
System.out.print(names[i] + TAB + payInfo[i][0] + TAB + payInfo[i][1]);
}
} // End main
// Method for reading file data into the file.
// Data is sorted as (number of hours) (pay rate) (name)
public static void readData (Scanner inputFile, double [][] payInfo, String [] names) {
for (int i = 0; i < MAX_EMPLOY; i++) {
payInfo [i][0] = inputFile.nextDouble();
payInfo [i][1] = inputFile.nextDouble();
names [i] = inputFile.nextLine();
} // End For
return;
} // End readData
} // End Class
*The fields on the text file are as so:
(hours) (pay) (name)
50.00 10.60 Light Karen L
52.00 10.80 Fagan Bert Todd
62.00 12.24 Antrim Forrest N*
The Exception and stack trace:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at CollinDunn_1_10.readData(CollinDunn_1_10.java:56)
at CollinDunn_1_10.main(CollinDunn_1_10.java:42)
You're never checking whether there is a value to retrieve before trying to retrieve it (look up Scanner.hasNextDouble). Since your for-loop goes through MAX_EMPLOY iterations, this exception will occur whenever your input file contains less than MAX_EMPLOY lines of data.
You should everytime check if your tables or your file contains right amounts of elements or if they are big enought. Code should look like:
public static void readData (Scanner inputFile, double [][] payInfo, String [] names) {
Integer payInfoLenght = payInfo.lenght;
Integer namesLenght = names.lenght;
if (MAX_EMPLOY > payInfoLenght || MAX_EMPLOY > namesLenght) {
System.out.println("Wrong size of tabels");
} else {
for (int i = 0; i < MAX_EMPLOY; i++) {
if (inputFile.hasNextDouble()) {
payInfo [i][0] = inputFile.nextDouble();
}
if (inputFile.hasNextDouble()) {
payInfo [i][1] = inputFile.nextDouble();
}
if (inputFile.hasNextLine()) {
names [i] = inputFile.nextLine();
}
}
}
}
And you don't need "return;" at the end of this method becouse this method nothing returns. It's "void" method.

How to get a String array to equal another String array

String[] mySecret;
String[] colours = {"R","Y","Bl","G","O","Pu","Pi","Br"};
public void getuserInput() {
numColours = min + (int)(Math.random() * ((max-min) +1));
numPegs = min + (int)(Math.random() * ((max-min) +1));
}
public void setSecret() {
for (i=0; i<numColours; i++) {
mySecret[i] = colours[new Random().nextInt(colours.length)];
}
}
This is a small part of my code. When I run this, I get a NullPointerException. Is there any other way to get mySecret which is meant to be a string array to contain a specified number of colours but chosen at random from the colours string array. Any help would be appreciated, thanks.
You shoud initialize your array mySecret like this:
String[] colours = {"R","Y","Bl","G","O","Pu","Pi","Br"};
String[] mySecret = new String[colours.length];
You need to read up on the Java language a bit more.
public void setSecret() {
mySecret = new String[numColours];
for ( int i=0; i<numColours; i++) {
mySecret[i] = colours[new Random().nextInt(colours.length)];
}
}

Random method for a quiz

Each method contain a question with multiple choice. When i call the method in the main, i need to shuffle it and make sure there are no repetition.
public static void main(String[] args) {
question_1();
question_2();
question_3();
question_4();
//continue to question 15
question_15();
}
thing that i tried.
int question_A = question_1();
int question_B = question_2();
int question_C = question_3();
int question_D = question_4();
//to question 15
int question_O = question_15();
//then i created an array
int [] question = new int[14];
question[0] = question_A;
question[1] = question_B;
question[2] = question_C;
question[3] = question_D;
//to last array
question[14] = question_O;
//to random it here is the code
Random r = new Random();
for (int counter = 0; counter <10; ++counter){
int swap_Index = r.next Int(15-counter)+counter; //there is an space between next Int, that because i was getting not properly formatted in the edit box
int temp = question[counter];
question[counter] = question[swap_Index];
question[swap__Index] = temp;
int[] question_To_Ask = new int[10];
for (int count = 0; count<10; ++count){
question_To_Ask[count] = question[count];
}
The reason the random does not work is because it starts executing the program at
int question_A = question_1();
for the random, i also tried any way such as Math.random. None of these worked and yeah, please do not use advance technique to solve this problem as i am a beginner.
The easy way to do this is using a list:
List<Question> questions = new ArrayList<Question>();
questions.add(question_1);
questions.add(question_2);
questions.add(question_3);
.....
Collections.shuffle(questions);
See, I dunno what you are doing with all these methods, but let us consider another approach put every question in a database, use a Collection like say hashmap in ur java code access ur database and based on the id of the question u can call whichever question u want to call and for the shuffling part there is a predefined function called shuffle in java, u can use it to shuffle ur question collection. Just a suggestion, try it, i think it is a better approach.
You could do something like this
public static void main(String[] args) {
// declare the variables first
int q1 = 1;
int q2 = 2;
...
int q15 = 15;
int[] questions = new int[] { q1, q2, q3, q4, ... q15 };
System.out.println("Before Shuffle");
for (int i : questions) {
System.out.println(i);
}
shuffle(questions); // here we do the shuffle
System.out.println("After Shuffle");
for (int i : questions) {
System.out.println(i);
}
}
public static void shuffle(int[] questions) {
Random random = new Random();
for (int i = 0; i < questions.length; i++) {
int newIndex = random.nextInt(questions.length - 1);
swap(questions, i, newIndex);
}
}
private static void swap(int[] questions, int oldIndex, int newIndex) {
int temp = questions[oldIndex];
questions[oldIndex] = questions[newIndex];
questions[newIndex] = temp;
}

Having trouble working with a class with an array

When i call my TruthTable class & populate it w/inputs, I can't access individual slots in the array when I'm trying to set the inputs of the AND gates?
threeAndGates.java -the class where the error happens
import java.util.Scanner;
public class threeAndGates {
public static void main(String[] args){
LogicGate and1 = new LogicGate(LogicGate.AND);
LogicGate and2 = new LogicGate(LogicGate.AND);
LogicGate and3 = new LogicGate(LogicGate.AND);
System.out.print("What is the number of Inputs? ");
Scanner scan = new Scanner(System.in);
int numOfInputs = scan.nextInt();
System.out.print("What is the number of Outputs? ");
int numOfOutputs = scan.nextInt();
TruthTable Table1 = new TruthTable(numOfInputs,numOfOutputs);
Table1.PopulateTruthTable();
//below is where it is giving me "the type of the expression must be an array type but it resolves to TruthTable"
for(int r = 0; r<(Math.pow(2, numOfInputs)) ; r++ ){
and1.setInput1(Table1[r][0]);
and1.setInput2(Table1[r][1]);
and2.setInput1(Truth1[r][2]);
and2.setInput2(Truth1[r][3]);
and3.setInput1(and1.getOutput());
and3.setInput2(and2.getOutput());
Table1[r][numOfInputs + numOfOutputs] = and3.getOutput();
}
Table1.printTruthTable();
}
}
TruthTable.java
public class TruthTable {
private int numOfInputs;
private boolean[][] table;
public TruthTable(int inputs, int outputs){
this.numOfInputs = inputs;
int rows = (int) Math.pow(2,inputs);
int columns = inputs + outputs;
table = new boolean[rows][columns];
}
public void printTruthTable(){
for(int r = 0 ; r < table.length ; r++){
for(int c = 0; c < table[r].length; c++)
System.out.printf("%-5b ", table[r][c]);
System.out.println();
}
}
public String toString(){
String outStr = new String();
for(int r = 0; r < table.length; r++){
for(int c = 0; c < table[r].length; c++)
outStr += String.format("%-5b ", table[r][c]);
outStr += '\n';
}
return outStr;
}
public boolean[][] PopulateTruthTable(){
String s;
String r ="";
int[] Line = new int[numOfInputs];
boolean bit;
for ( int i= 0; i < Math.pow(2,numOfInputs) ; i++){
int x = numOfInputs - Integer.toBinaryString(i).length();
for(int j = 0; j<x ; j++)
r += "0";
s = r + Integer.toBinaryString(i);
for(int k=0; k<s.length() ;k++){
Line[k] = s.charAt(k)-48;
}
for(int m=0 ; m<numOfInputs ; m++){
if(Line[m]==1) bit = true;
else bit = false;
table[i][m] = bit;
}
r="";
}
return table;
}
}
Your TruthTable class is not an Array. It contains an Array. You could add a get and set method to your TruthTable class:
public boolean getValueAt(int x, int y) {
return this.table[x][y];
}
public void setValueAt(int x, int y, boolean value) {
this.table[x][y] = value;
}
and use that to work with the TruthTable values.
This is unrelated to your problem, but when naming variables in your classes, the general practice is to use lower case. For example you have:
TruthTable Table1 = new TruthTable(numOfInputs,numOfOutputs);
would be better
TruthTable table1 = new TruthTable(numOfInputs,numOfOutputs);
and probably best as
TruthTable truthTable = new TruthTable(numOfInputs,numOfOutputs);
The better and more consistent you name things the easier it will be to read down the road.
Your TruthTable class isn't a mutil-dimensional array; it has a multi-dimensional array field. Therefor, you can not use the following syntax:
tableInstance[x][y]
If you TruthTable's table field was public, or better yet, it had a getter, you could do womthing like this instead...
tableInstance.getTable()[x][y]
Some languages (like C#) also support operator overloading which would allow you define the behaviour of using the [] index operator (or others like +, /, etc.). This would allow you to make the indexing work. Unfortunately, Java doesn't have this feature.
This is more of a comment than an answer but I needed more space.
If your code causes you problems later, may I make a suggestion? Break down populateTruthTable into 2 or 3 methods, putting each loop in it's own well named method because Each method should do exactly one thing
Also you probably shouldn't be accessing the array directly from the main class, instead put all the code from your main classes "for" loop into a method in the TruthTable class and call that method from main because you should Tell an object what to do rather than asking for it's data.
I'm not trying to say you're doing it wrong or anything, you are obviously doing very well, but it's always good to pick up more coding tricks/practices as you go along and you seem like you are at the level where these would come in handy.

Categories