So I am relatively new to Java language but am trying to get better so I can add more skills to my resume. I am currently focusing on arrays and I am writing a program that I want to be able to use with a barcode scanner or keyboard in order to keep track of Cultural Enrichment credits (inspired by my school's need of one ). I thought it might be a neat starting program to wrap my head around array use but I am having a problem with the two arrays. They keep overwriting the new values entered. I have been googling and trying things but I am still not able to get them to work properly and would like to ask for help from more seasoned coders. I know my output method is rather lazy but it'll do for what I would like to see for the output format.
Here is my code:
public static void main(String []args)throws InputMismatchException
{
Scanner user_input = new Scanner( System.in );
int n = 0;
String Name;
int CEU;
String[] users = new String[5];
String[] numbers = new String[6];
Object end = null;
Object print = null;
System.out.print("Enter value for CEU: ");
CEU = user_input.nextInt();
while (n >= 0)
{
/* Loop*/
System.out.println("Scan ID or type **end,print** ");
numbers[n] = user_input.next();
if ("end".equals(users[n] ))
{
System.out.print("Program terminated.");
System.exit(0);
}
if ("print".equals(numbers[n]))
{
System.out.print("CEUs: " + CEU);
System.out.print(" ID#: " + numbers[0]);
System.out.print(" Name: " + users[0]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[1]);
System.out.print(" Name: " + users[1]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[2]);
System.out.print(" Name: " + users[2]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[3]);
System.out.print(" Name: " + users[3]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[4]);
System.out.print(" Name: " + users[4]);
}
else
{
System.out.print("Enter Name: ");
users[n] = user_input.next();
}
}
}
Inside your loop you need to increment n as it is always 0. Use: n++; at the last line of code inside the while loop.
n isn't being incremented. Because n never changes, it will override the same part of the array each time the loop executes. Also, it seems like you may get a outofbounds error later, because i will keep increasing. Soon it will be greater than the max index of the numbers array, so it will return the error. You should try adding in some code that stops the error from happening.
Related
I have the following code, and I would like the user inputs to store, and then the code loop back with the next input storing also, until they hit "Q" which will then quit. I am not sure how to do it.
Also, I want my 2d array to be printed blank, instead of the default 0s, after the user sets the size. SO if the user says they want to input SIZE = 4x4 "row =1, column =2, input =7" it would print "These ZEROS would be BLANK
0000
0070
0000
0000
the input "row 2, column 1, input A it would print
0000
0070
0700
0000
My code so far
import java.util.*;
public class MainProg {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many rows do you want for your matrix? ");
int row = in.nextInt();
System.out.print("How many columns do you want for your matrix? ");
int column = in.nextInt();
String[][] newArray = new String[row][column];
Array2 twoDArray = new Array2(row, column, newArray); //calling my class
do {
System.out.println("If you would like to set an, element press S: " + "\n" +
"If you would like to set an element, press G" + "\n" +
"If you would like to empty an element, press E" + "\n" +
"If you would like to print an element, press P" + "\n" +
"If you would like to quit, press Q");
String userInput = in.next();
if (userInput.equalsIgnoreCase("S")) {
twoDArray.setElement();
} else if (userInput.equalsIgnoreCase("G")) {
twoDArray.getElement();
} else if (userInput.equalsIgnoreCase("E")) {
twoDArray.clearElement();
} else if (userInput.equalsIgnoreCase("P")) {
twoDArray.printMatrix();
//you will do you toString here
} else if (userInput.equalsIgnoreCase("Q")) {
//this will quit the program
twoDArray.quitProgram();
}
//break;
} while (true);
}
}
import java.util.*;
public class Array2 {
MainProg main1 = new MainProg();
Scanner in = new Scanner(System.in);
private String [][] newArray;
private int row;
private int column;
public Array2(int row, int column, String[][] newArray) {
this.row = row;
this.column = column;
this.newArray = newArray;
}
public void getElement() {
Scanner in = new Scanner(System.in);
System.out.println("What row is the element you would like to get in? (Must be under " + row + ")");
int userRow = in.nextInt();
System.out.println("What column is the element you like to get in? (Must be under " + column + ")");
int userCol = in.nextInt();
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol);
String getElement = newArray[userRow-1][userCol-1];
System.out.println(getElement);
}
public void setElement() {
System.out.println("What row would you like your element in? (Must be under " + row + ")");
int userRow = in.nextInt();
System.out.println("What column would you like your element in? (Must be under " + column + ")");
int userCol = in.nextInt();
System.out.println("What character would you like the element to be?");
String userChar = in.next();
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol + "\n" +
"Char to be entered: " + userChar);
newArray[userRow][userCol] = String.valueOf(userChar);
}
public void clearElement() {
Scanner in = new Scanner(System.in);
System.out.println("What row is the element you would like empty? (Must be under " + row + ")");
int userRow = in.nextInt();
System.out.println("What column is the element you like to empty? (Must be under " + column + ")");
int userCol = in.nextInt();
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol);
}
public void printMatrix() {
Scanner in = new Scanner(System.in);
//String result = " ";
System.out.println("The array is: \n");
for (int i = 0; i < newArray.length; i++) {
for (int j = 0; j < newArray[i].length; j++) {
System.out.print(newArray[i][j]);
}
//for (String[] row: newArray) THIS LEAD TO A PROBLEM
// Arrays.fill(row, " ");
System.out.println();
}
}
public void quitProgram() {
System.out.println("The system will now exit! BYE!!!");
System.exit(0);
}
}
I have EDITED my code so that I have answered some questions. Now my only problem left is getting my matrix to be initially filled with blanks " ", instead of the default "null". I attempted to use the Arrays.fill in my printMatrix method, however that lead to problems, it would not save the user input after the loop.
Your IndexOutOfBoundsException (now editted out) is due to you using row and column instead of userRow and userColumn in setElement, which are where you've stored the user inputs. row and column will refer to the classes member variables, which are both 5 since you set it up as a 5x5 matrix, so above the max index of 4. You also will need to conver the char to a string since your using a String[][]
System.out.println("You have entered: " + "\n" +
"Row " + userRow + "\n" +
"Column " + userCol + "\n" +
"Char to be entered: " + userChar);
newArray[row][column] = userChar;
The last line should be newArray[userRow][userColumn] = String.valueOf(userChar);. Though you probably want to check those values are less than row and column to avoid more of that exception.
Even with that fixed, your code currently has other issues. The biggest is that you're currently defininig and using a new array in most methods and not the member variable newArray, so the method calls to get/set/clear/print aren't using your instance like you expect, but new empty arrays each time. These should be manipulating this.newArray not creating their own to manipulate, which dies with their return. You'll need to work through fixing all of that before looking into looping over the user input and interacting with your array.
On the printing of 0's, that is a side affect of one of the above issues. In printMatrix you declare a new int[][] newArray and print that. The default value of int is 0, so you get all 0's. If you were using your String array you'd get all "nullnullnull.." for each row as String's default to null. If you want all blanks initially, you'll have to initalize the array to all empty strings in your constructor or handle the null when looping through the array printing a space instead.
On looping for user input, you'll also need to ask for it again inside of your loop before the while, as otherwise the user input will only be asked for once and you will forever loop with that option.
Good luck, this seems like a good excersize to familiarize yourself with OO and array maniupulation, but a lot of the issues in your code are outside the scope of a single SO answer and smells a bit like classwork. I got your example code fixed up and manipulating as you want with only a handful of changes, so youre close.
EDIT:
In the future, please don't continuously edit questions to reflect further development unless you leave the original in place and add to it and it still reflects a continuation of the original problem, as it makes answers and comments have no context. SO is meant more to be questions and answers about specific issues faced, not a forum for feedback on continued development. If you got past a specific problem via an answer, mark that answer as the solution and move any new issues into a new question, else you risk having your question closed. See the first few topics under https://stackoverflow.com/help/asking, especially https://stackoverflow.com/help/how-to-ask, to see what I mean. I'm being pretty gentle, but this community can not always be.
That being said, as you seem to be making a geniune effort here, here's a few more bits of advice based on your comments and edits.
If you want to prefill the rows with spaces, the
for (String[] row : newArray)
Arrays.fill(row, " ");
block of code would not go in print, as that would blank it out each time print is called. It should go into your constructor, so that it only happens once when the object is created.
Alternatively, if you wanted to deal with it in the print method, something like
System.out.print(newArray[i][j] == null ? " " : newArray[i][j]);
Would do the trick, using a ternary operator to print out " " instead of null when encountered.
You also don't need to new up the Scanner in those methods but its not affecting functionality.
I'm a student just starting out in Java; I get hung up on seemingly easy concepts and have had trouble finding the answer to this despite a lot of googling. The assignment asks to:
Prompt the user to enter the number of people
Create a String array of the given size
Prompt the user for the name of each person
Put each name in the String array you created
Use a Java for-each to print each name with the length of the name
The output should look something like:
"Person 1 is named Andrew, and their name is 6 characters long"
This is what I currently have coded.
System.out.print("Hello. Please enter the number of people: ");
int people = scan.nextInt();
String[] myPeople = new String[people + 1];
System.out.println("Enter the name of each person:");
for(int i = 0; i < myPeople.length; i++)
{
myPeople[i] = scan.nextLine();
}
for(String peoples : myPeople)
{
System.out.println(peoples);
}
As it stands right now, the program can collect input from the user, put it into an array, and then print the array back out.
Am I approaching this the wrong way? I can't think of how I would modify the last For to not just print all the names, and instead print out each one with the "Person X is named ... ", their name, and then the description of how many characters long their name is.
Read about string concatenation.
int j = 1;
for(String peoples : myPeople)
{
System.out.println("Person " + j + " is named " + peoples + " and their name is " + peoples.length() + " characters long");
j++;
}
+ operator is used for concatenation of the strings.
You are doing good. In last for loop you can just do something like:
int personNumber = 0;
for(String people: myPeople)
{
System.out.println(String.format("Person %d is named %s, and their name is %d characters long", personNumber + 1, people, people.length());
personNumber++;
}
And one thing I've noticed - why are you instantiating array using new String[people + 1]? Why this extra one person? Arrays indexes are numered from 0, so new String[5] would give you array of 5 persons.
Firstly, you should create an array of size people, not people + 1:
String[] myPeople = new String[people];
To produce output in the required the format, you need to use the + operator to join the strings together. Also, since the person's position in the array is required, you need to create a variable to store that:
int index = 1;
for (String person: myPeople) {
String output = "Person " + index + " is named " + person + ", and their name is " + person.length() + " characters long.";
System.out.println(output);
index++;
}
Alternatively, you can use print instead of println: (only showing code inside for loop)
System.out.print("Person ");
System.out.print(index);
System.out.print(" is named ");
System.out.print(person);
System.out.print(", and their name is ");
System.out.print(person.length());
System.out.println(" characters long.");
index++;
I'm currently working on this assignment for a class and I'm having a hard time getting my while loop to work. Can anyone assist me on figuring out why I can't get the user to enter y or n to either restart the loop or terminate it? Thank you so much!
import java.util.Scanner;
import java.text.NumberFormat;
public class EvenQuizzes {
public static void main (String[] args) {
String another="y";
double percent;
int answers;
int score = 0;
Scanner scan = new Scanner(System.in);
NumberFormat fmt = NumberFormat.getPercentInstance();
// Asks the user to input the amount of questions on the quiz
System.out.print("How many questions are on the quiz? ");
final int QUESTIONS = scan.nextInt();
System.out.println(); // spacer
int[] key = new int [QUESTIONS];
// Asks the user to enter the key
for (int i=0; i<key.length; i++){
System.out.print("Enter the correct answer for question "+ (i+1) +": ");
key[i] = scan.nextInt();
}
System.out.println(); // spacer
while (another.equalsIgnoreCase("y")) {
// Asks the user to enter their answers
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
// Grades the amount of questions right and gives the percentage
percent = (double)score/QUESTIONS;
System.out.println();
System.out.println("Your number of correct answers is: " + score);
System.out.println("Your quiz percentage: " + fmt.format(percent));
System.out.println();
System.out.println("Grade another quiz? (y/n)");
another = scan.nextLine();
}
}
}
So instead of this
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
you should try this
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
scan.nextLine();
At the end of your while loop, try adding this print statement:
System.out.println("Next line is >>>" + another + "<<<");
That should make it clear what you are getting from the scan.nextLine() call. It won't fix your problem, but it will make the issue obvious.
It has to do with that your scan is reading integers before getting the y/n from the user.
In this transition, the scan is reading a newline character instead of y. As a result, the another is a newline char and hence fails the while-loop condition.
To overcome this, the shortcut method is what #3kings had mentioned.
Another method is scan all inputs as string (nextLine) and then for the quiz part, parse for integer. It may seems a lot of work but you get to use parseInt and try/catch exception.
The task is to "Write a program that displays a user-indicated number of multiples for an integer entered by the user."
I suppose I do not need a completely direct answer (although I do want to know the methods/formula to use), as I want to use this as a learning experience in order to do and learn from the task myself. I really want to know about the process and which methods to use, along with finding a formula. :||
I'm really not sure how to write a code that displays a user-inputted number of a user-inputted integer. The hardest part seems to be writing the loop formula. Not sure where to start.
So far, I have:
import java.util.Scanner;
public class MultipleLooping
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
\\just stuff to base my code off of
int integer;
int numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
\\pretty much everything from here on out.. I'm not sure what to really do.
int n = integer;
int result = (integer * (numberMultiples));
while (result > 0){}
System.out.print(result);
}
} \\at the moment this code doesn't seem to have any running errors
I'm really not sure how to write a code that displays a user-inputted number of a user-inputted integer. The hardest part seems to be writing the loop formula. Not sure where to start.
NEW QUESTION
I need to loop my program as well. (By asking a question to the user first.) Mines isn't working, as it just keeps looping only the integer loop and doesn't let me type yes/no.
import java.util.Scanner;
public class MultipleLoops
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int integer, numberMultiples;
String repeat = "yes";
while (repeat != "no")
{
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
for (int i=1; i<=numberMultiples; i++){
System.out.println(integer + " * " + i + " = " + i*integer );
}
System.out.println("Would you like to do this again? Enter yes or no: ");
repeat = keyboard.nextLine();
}
}
}
Ok so you need to understand the problem first to know how to solve it
x = First input
n = Second input
you need to calculate n multiple of x
example with x = 3 and n = 10
To calculate 10 multiple of 3 we need to do :
1st multiple = x*1
2nd multiple = x*2
3rd multiple = x*3
...
n multiple = x*n
you can notice that these operations can be replaced by one for loop (notice first and last character of every line, it can be index of your loop )
Back to java :)
for (int i=1; i<=numberMultiples; i++){
System.out.println("Listing multiple N# " + i + " = "+ i*integer );
}
Replace your code with the following and try this code :
import java.util.Scanner;
public class MultipleLooping{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int integer,numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
for (int i=1; i<=numberMultiples; i++){
System.out.println("Listing multiple N# " + i + " = "+ i*integer );
}
}
}
Enter an integer:
3
How many multiples of 3 would you like to know?
7
Listing multiple N# 1 = 3
Listing multiple N# 2 = 6
Listing multiple N# 3 = 9
Listing multiple N# 4 = 12
Listing multiple N# 5 = 15
Listing multiple N# 6 = 18
Listing multiple N# 7 = 21
Do you want like this ? Below is the code
package com.ge.cbm;
import java.util.Scanner;
public class MultipleLooping
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//just stuff to base my code off of
int integer;
int firstEntered;
int numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
firstEntered = integer;
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
//pretty much everything from here on out.. I'm not sure what to really do.
for (int i=0;i<numberMultiples;i++){
integer=integer*firstEntered;
System.out.println(integer);
}
}
}
Output:
Enter an integer:
3
How many multiples of 3 would you like to know?
7
Listing the first 7 multiples of 3:
9
27
81
243
729
2187
6561
this should work
while(repeat.equals("yes"))
{
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
for (int i=1; i<=numberMultiples; i++)
{
System.out.println(integer + " * " + i + " = " + i*integer );
}
System.out.println("Would you like to do this again? Enter yes or no: ");
repeat = keyboard.nextLine();
repeat = keyboard.nextLine();
}
I'm currently working on a program and ran into an error while trying to execute a for loop. I want to declare a variable in the for loop, then break once that variable obtains a certain value, but it returns the error "cannot be resolved to a variable."
Here's my code
int i = -1;
for (; i == -1; i = index)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
int index = (input.indexOf('y'));
}
I want to run the output segement of my program until the user inputs yes, then the loop breaks.
The variable index's scope is local to the block of the for loop, but not the for loop itself, so you can't say i = index in your for loop.
You don't need index anyway. Do this:
for (; i == -1;)
or even
while (i == -1)
and at the end...
i = (input.indexOf('y'));
}
Incidentally, I'm not sure you want input.indexOf('y'); an input of "blatherskyte" will trigger this logic, not just "yes", because there's a y in the input.
Instead of using a for loop, you can do-while(it suits much better for this scenario.
boolean exitLoop= true;
do
{
//your code here
exitLoop= input.equalsIgnoreCase("y");
} while(exitLoop);
for indefinite loop, i would prefer while.
boolean isYes = false;
while (!isYes){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
isYes = input.equalsIgnoreCase("yes");
}
You cannot do this. If the variable is declared inside of the loop, then it is re-created every run. In order to be part of the condition for exiting the loop, it must be declared outside of it.
Alternatively, you could use the break keyworkd to end the loop:
// Should we exit?
if(input.indexOf('y') != -1)
break;
Here you want to use a while loop. Usually you can decide which loop to use by saying your logic out loud to yourself, While this variable is(not) (value) do this.
For your problem, initialize the variable outside of the loop, and then set the value inside.
String userInput = null;
while(!userInput.equals("exit"){
System.out.println("Type exit to quit");
userInput = scan.nextLine();
}