I'm trying to store the values inputted on the for-loop structure that I will need for later use, but it can only be recognized inside the for loop structure. I need the stored values to be recognize for the rest of the program but somehow I'm getting an error "cannot find symbol"
public class TryArray {
public static void main(String args[]) throws IOException {
BufferedReader inpt = new BufferedReader(new InputStreamReader(System. in ));
int[] arrayCrit = new int[5];
String[] crits = new String[5];
for (int i = 0; i < crits.length; i++) {
System.out.print("Criteria: ");
crits[i] = inpt.readLine();
for (int j = 0; j < arrayCrit.length; j++) {
System.out.print("Percentage: ");
arrayCrit[j] = Integer.parseInt(inpt.readLine());
}
}
System.out.println(crits[i] + arrayCrit[j])
}
}
Edit: Yes, I can move the print output inside the for-loop, but I need to input all the values first before showing all of it. Please I need help.
Hope this will help.
public static void main(String args[]) throws IOException {
BufferedReader inpt = new BufferedReader(new InputStreamReader(
System.in));
int[] arrayCrit = new int[5];
String[] crits = new String[5];
for (int i = 0; i < crits.length; i++) {
System.out.print("Enter Criteria: ");
crits[i] = inpt.readLine();
System.out.print("Enter Percentage: ");
arrayCrit[i] = Integer.parseInt(inpt.readLine());
}
// Printing the values
for (int i = 0; i < crits.length; i++) {
System.out.println("Criteria :" + crits[i] + " Percentage: "
+ arrayCrit[i]);
}
}
to show all you have to make another loop to read, after the insertion
import java.io.*;
public class TryArray{
public static void main(String args[])throws IOException{
BufferedReader inpt = new BufferedReader (new InputStreamReader(System.in));
int [] arrayCrit = new int [5];
String [] crits = new String [5];
for(int i=0; i<crits.length; i++){
System.out.print("Criteria: ");
crits[i]=inpt.readLine();
for (int j=0; j<arrayCrit.length; j++){
System.out.print("Percentage: ");
arrayCrit[j]=Integer.parseInt(inpt.readLine());
}
}
for(int i=0; i<crits.length; i++){
for (int j=0; j<arrayCrit.length; j++){
System.out.println(crits[i] + arrayCrit[j])
}
}
}
}
or I misunderstood your question?
What you're currently doing will overwrite the values entered for the previous criteria when you get the input for the next. I believe you want to have a 2d array for arrayCrit to store all the percentages for each criteria. Only in such a scenario it makes sense to have 2 for loops.
String[] crits = new String[5];
int[][] arrayCrit = new int[5][5]; // The 2d array
for (int i = 0; i < crits.length; i++) {
System.out.print("Criteria: ");
crits[i] = inpt.readLine();
for (int j = 0; j < arrayCrit[i].length; j++) {
System.out.print("Percentage: ");
arrayCrit[i][j] = Integer.parseInt(inpt.readLine()); // Inputting different set of percentage for each criteria
}
}
// Displaying each criteria with its own percentages
for (int i = 0; i < crits.length; i++) {
System.out.print("For Criteria: " + crits[i]+" ---> ");
for (int j = 0; j < arrayCrit[i].length; j++) {
System.out.print("Percentage " + j + " : " + arrayCrit[i][j] + "\t");
}
System.out.println();
}
1) Add
import java.io.*;
2)You are using nested for loops
for(int i=0; i<crits.length; i++){ //this will execute 5 times
System.out.print("Criteria: ");
crits[i]=inpt.readLine();
for (int j=0; j<arrayCrit.length; j++){ //this will execute 5 times for each i = 25 times
System.out.print("Percentage: ");
arrayCrit[j]=Integer.parseInt(inpt.readLine());
}
}
Remove nested for-loop as
for(int i=0; i<crits.length; i++){ //this will execute 5 times
System.out.print("Criteria: ");
crits[i]=inpt.readLine();
}
for (int j=0; j<arrayCrit.length; j++){ //this will execute 5 times
System.out.print("Percentage: ");
arrayCrit[j]=Integer.parseInt(inpt.readLine());
}
3) can not find symbol
You want to print criteria and percentage at same time, as you have initialized both arrays with size 5, then you can directly print
for (int i = 0; i < 5; i++) {
System.out.println(crits[i] + arrayCrit[i]);
}
4)You can use following program which is enhanced version of your program
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestArray {
public static void main(String args[]) throws IOException {
BufferedReader
inpt = new BufferedReader(new InputStreamReader(System. in ));
System.out.println("How many records?");//ask for how many records
int n = Integer.parseInt(inpt.readLine());// store in n
int[] arrayCrit = new int[n];//create array with size n
String[] crits = new String[n];
//**as you mentioned in edit you want to take all the input before printing**
for (int i = 0; i < n; i++)
{
System.out.print("Criteria: ");
crits[i] = inpt.readLine();
System.out.print("Percentage: ");
arrayCrit[i] = Integer.parseInt(inpt.readLine());
}
//print both arrays
System.out.println("Criteria \t Percentage");
for (int i = 0; i < n; i++)
{
System.out.println(crits[i] + "\t"+arrayCrit[i]);
}
}
}
Useful link
Nested for
You have to define i and j outside the loop. Otherwise, you can only use them inside the loop:
int i;
int j;
int[] arrayCrit = new int[5];
String[] crits = new String[5];
for (i = 0; i < crits.length; i++) {
System.out.print("Criteria: ");
crits[i] = inpt.readLine();
for (j = 0; j < arrayCrit.length; j++) {
System.out.print("Percentage: ");
arrayCrit[j] = Integer.parseInt(inpt.readLine());
}
}
Related
I tried getting String input from the user. But it fails with to receive input at arr[0][0].
About Program: In dynamic 2d array program search a string in that array matrix and return true or false.
class SearchString{
public static void main(String[] args){
int n, m;
System.out.println("Enter the size of 2d array: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
m = s.nextInt();
String[][] arr = new String[n][m];
System.out.println("Enter the elements: ");
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < arr[i].length; j++){
System.out.println("arr["+i+"] ["+j+"]"); arr[i][j] = s.nextLine();
}
}
}
}
Enter the size of 2d array:
2
2
Enter the elements:
arr[0] [0]
arr[0] [1]
AMerica
arr[1] [0]
Uk
arr[1] [1]
France
do a
s.nextLine();
After reading the int values (m and n). To clear the eol caracter before using s.nextline to read the input
public static void main(String[] args){
int n, m;
System.out.println("Enter the size of 2d array: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
m = s.nextInt();
s.nextLine();
String[][] arr = new String[n][m];
System.out.println("Enter the elements: ");
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < arr[i].length; j++){
System.out.println("arr["+i+"] ["+j+"]"); arr[i][j] = s.nextLine();
}
}
}
Assuming you use the [enter] key to submit your values, you should add a s.skip("\n"); after getting the array size, so that the first position of your 2d array is not ignored:
public static void main(String[] args) {
int n, m, flag = 0;
System.out.println("Enter the size of 2d array: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
m = s.nextInt();
s.skip("\n");
String[][] arr = new String[n][m];
System.out.println("Enter the elements: ");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.println("arr[" + i + "] [" + j + "]");
arr[i][j] = s.nextLine();
}
}
System.out.println("Done! Content of your 2d array:");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.println("arr[" + i + "] [" + j + "] = " + arr[i][j]);
}
}
}
Just thought of a simple program to practice java coding and am stuck at the end part.,..
the code prints out the required answer (what numbers match from input compared to results for a 5 number lottery) but the answer is printed without spaces. I thought perhaps to add a "" when += to matchingNumbers but that didnt do anything!
import java.util.Scanner;
import java.util.Arrays;
public class LottoChecker
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int [] yourNumbers = new int [5];
int yourInput, resultsInput;
int [] results = new int [5];
int currentNumber = 0;
String matchingNumbers = "";
for (int i=0; i<yourNumbers.length; i++)
{
System.out.println ("Enter your main numbers: " );
yourInput = in.nextInt();
yourNumbers[i]=yourInput;
}
for (int j=0; j<results.length; j++)
{
System.out.println("Enter the results from the main numbers: ");
resultsInput = in.nextInt();
results[j] = resultsInput;
}
System.out.println("Your Numbers: " +
Arrays.toString(bubbleSort(yourNumbers)));
System.out.println("The Results are: " +
Arrays.toString(results));
for (int i =0; i<yourNumbers.length;i++)
{
currentNumber = yourNumbers[i];
for (int j=0;j<results.length;j++)
if (currentNumber == results[j])
matchingNumbers += currentNumber + "";
}
System.out.println("Your matching numbers are: " +
matchingNumbers);
}
public static int [] bubbleSort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
return arr;
}
}
An elegant solution would be using StringJoiner(" ") and then add the numbers on each iteration.
I'm trying to tally a count array to keep up with a set of 50 choices where there are three options for each choice. The count array should have 150 elements, per my instructor (3 x 50 = 150). But I keep getting an IndexOutofBounds Exception at line 55 (index = thisChoice.get(i)). I'm thinking that it must have something to do with how (or where?) I'm instantiating my count array at
line 50: int[] count = new int[students.get(0).getChoices().size()*3]
because the rest of the code came from my instructor and is presumably correct. Any ideas on what could be sending it out of bounds?
public class P1Driver {
public static void main(String[] args) throws IOException{
ArrayList<Students> students = new ArrayList<Students>();
ArrayList<String> choices = new ArrayList<String>();
Scanner scan1 = new Scanner(new File("Choices.txt"));
Scanner scan2 = new Scanner(new File("EitherOr.csv"));
// Scan the first file.
int choicesIndex = 0;
while(scan1.hasNextLine()){
String line = scan1.nextLine();
choices.add(line);
choicesIndex++;
}
scan1.close();
// Scan the second file.
int studentIndex = 0;
while(scan2.hasNextLine()){
String line = scan2.nextLine();
String [] splits = line.split(",");
students.add(new Students(splits[0]));
for(int i = 1; i < splits.length; i++){
students.get(studentIndex).addChoices(Integer.parseInt(splits[i]));
}
studentIndex++;
}
scan2.close();
// Instantiate and add to the count array.
int index, countIndex;
ArrayList<Integer> thisChoice;
int[] count = new int[students.get(0).getChoices().size()*3];
for(int i = 0; i < students.size(); i++){
countIndex = 1;
thisChoice = students.get(i).getChoices();
for(int j = 0; j < thisChoice.size(); j++){
index = thisChoice.get(i);
count[countIndex + index] = count[countIndex + index] + 1;
countIndex+=3;
}
}
// Display data.
countIndex = 1;
for(int i = 0; i < choices.size(); i+=2){
System.out.println(choices.get(i) + count[countIndex] + choices.get(i+1) + count[countIndex+1] + " Invalid: " + count[countIndex-1]);
countIndex+=3;
}
HI Please check second nested loop, it should be j instead of i .
also you haven't used int j in that loop.
for (int i = 0; i < students.size(); i++) {
countIndex = 1;
thisChoice = students.get(i).getChoices();
for (int j = 0; j < thisChoice.size(); j++) {
index = thisChoice.get(j);
count[countIndex + index] = count[countIndex + index] + 1;
countIndex += 3;
}
}
So I have to fill a 2D array with chars, print out the array, let people search for words, and then print out the number of instances of that word and the array with the instances of that word highlit.
here is my code so far:
import java.util.Scanner;
import java.util.*;
public class testSearchMatrix {
public static void printArray(char[][] myArray){
for(int i = 0; i < myArray.length; i++){
for(int j = 0; j < myArray.length; j++){
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
queryNum += 1;
}
}
}
System.out.println(queryNum);
}
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
Random random = new Random();
//Create an alphabet array so I can use this to fill in the searchBox array
char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
System.out.println("Please choose an array size: ");
int a = keyboard.nextInt();
//Create a square array
char[][] searchBox = new char[a][a];
//Fill in the array with random chars
for(int i = 0; i < searchBox.length; i++){
for(int j = 0; j < searchBox[i].length; j++){
int randNum = random.nextInt(25);
searchBox[i][j] = alphabet[randNum];
}
}
//Implement my method to print the array to the screen
System.out.println("Here is the square matrix with random letters: ");
printArray(searchBox);
System.out.println("Enter a query to search: ");
searchArray(searchBox);
}
}
This will print out my array but I can't seem to get the search to work.
Modified Your searchArray function
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
String out = null;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
//System.out.println(i+":"+j+a[i][j]);
//w+=1;
if(out==null)
{
out=String.valueOf(a[i][j]);
}else
out=out+a[i][j];
for(int f = 1; f < query.length(); f++){
if(j+f<5){
if(a[i][j+f] == query.charAt(w+f)){
// System.out.println(i+"Index:w+f"+w+f+query.charAt(w+f)+"query.charAt(w+f)Index"+query.indexOf(query.charAt(w+f)));
// System.out.println(i+":"+j+a[i][j+f]);
out=out+a[i][j+f];
System.out.println(out+":"+query+"here"+out.length()+query.length());
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
}
}
} if(out!=null)
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
out=null;
}
}
}
System.out.println(queryNum);
}
OuptPut
package test1;
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int traincars;
int maxweight;
int count = 0;
int total = 0;
maxweight = input.nextInt();
traincars = input.nextInt();
int[] trains = new int[traincars];
for(int i = 0; i < traincars; i++)
{
trains[i] = input.nextInt();
}
if (total < maxweight)
{
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
}else
{
count = count + 3;
}
System.out.println("count");
}
}
this is a really simple program but for some reason, the array for the traincars goes out of bounds..
Why is this happening?
The problem is here:
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
When i equals traincars-1 you will be accessing elements i+1, i+2. and i+3 which are out of bounds of your trains array.
If your logic is calling for calculating totals of 4 consecutive elements of the array then your for loop should stop earlier:
for(int i = 0; i < traincars - 3; i++) {...}
In the last iteration of
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
You try to access trains[i+1] and this is bigger than the length of your trains array.
To make this for loop matter you should just do the following:
for(int i = 0; i < traincars; i++)
{
total += trains[i]; //unless of course you need something else...
count++;
}