2D array scanner validation - java

Anyone able to steer me in the right direction. I am building a simple mark program where I get input from Scanner and insert it into my 2D array. I want to validate my input so that it isn't below 0 or above 100 but if I have the incorrect number I don't want the array to move to next position.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);//naming the scanner
String [] student = {"Mark","Jen","Gaby","John","Michael","James"};
String [] subject = {"Digital electronics","Analogue electronics","Maths","Networks","Telecommunications",
"Computer applications","Software developemnt","Workshop"};
String [] printSub = {"Digit","Analo","Maths","Netwo","Telec","Appli","Softw","Works"};
int maxRow = 6;//setting max row amount int
int maxCol = 8;//set max column amount int
int [][] mark = new int [maxRow][maxCol];//declaring the int array and setting the row & column max.
int i = 0, j = 0;//declaring i and j for use in the for loops
int maxMark = 0;//declaring for use in if statement to find highest mark
int minMark =100;//Declaring for use in if statement to find lowest mark
for(i = 0; i < maxRow; i++)
{
for(j = 0; j < maxCol; j++)
{
System.out.print("Please enter "+student[i]+" mark for "+subject[j]+" and press return :");
mark[i][j]= input.nextInt();
}
}
for(i=0; i < maxRow; i++)
{
for(j=0; j < maxCol; j++)
{
if (i == 0 && j == 0)
{
System.out.print("Student \t");
for(int sub = 0; sub < 8; sub++)
{
System.out.print(printSub [sub]+"\t");
}
System.out.println();
System.out.println();
}
if(i < maxRow && j == 0)
{
System.out.print(student[i]+"\t \t ");
}
System.out.print(mark [i][j]+"\t");
}
System.out.println();
System.out.println();
}
}
I am not looking for the answer i am looking for more of a nudge in the direction where I may be able to figure out the answer myself.
Thanks for the help in advance.
Matt

Nudge : You do not directly insert number into array, you insert it into some temporary variable, checks it and then decide if you save it or you ask again (while cycle needed)
Spoiler 1 : Here is complete solution, if you want to do it yourself, do not look there :) :
for (i = 0; i < maxRow; i++) {
for (j = 0; j < maxCol; j++) {
System.out.print("Please enter ");
int number = input.nextInt();
boolean isItOk = false;
while (isItOk == false) {
if (number < 0 || number > 100) {
System.out.println("You shall not insert a value below 0 or bigger than 100! Try it again");
number = input.nextInt();
} else {
isItOk = true;
}
}
mark[i][j] = number;
}
}
Spoiler 2 : This is a little nicer code, but for beginners, I would recommend the approach of Spoiler 1, because it is always usable. In more complex problems, the Spoiler 2 solution is not always possible.
for (i = 0; i < maxRow; i++) {
for (j = 0; j < maxCol; j++) {
System.out.print("Please enter ");
int number = input.nextInt();
while (number < 0 || number > 100) {
System.out.println("You shall not insert a value below 0 or bigger than 100! Try it again");
number = input.nextInt();
}
mark[i][j] = number;
}
}

Scanner s = new Scanner(System.in);
int number =0;
System.out.print("Please enter ");
while(true)
{
number = s.nextInt();
if(number > -1 && number < 101)
break;
System.out.println("Marks should be between 0 and 100, Please enter");
}
You also need to validate if input is integer, which can be done through exception handling

Related

Rhombus with letters - Java

