Given the 2d array:
double[][] table;
table = new double[4][5];
I know how to print the array with 20 0's using:
for (int ii = 0 ; ii < table.length ; ii++)
{
for (int jj = 0 ; jj < table[0].length ; jj++)
{
System.out.print(table[ii][jj] + "\t");
}
System.out.println("");
}
I would like to ask the user to input "1,2,3" where 1 is the row, 2 is the column and 3 is the value that goes in the cell. Please help me how to do this using the string split method. Thank you!
String numString = "1,2,3";
String[] splitString = numString.split(",");
int num1 = Integer.parseInt(splitString[0]);
int num2 = Integer.parseInt(splitString[1]);
int num3 = Integer.parseInt(splitString[3]);
table = new double[4][5];
table[num1][num2] = num3;
That's easy if you go step by step:
use Scanner class on System.in to read a line through nextLine()
split the String according to the given delimiter (",")
check if amount of tokens is correct
convert each token to an int through Integer.parseInt(..)
set the correct value through table[x][y] = v
Related
First I uploaded the file I'm using, the constitution. Then, I created two arrays, one for the length of the alphabet, the second to compute the frequency. I created a while loop to read every line in the document and count the frequency of every letter, I just can't figure out how to compute each as a percentage of each letter because after I'm going to put it into a bar chart.
int [ ]lettersLabels = new int [26];
int [ ]lettersFrequency = new int [26];
String line;
//initialize arrays
letterLabels = 0;
lettersFrequency = 0;
Scanner sc = new Scanner(constitution);
while(sc.hasNextLine())
{
line = sc.nextLine();
line = sc.toLowerCase();
char[] characters = line.toCharArray();
for (int i = 0; i< characters.length ; i++)
{
if((characters[i] >='a') && (characters[i]<='z'))
{
lettersLabels[characters[i] -'a' ]++;
}
}
}
for (int i = 0; i < 26; i++)
{
lettersFrequency = 'a' + [characters[i] -'a' ]++;
lettersFrequency = lettersFrequency / 100;
System.out.println(lettersFrequency);
}
Percentage is ratio * 100 (1/2 = 0.5 = (0.5 * 100)% = 50%), and the ratio here is lettersLabels[i] / totalLetters. So, in order to find the percentage, you just use lettersFrequency[i] = (double) lettersLabels[i] / (double) totalLetters * 100;. So, you might need a variable totalLetters at the beginning to count the number of letters.
You have a mistake in your code, which is initializing arrays with 0. You have already initialized the arrays with int[] arr = new int[26];, so you don't need those two lines, which will give an error since initializing arrays with an int is the wrong type. Also, when setting some part of lettersFrequency to something, you need to specify the index, like lettersFrequency[i], and instead of using characters when its out of scope to get the characters, so instead you have to use the letterLabels array.
Hope this works!
Here I've fix some of the errors with description see the code comments for explanation :
int [ ]lettersLabels = new int [26];
int [ ]lettersFrequency = new int [26];
String line;
int totalLetter =0; // needed to calculate %
// No need to initialize, it's already initialized with 0 values.
// remove those lines.
//initialize arrays
// letterLabels = 0;
// lettersFrequency = 0;
Scanner sc = new Scanner(constitution);
while(sc.hasNextLine())
{
line = sc.nextLine();
// need to lower case the current line
line = line.toLowerCase();
char[] characters = line.toCharArray();
for (int i = 0; i< characters.length ; i++)
{
if((characters[i] >='a') && (characters[i]<='z'))
{
// lets count the letter frequency.
totalLetter++;
lettersFrequency[characters[i] -'a' ]++;
}
}
}
// get rid of divide by zero exception
if(totalLetter ==0) totalLetter =1;
for (int i = 0; i < 26; i++)
{
char ch = 'a'+i;
// let's count the parentage of each letter.
double parcentage = (lettersFrequency[i]*100.00)/totalLetter;
System.out.println("parcentage of "+ ch+ " is: " +lettersFrequency +"%");
}
Sudoku with Java Arrays
I am building a 9x9 2D array and trying to fill it by inputting a random 9 digits integer for each row. I want to insert each digit of that number as an element along the rows [0][0-8],[1][0-8]... I tried to convert the integer into a string and insert each character but I can't seem to figure it out.
System.out.println("Please insert 9 lines of 9 digits (1-9)");
int Choise = scan.nextInt();
char c =(char)Choise;
int soduko[][] = new int[9][9];
for (int i = 0; i< soduko.length; i++){
for(int j =0; j< soduko.length; j++){
soduko[i][j]=c;
}
}
i have tried another way that still uses the number as an int, by taking the remainder of that number to the last cell in the row, and dividing the number by 10 each time in the loop. although its not working when i try to divide by 10 to get the next remainder.
System.out.println("Please insert 9 lines of 9 digits (1-9)");
Choise = scan.nextInt();
for (int i =0; i <= soduko.length -1; i++){
for(int j = soduko.length -1; j > 0; j--){
int ChoiseDigit = Choise % 10;
soduko[0][j] = ChoiseDigit;
Choise = (int)(Choise / 10);
}
}
Building on your string conversion idea, you might benefit from using the split() method, which splits up a string based on a string you pass as an argument, and then returns an array of the split-up strings. So when you do split(""), the string is split up into single characters. Then you can parseInt to turn each string into an int. I would also recommend putting the scanner input in the loop, to make sure the user has to input a string 9 times.
System.out.println("Please insert 9 lines of 9 digits (1-9)");
int soduko[][] = new int[9][9];
for (int i = 0; i< soduko.length; i++){
//reading a string of input 9 times and splitting them by "" into 1-character strings
String Choise[] = scan.nextLine().split("");
for(int j =0; j< soduko[i].length; j++){
//Integer.parseInt converts each string to an int so we can save it to the 2d array
soduko[i][j]= Integer.parseInt(Choise[j]);
}
}
I'm trying to get a string to read a file, that then stores all the digits in an array that can be recalled one by one in another loop. Name the array digitStorage please :D Here's my current bit of code:
for (int i = 0; i <= 40000 ; i++) {
String digit;
if ( i <=39998)
digit = pictureFile.substring(i, i+1);
else
digit = pictureFile.substring(39998,39999);
My question :
What to do, how could I do this, how would I get it to read each digit (single integers) 1 by 1 and then store them 1 by 1 in an array that could be later recalled, each number corresponds to a color that would be used to sketch a picture in a graphics window (there are 40,000 single digit integers in a file that i've already worked out how to read) ?
Cheers.
As you have mentioned that you have already read the file and you want to store it in some kind of array. Below code will work.
List<String> list = new ArrayList<String>();
for (int i = 0; i <= 40000 ; i++) {
String digit;
if ( i <=39998)
list.add(pictureFile.substring(i, i+1));
else
list.add(pictureFile.substring(39998,39999));
}
If you want List of Integer then us.
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i <= 40000 ; i++) {
String digit;
if ( i <=39998)
list.add(Integer.parseInt(pictureFile.substring(i, i+1)));
else
list.add(Integer.parseInt(pictureFile.substring(39998,39999)));
}
You can iterate through list after this.
Your question is not very clear, but I believe this should do it:
int [] digitStorage = new int[40000];
for (int i = 0; i <= 40000 ; i++) {
if ( i <=39998)
int[i] = Integer.parseInt(pictureFile.substring(i, i+1));
else
int[i] = Integer.parseInt(pictureFile.substring(39998,39999));
Based on your comments and question, the easiest solution I can think of is to use String.toCharArray() and Character.digit(char, int) like
char[] chars = pictureFile.toCharArray();
int[] digitStorage = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
digitStorage[i] = Character.digit(chars[i], 10);
}
System.out.println(Arrays.toString(digitStorage));
I've read data from a text file and stored them in an array called 'boat1'.
There are nine values and I am trying to add together index's [4] to [9] to get a total value.
How would I go about doing this?
Here is my code:
String[] boat1 = new String[9];
int i = 0;
while(reader.hasNextLine() && i < boat1.length) {
boat1[i] = reader.nextLine();
i++;
}
I've tried to change the values to an integer but it doesn't seem to be working..?
Thank you.
You got to parse before adding:
int a = Integer.parseInt(boat1[3]);
int b = Integer.parseInt(boat1[8]);
int c = a + b;
Your array boat1 is a String array and not an int array. You need to convert it. Note that boat1 is size of 9 meaning that it has indexes from 0 to 8. Java is 0 based.
If you want to add up a sequence of numbers (ex. 3,4,...,7,8), just loop through the indexes you want to add up and keep track of a total.
Because your array is an String type it needs to be converted to int, After you do that you will have something like this example assuming that I'm making up those values , but it should still work for your code :). Don't forget to add the for loop at the end as I have it on my code so it can find the sum of your indexes. Hope it can help you!
int sum = 0;
int[] boat = new int[9];
boat[0] = 2;
boat[1] = 4;
boat[2] = 6;
boat[3] = 8;
boat[4] = 10;
boat[5] = 12;
boat[6] = 14;
boat[7] = 16;
boat[8] = 18;
for(int i = 3; i < boat.length ; i++){
sum += boat[i];
}
System.out.println(sum);
I keep trying to add (many times) +1 to a number (the number is zero) already in an array which is zero but it is not working.
int i=0;//var for arrays
int [] countArray = new int[10];
/////////////////////
//__________ ask for values --------------
System.out.println("Hello please enter the number you would" +
" like to be sorted separated by commas. \n" +
"Example: \" 2,3,5,83,2 \".\t only use" +
" commas. to separate numbers\n");
//----------- save values -----
Scanner scan = new Scanner(System.in);
String allInput = scan.nextLine();//single string object with all input
String [] arr = allInput.split(",");//string array that holds all values
//as String
int [] numbersArray =new int[arr.length] ;//numbers
for ( String w: arr){//change Strings to Int
numbersArray[i]= Integer.valueOf(arr[i]);
i++;
}
//__ set all number in count to zero because necessary
i=0;
for ( int x: countArray){//set all numbers to zero
countArray[i]=0;
i++;
} //everything zeroed
i=0;
This works now, thank you guys:
for (int x = 0; x < numbersArray.length; x++){
if (numbersArray[x] >=10 && numbersArray[x] <=100) {
countArray[(numbersArray[x]-1)/10]++;}
else{
if (numbersArray[x] >=0 && numbersArray[x] <=10)
{
countArray[1 -1]++;}
}
}
Instead of using a for-each loop to edit all the values, try to iterate through them using a standard for loop. Here is a shorthand version of what you wrote. Try this:
for (int x = 0; x < numbersArray.length; x++){
countArray[(numbersArray[x]-1)/10]++;
}