I want to be able to choose an array index using input.
Object stud1 [][] = {
{1,2,3},
{"favorite food: ","pet name: ","bday: "}
}
System.out.println("how many inputs?");
If a user inputs 1, then "favorite food:" will prompt the user and if the user inputs 2, then
both "favorite food: " and "pet name: " will prompt the user and so on.
After the user completes the prompt input, this will display:
favorite food: chicken
pet: doge
birthday: december 25,1994
/////////////////////////////////////////my code/////////////////////////////////////////////
This question is similar to my other question, I just could not find the right answer for my question because I think it was confusing and not specific enough.
It's kind of working already but the problem is that when I input 1 then it still outputs everything. I only want it to output everything if the user inputs 3 which is the number of indexes in my array.
I am not pretty good with arrays yet especially multi array, I'm still experimenting.
String ctr1;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
if (num1 <= stud1.length) {
for (int x = 1; x<stud1.length;x++){
for (int i = 0; i<stud1[x].length;){
/*System.out.print("Enter Value #" + x++ +":");
ctr1 =Integer.parseInt(in.readLine());
i++;*/
System.out.println(stud1[x][i]);
ctr1 =in.readLine();
i++;
}
}
I'm sorry but I don't think this is a good example for multidimensional arrays... nothing is really being done with the first element here: {1,2,3}.
To answer the specific question of why all 3 elements are printing out when the user only inputs a "1", it is because that value is being read into the variable num1, but num1 is not used anywhere in the loop that prints the output. If you want the input to control how many values are printed, then num1 needs to be used in the for loop's test expression (the middle phrase in the parentheses). I think a good first step is to change your inner loop like so:
for (int i = 0; i<num1;i++){
System.out.println(stud1[1][i]);
ctr1 =in.readLine();
}
Also note that the i++ is moved inside the parentheses for the for loop. That's really where it belongs, if you're using for.
Hope this helps!
Related
I'm not very good at this, but I am trying to create a program in Java that creates a polyhybrid cross punnett square from the parameters of two objects, which are the parents. every parameter is a string that is user defined with a scanner.
These are the two objects that I have, modified for the purpose of this question (they actually have seven strings parameters that are its genetic traits and they are all filled in by the user with scanner)
Creature Mom = new Creature("B,b");
Creature Dad = new Creature("C,c");
and I want to use a for loop to get the results "BC, bC, Bc, bc" in the console.
i know i need to use a delimiter or split somewhere to get those results, But I haven't really gotten to that point yet.
I've managed to create a punnett square with two arrays of strings that i loop through, as is seen here,
//accept user input
Scanner alleles = new Scanner(System.in);
System.out.println("enter first allele in mother's allele pair: ");
Mom.alleleOne = alleles.nextLine();
System.out.println("enter second allele in mother's allele pair: ");
Mom.alleleTwo = alleles.nextLine();
System.out.println("enter first allele in father's allele pair: ");
Dad.alleleOne = alleles.nextLine();
System.out.println("enter second allele in father's allele pair: ");
Dad.alleleTwo = alleles.nextLine();
//close scanner
alleles.close();
//arrays for parents data
String[] Mother = {Mom.alleleOne, Mom.alleleTwo};
String[] Father = {Dad.alleleOne, Dad.alleleTwo};
//display data
System.out.println("Mother Result: " + Arrays.toString(Mother));
System.out.println("Father Result: " + Arrays.toString(Father));
System.out.println("Possible children: ");
// for loop to cycle through combinations
for (int i = 0; i < Mother.length; i++) {
for (int j = 0; j < Father.length; j++) {
System.out.println(Mother[i] + Father[j]);
}
}//end for
But i really think continuing with objects is my best bet here for continuing this project. I've thought about using reflection, and turning an object into an array of its fields/parameters, but nothing seems to click in my mind. I hope what I'm asking makes sense, I apologize if it doesn't. Thank you in advance.
I have made an array rotation program that will allow the user to enter nine numbers (nine just to test that it works). The nine numbers will be stored into an array and rotated in a rotateArray() function. I'm trying to make it so that the user can be able to enter as many numbers as they want. Would the arraylist be the best way to dynamically allocate the array capacity?
int[] userArray = new int[9];
System.out.println("This program can also rotate arrays.\n" +
"Enter 9 single digit integers separated by spaces");
for(int i = 0; i<userArray.length; i++)
{
userArray[i] = scan.nextInt();
}
System.out.println("The array you entered is: " + Arrays.toString(userArray) +"\n"+
"When your array is rotated, it looks like this: \n" +
Arrays.toString(rotateArray(userArray)));
}
Would the arraylist be the best way to dynamically allocate the array capacity?
Yes, you can use Arraylists. But the best way? Saying "yes" would be a daring answer, but clearly it's better to use in this case.
In given scenerio, it can be used like this:
//an arraylist
ArrayList<Integer> userArrayList = new ArrayList<Integer>();
System.out.println("This program can also rotate arrays.\n" + "Enter any numbers, type 'end' when you finish");
//flag for while loop, in case the user prompts "end"
boolean endNotPrompted = true;
//scanner
Scanner scan = new Scanner(System.in);
while(endNotPrompted) {
//if user input is a number
if(scan.hasNextInt() == true) {
int num = scan.nextInt();
userArrayList .add(num);
}
//if not a number, checks if the user wants to finish entering numbers
else if(scan.nextLine().equals("end")) {
endNotPrompted = false;
}
}
scan.close();
/*
*rest of your code
*/
When using an ArrayList, you need not to know the exact size of the user input.
I have a program that asks the user for an input which is an int(using a scanner).
I only want the program to take in 7 digits.
If the input is not 7 digits I want to truncate it to 7 digits.
So if the number were 12345678 I would want it to be 1234567.
Currently I am storing the input in an array like the following:
for(int i = 0; i > 7; i++)
{
numbers[i] = input1 % 10;
input1 /= 10;
System.out.print(numbers[i]);
//stores the numbers backwards so if input was 123, first element would be 3, 2, 1
}
so that's when I run into the problem if I enter 12345678, it will store it as 8765432. I want it to store as 7654321 instead.
If anyone has any suggestions on my loop making the number store as 1234567 or 7654321, it would be quite helpful :)
An easier way can be to save the input into a String
Then check if length>7, if yes keep the 7 first character, if no, do nothing ;)
String input1 = sc.nextLine();
if(input1.length>7){
input1 = input1.substring(0,7);
}
int input = Integer.valueOf(input1);
It's clearly easier than storing each digit individually or iterate over the input ;)
Edit with '?' ('?' definition and explication)
String input1 = sc.nextLine();
int input = Integer.valueOf(((input1.length>7) ? input1.substring(0,7) : input1);
This allows to not change the value of input1 this will stay the original input
Well, there are several things.
First of all, I think it'd be better for you to use ArrayList and work on Integers, rather than primitive types such as int. If you use ArrayList, then you can simply do .add(Integer e) to put next Integer into your list.
Next thing, your loop should be:
for(int i = 0; i < 7; i++) instead of for(int i = 0; i > 7; i++). See the difference? If you are using i++, then you limit your loop with a <, not >.
As for reversing the input, it's pretty simple, use i-- instead, but I think you can figure this out yourself.
public static void trauncateNumber(int input1) {
String Str=Integer.toString(input1);
//int changeValue=0;
if(Str.length()>7){
//Str=Integer.toString(input1);
Str=Str.substring(0, 7);
input1=Integer.parseInt(Str);
}
//int changeValue=
System.out.println(input1);
}
I know there is a similar question already asked, so let me apologize in advance. I am new to Java and before this, my only programming experience is QBasic.
So here is my dilemma: I need to accept 2 integer values and I would like to be able to enter both values on the same line, separated by a space (IE: Enter "45 60" and have x=45 and y=60).
From what I have seen, people are suggesting arrays, but I am weeks away from learning those... is there a simpler way to do it? We have gone over "for", "if/else", and "while" loops if that helps. I don't have any example code because I don't know where to start with this one.
I have the program working with 2 separate calls to the scanner... just trying to shorten/ clean up the code. Any ideas??
Thanks!
//UPDATE:
Here is the sample so far. As I post this, I am also reading the scanner doc.
And I don't expect you guys to do my homework for me. I'd never learn that way.
The println at the end it my way of checking that the values were stored properly.
public static void homework(){
Scanner hwScan = new Scanner(System.in);
System.out.println("Homework and Exam 1 weights? ");
int hwWeight = hwScan.nextInt();
int ex1Weight=hwScan.nextInt();
System.out.println(hwWeight+" "+ex1Weight);
}
Even simple scanner.nextInt() would work for you like below:
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int y = scanner.nextInt();
System.out.println("x = " + x + " y = " + y);
Output:
1 2
x = 1 y = 2
If you only have to accept two integer numbers you could do something like this:
String input = System.console().readLine(); //"10 20"
//String input = "10 20";
String[] intsAsString = input.split(" ");
int a = Integer.parseInt(intsAsString[0];
int b = Integer.parseInt(intsAsString[1]);
intsAsString is an array, in simple terms, that means it stores n-strings in one variable. (Thats very simplistic, but since you look at arrays more closely later you will see what i mean).
Be sure to roughly understand each line, not necessarily what exactly the lines do but conceptually: Read data form Console, parse the line so you have the two Strings which represent the two ints, then parse each string to an int. Otherwise you will have a hard time in later on.
Any possible way to keep entering numbers, and when the same number is entered 2 or more times an error message arises or something like that? I need this to be answered in Java only. I'm new and I don't know where to go from here. I need help searching values in the array and then printing out all the numbers that have been entered.
public class Test
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("How big is the group?: ");
int[] group = new int[input.nextInt()];
for (int i = 0; i < group.length; i++)
{
System.out.println("Please enter number: ");
group[i] = input.nextInt();
}
I think this is what you're looking for. Inside of the for loop, there's a while loop spinning to keep collecting new ints until you enter one that's not already in the list.
for (int i = 0; i < group.length; i++)
{
System.out.println("Please enter number: ");
int next = input.nextInt();
while(Arrays.asList(group).contains(next)) { // Keep asking for new input while the input is already in list
System.out.println("That number is already in the group ... try again.");
next = input.nextInt();
}
group[i] = next;
}
Since this is clearly a "learning exercise", it is only appropriate to give you hints:
You can search an array by stepping through the array indexes and testing the elements at each index.
A method and a class both need a closing } ...
I need this to be answered in Java only.
That is incorrect. What you REALLY need is some hints. If we give you Java code, you miss out on the important learning experience of writing it yourself. And THAT is the WHOLE POINT of the homework. Go ask your teacher if you don't believe me.