I am new to programming and started with learning c# and now java. I came across a task creating a rhombus where the user inputs the height (odd numbers only) and the char for the rhombus.
I created a for loop for the height and another loop for the characters. Here is my output:
h: 7
c: k
k
jkj
ijkji
hijkjih
ghijkjihg
But I want the output to be:
h: 7
c: k
k
jkj
ijkji
hijkjih
ijkji
jkj
k
How can I develop my logic to apply it to my code.
Here is my code:
Scanner in = new Scanner(System.in);
System.out.print("h: ");
int h = in.nextInt();
System.out.print("c: ");
char c = in.next().charAt(0);
if(h%2==0){
System.out.println("Invalid number!");
return;
}
int count = 1;
int space = 1;
for (int i = 2; i < h; i++)
{
for (int spc = h - space; spc > 0; spc--)
{
System.out.print(" ");
}
if (i < h)
{
space++;
}
else {
space--;
}
for (int j = 0; j < count; j++)
{
System.out.print(c);
if (j < count/2)
{
c++;
}
else {
c--;
}
}
if (i < h)
{
count = count + 2;
}
else {
count = count - 2;
}
System.out.println();
}
Any help is highly appreciated.
Your code contains the following flaws:
count and space variables depend on the values of i and h, which makes it very hard to keep track of and understand. You should avoid hidden dependencies in your code in general
you change the value of c all the time. It makes it very hard to keep track of. You should never change its value
your function is too big
strange values like i = 2, count/2, incrementing by 2
incorrect conditions
You have one loop which increments i. What you need is a second loop which decrements the value of i. And you should also use the same approach for printing of the characters (2 loops for both sides). Let me show you:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// load parameters
System.out.print("h: ");
int h = in.nextInt();
System.out.print("c: ");
char c = in.next().charAt(0);
// validate parameters
if (h % 2 == 0) {
System.out.println("Invalid number!");
return;
}
for(int i = 0; i <= h/2; i++) {
printSpaces((h+1) / 2 - i - 1);
printLine(c, i);
System.out.println();
}
for(int i = h/2-1; i >= 0; i--) {
printSpaces((h+1) / 2 - i - 1);
printLine(c, i);
System.out.println();
}
}
private static void printLine(char character, int sideWidth) {
for (int j = sideWidth; j >= 0; j--)
System.out.print((char) (character - j));
for (int j = 1; j <= sideWidth; j++)
System.out.print((char) (character - j));
}
private static void printSpaces(int numberOfSpaces) {
for (int i = 0; i < numberOfSpaces; i++) {
System.out.print(" ");
}
}
which gives you the desired output.
public class Rhombusstar
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter N : ");
int n=sc.nextInt();
System.out.print("Enter Symbol : ");
char c = sc.next().charAt(0);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n-i;j++)
{
System.out.print(" ");
}
for(int j=1;j<=n;j++)
{
System.out.print(c);
}
System.out.println();
}
}
}

Numerical triangle using java

How do I stop the loop if the number reaches the n? i tried the break; but the loop still doesn't stop.
Scanner in = new Scanner(System.in);
int i, j;
int n = in.nextInt();
int number = 1;
for(i = 1; i <= n; ++i) {
for(j = 1; j <= i; ++j) {
System.out.print(number);
++number;
if(number >= n){
break;
}
}
System.out.println();
}
input: 9
expected output:
1
23
456
789
or
input: 12
expected output:
1
23
456
78910
1112
Break and Labeled break should be avoided in code. So you can use loops as below:
public static void main(final String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter input number:");
int n = in.nextInt();
System.out.println("You have entered : " + n);
for (int i = 1, k = 1; k <= n; i++) {
for (int j = 0; j < i && k <= n; j++, k++) {
System.out.print(k);
}
System.out.println();
}
}
Printing k variable which is initialized in outer and updated in inner loop.
Putting condition to break inner and outer loop to check k with input variable
EDITED : To understand it better:
i variable is used to maintain the number of rows we need to print.
j variable is used to maintain the number to elements to print in each row.
In most of placed the value which is being print is in context with either row number or element number in row, but here print value is not in sync with it, so we are maintaining it in 2rd variable k.
Use the labeled break statement and you can break from the nested loop:
loop:
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= i; ++j)
{
System.out.print(number);
++number;
if (number > n) //not (number >= n)
{
break loop;
}
}
System.out.println();
}
There are many ways of doing this. The most straightforward one is to use a label to break out of several loops at once:
outer: for(i = 1; i <= n; ++i) { // a label is a word followed by :
inner: for(j = 1; j <= i; ++j) { // you can declare labels without using them
System.out.print(number);
++number;
if(number >= n){
break outer; // break inner would be equivalent to what you had
}
}
System.out.println();
}
However, these break statements with labels look suspiciously similar to gotos, and gotos are frowned upon. A more teacher-friendly version would be to use a boolean flag, and check the flag in each loop:
boolean finished = false;
for(i = 1; i <= n && ! finished; ++i) {
for(j = 1; j <= i && ! finished; ++j) {
System.out.print(number);
++number;
if (number >= n) {
finished = true; // no need to break - loops condition will now be false
}
}
System.out.println();
}
Note that this introduces an extra newline, which you generally want to make sure that whatever you print next appears on a different line.
Another option is to simply complicate your initial condition, without any flags:
for(i = 1; i <= n && number < n; ++i) {
for(j = 1; j <= i; ++j) {
System.out.print(number);
++number;
}
System.out.println();
}
I would recommend, for readability purposes, version 2. Additionally, I would write it as follows:
boolean finished = false;
for(int i = 0; i < n && ! finished; ++i) {
for(j = 0; j < i && ! finished; ++j) {
System.out.print(number++);
if (number >= n) {
finished = true;
}
}
System.out.println();
}
The key differences are using 0 to n-1 counting to repeat something n times (most programmers are very accustomed to that, instead of counting from 1 to n), and defining loop variables within the for, so that trying to use them outside of their loops is an error. This helps to avoid accidental reuse of variables.
import java.util.Scanner;
public class Tester{
public static void main(String []args){
Scanner in = new Scanner(System.in);
int i, j;
int n = in.nextInt();
int number = 1;
loop:
for ( i = 1; i <= n; ++i){
for ( j = 1; j <= i; ++j){
System.out.print(number);
++number;
if (number > n)
{
break loop;
}
}
System.out.println();
}
}
}
by using a for loop with a nested one you can achieve it like this:
you have a row which is incremented by 1 on each row (line)
you have a column variable which is increasing by one on each line or row
you have a number with start to print from 1 till the inputed number for example it was entered 12.
in inner loop you need to check the column be less or equal to row and the incremented number be less the entered number.
Scanner in = new Scanner(System.in);
System.out.print("Enter a Number: ");
int n = in.nextInt();
int number = 1;
for (int row = 1; row <= n && number <= n; row++) {
for (int column = 1; column <= row && number <= n; column++) {
System.out.print((number++) + " ");
}
System.out.println();
}

Looking to Create a Randomized Array using Java

I'm building out a user defined array as a game board. The characters used "O" and "." have to be randomized and the "O" has to appear more than once.
This is what I have thus far.
import java.util.Scanner;
public class PacMan {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Input total rows:");
int row = input.nextInt();
System.out.println("Input total columns:");
int column = input.nextInt();
boolean[][] cookies = new boolean[row+2][column+2];
for (int i = 1; i <= row; i++)
for (int j = 1; j <= column; j++);
cookies [row][column] = (Math.random() < 100);
// print game
for (int i = 1; i <= row; i++)
{
for (int j = 1; j <= column; j++)
if (cookies[i][j]) System.out.print(" O ");
else System.out.print(". ");
System.out.println();
}
}
}
The output, for example, produces a 5 x 5 grid, but the "O" only appears once and is at the bottom right of the grid.
Assistance randomizing the "O" and "." and having the "O" appear in random fashion throughout the board which is initialized by the user input via Scanner.
Here is the updated code which is producing the output that I'm looking for and is user defined.
import java.util.*;
public class PacManTest
{
public static void main(String[] args)
{
char O;
Scanner input = new Scanner(System.in);
System.out.println("Input total rows:");
int row = input.nextInt();
System.out.println("Input total columns:");
int column = input.nextInt();
char board[][] = new char[row][column];
for(int x = 0; x < board.length; x++)
{
for(int i = 0; i < board.length; i++)
{
double random = Math.random();
if(random >.01 && random <=.10)
{
board[x][i] = 'O';
}
else {
board[x][i] = '.';
}
System.out.print(board[x][i] + " ");
}
System.out.println("");
}
}
}
The main issue is the typo in the first loop:
cookies [row][column] = (Math.random() < 100);
should be
cookies [i][j] = (Math.random() < 100);
Second, Math.random() returns a value greater than or equal to 0.0 and less than 1.0 (doc). So, (Math.random() < 100); will always be true. If you want a 50% chance of an O or . use:
cookies[i][j] = Math.random() < 0.5;
Also, not sure what your motivation is for using a starting index of 1 but array indexes start at 0.

What would the condition be?

I'm trying to make a program that asks a user for two numbers. I want to determine how many times a certain value appear in the sequence of numbers. For instance, if user entered 10 and 20 the number "1" would appear 9 times. What I am wondering is what condition would I have to set to see how many times the number "1" would appear.
This is what I got so far...
System.out.println("Enter a number: ");
int no1 = scan.nextInt();
System.out.println("Enter a number: ");
int no2 = scan.nextInt();
int i;
int j = 0;
for(i = no1; i <= no2; i++){
if(){ // Some condition here
j++;
}
}
System.out.println(j);
}
Any other tips and tricks on how to make my code efficient would also be greatly appreciated.
for (int i = no1; i <= no2; i++) {
if(String.valueOf(i).contains("1"))
int occurances = StringUtils.countOccurrencesOf(String.valueOf(i), "1");
j+=occurances
}
Assuming that you want to count the occurrences of a digit within a list of numbers you could e.g. use modulo:
int[] occurrences = new int[10];
for (int i = n1; i <= n2; i++) {
int currentNumber = Math.abs(i);
while (currentNumber > 0) {
occurrences[currentNumber % 10]++;
currentNumber /= 10;
}
}
or parse the string representation of the number
int[] occurrences = new int[10];
for (int i = n1; i <= n2; i++) {
String cur = String.valueOf(Math.abs(i));
for (int j = 0; j < cur.length(); j++) {
char currentChar = cur.charAt(j);
if (currentChar != '-')
occurrences[Character.getNumericValue(currentChar)]++;
}
}
occurrences will contain the counts for digits from 0 to 9;
Edit: Added handling for negative integers.

Need help centering text output

import java.util.Scanner;
public class diamond {
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer");
int lines = scan.nextInt();
for(int counter = 1; counter <= lines; counter++)
{
if (counter%2 != 0)
{
for(int count2 = 1; count2 <= counter; count2++){
System.out.print("*");
}
System.out.println();
}
}
}
}
I am supposed to ask the user for a number of lines and output a diamond made of asterisks that number of lines tall. I need some help figuring out how to center the asterisks. I know for strings there is some String.utils method or something, but the output comes in pieces based on a for loop, so I don't think that really works here. If it does, by all means let me know though.
You need to print a certain amount of spaces before each line. Then, you would need another for loop for the opposite.
Try this code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer ");
int lines = scan.nextInt();
for (int counter = 1; counter <= lines; counter++) {
if (counter % 2 != 0) {
for (int i = 0; i < lines - (counter / 2) - 3; i++) {
System.out.print(" ");
}
for (int count2 = 1; count2 <= counter; count2++) {
System.out.print("*");
}
System.out.println();
}
}
for (int counter = lines - 1; counter >= 1; counter--) {
if (counter % 2 != 0) {
for (int i = 0; i < lines - (counter / 2) - 3; i++) {
System.out.print(" ");
}
for (int count2 = 1; count2 <= counter; count2++) {
System.out.print("*");
}
System.out.println();
}
}
}
I think you should prepare a string to print out on each line, then you will know exactly how many characters it has, when the line increases, remove the two '*' in center of the string and add one " " in front of it, then print it out again.

Categories