This is the link the problem that I am trying to solve: https://dmoj.ca/problem/dmopc14c1p5
Here is the code that I have written for taking in input.
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
int y = kbd.nextInt(); //number of rows
int x = kbd.nextInt(); //number of columns
int initX = kbd.nextInt(); //initial starting position
int initY = kbd.nextInt();
int endX = kbd.nextInt(); //ending position (main office)
int endY = kbd.nextInt();
char [] [] maze = new char [y][x];
for (int i = 0; i < y; i++)
{
for (int j = 0; j < x; j++)
{
maze[i][j] = kbd.next().charAt(0);
}
}
//For checking
for (int i = 0; i < y; i++)
{
for (int j = 0; j < x; j++)
{
System.out.print(maze[i][j]);
}
System.out.println();
}
}
However, I don't know how to properly take in the char input in the for loop. I used the scanner.next().charAt(0) method I found with this link (How to take input for 'char' array in Java?), but it results in an infinite loop that does not end no matter how many characters I input.
What am I doing wrong?
Update:
This is the input that I will be receiving (There are no white spaces between characters):
OOXOO
OXOXO
OOOXX
XOXOX
OOOOO
How should I modify my code to make reading this input possible?
Your code works properly. Just remembers that you need to type atleast x*y (your variable name) times of char.
EDIT: I just saw your update. We need to think about it a little bit.
.charAt(0)
Only takes the first character of a string and return it. If you want to take "ooxoo" and turn it into ['o','o','x','o','o'], you can use the toCharArray method on strings. However if you do this, your for loop will loop longer than needed. If you know your sets of input, you can only loop through n numbers of strings and accept them and convert them into array. Let me know if you want me to go more in details.
The java.util.Scanner.next() method finds and returns the next
complete token from this scanner.
Every time you call kbd.next().charAt(0), you call next() and get a complete token. The tokens, by default, are separated by whitespace.
You also need to hit ENTER before System.in makes an data available.
So, enter your characters separated by spaces and end the input with a carriage return.
Related
Basically I'm trying to make an method that would return an array so that I can use this list later down the line, only problem is I cant find a way to terminate user input other than using 0. I've tried to take in user input using a string then parsing it into an int but that only results in an error when a non-number character is used.
public static double[] input()
{
double[] arr = new double[100];
//int count = 1;
for(int i = 0; i < arr.length; i++)
{
System.out.print("Insert a number or Zero to stop: ");
double input = scan.nextDouble();
arr[i] = input;
if(input == 0)
{
break;
}
count++;
}
return arr;
}
I think that instead of the condition for(int i = 0; i < arr.length; i++) you could simply ask the user how many digits he/she wishes to enter and then pass that value to the for loop to execute lie for(int i = 0; i < length; i++) where length is the user desired size of array.
If you do not want to ask the user then do this accept the numbers as single characters instead of a string then before parsing it into int just check if the entered character is an escape sequence(\n or \r) arr[index]='\n' or'\r' then you can terminate the input process.
Note: this process is only for integer input if the user enters a character it accepts it just make sure that the entered character is a number.
I suggest you put the print statement out of the for loop as it will be repeated as long as the for loop runs, it is not nice to have those instructions displayed again and again.
I want to...
create an asterisk triangle, using Java, that matches the length of whatever number (Between 1-50) the user enters.
Details
The first line would always start with an asterisk.
The next line would increment by one asterisk until it matches the
user's input.
The following lines would then decrement until it is back to one
asterisk.
For instance, if the user was to enter 3, then the output would have one asterisk on the first line, two asterisks on the second line, three asterisks on the third line, and then revert back to two asterisks on the following line before ending with an asterisk on the last line.
What I've tried so far
I am required to use nested for loops. So far, I tried to test it out using this practice example I made below. I was only able to create on output of the numbers. I also have some concepts of outputting asterisk triangles. How can I apply the concept of this code to follow along the user's input number?
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int count, index = 0, value, number;
System.out.println("This program creates a pattern of numbers " );
System.out.println("Based on a number you enter." );
System.out.println("Please enter a positive integer. " );
count = keyboard.nextInt();
value = count;
for (index = 1; index <= count; index++)
{
for (number = value; number >= 1; number--)
{
System.out.println(number);
}
value--;
System.out.println();
}
}
}
Here's how i would proceed
write a method printAsterisks that takes an int N as parameter and writes a line of N asterisks. You wil need a for loop to do so.
call printAsterisks in a for loop that counts from 1 to COUNT
call printAsterisks in a second loop that counts down from COUNT-1 to 1
That should do the trick.
Also, as a side note, you should close your scanner. The easy way to do so is enclose ot in a try-with-resource like so :
try (Scanner keyboard = new Scanner(System.in);) {
// your code here
}
Let us know the version of the program taht works (or the question you still have) :)
HTH
Here is what you want:
public class Asterisk {
private static final String ASTERISK = "*";
private static final String SPACE = "";
private static int LENGTH;
public static void main(String[] args) {
try{
readLength();
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
}catch (Exception e) {
System.out.println("You must enter a number between 1 and 50.");
}
}
static void readLength(){
System.out.println("Enter asterisk's length (1-50)");
LENGTH = Integer.parseInt(System.console().readLine());
if (LENGTH<=0 || LENGTH>50)
throw new NumberFormatException();
}
static void drawLine(int asterisks){
StringBuilder line = new StringBuilder();
int spacesLeft = getLeftSpaceCount(asterisks);
int spacesRight = getRightSpaceCount(asterisks);
for (int i=0; i<spacesLeft; i++) {
line.append(SPACE);
}
for (int i=0; i<asterisks; i++) {
line.append(ASTERISK);
}
for (int i=0; i<spacesRight; i++) {
line.append(SPACE);
}
System.out.println(line.toString()+"\n");
}
static int getLeftSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
int mod = spaces%2;
return spaces/2 + mod;
}
static int getRightSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
return spaces/2;
}
}
I am required to use nested for loops
Yes, the main logic lies there...
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
The triangle using 5 as input.
*
**
***
****
*****
****
***
**
*
Tip:
There is an easier way to get input from the user usingSystem.console().readLine().
In regards to the printing part, I wanted to clean up the answers a little:
int input = 3; //just an example, you can hook in user input I'm sure!
for (int i = 1; i < (input * 2); i++) {
int amount = i > input ? i / 2 : i;
for (int a = 0; a < amount; a++)
System.out.print("*");
}
System.out.println();
}
For our loop conditions, a little explanation:
i < (input * 2): since i starts at 1 we can consider a few cases. If we have an input of 1 we need 1 row. input 2, 3 rows. 4: 5 rows. In short the relation of length to row count is row count = (length * 2) - 1, so I additionally offset by 1 by starting at 1 instead of 0.
i > input ? i / 2 : i: this is called a ternary statement, it's basically an if statement where you can get the value in the form boolean/if ? value_if_true : value_if_false. So if the row count is bigger than your requested length (more than halfway), the length gets divided by 2.
Additionally everything in that loop could be one line:
System.out.println(new String(new char[i > input ? i / 2 : i]).replace('\0', '*'));
And yeah, technically with a IntStream we could make this whole thing a one-line, though at that point I would be breaking out newlines for clarity
Keep in mind, I wouldn't call this the "beginner's solution", but hopefully it can intrigue you into learning about some other helpful little things about programming, for instance why it was I replaced \0 in my one-line example.
I'm quite new to java.
I'm trying out some things for a project but I don't get why this does not work.
The goal here is to let the user input numbers separated by spaces and end with a letter. The program then needs to count the even and odd indexed numbers and output which sum is larger.
I already made this successfully when the amount of numbers given was a constant, but now I want to make it adapt to the user input.
Because I want to put the numbers in an array I need to know the length of this array. To get this I want to count the amount of numbers the user puts in so I can create the appropriate length array.
For some reason the while loop does not end and keeps running. How do I count the amount of numbers put in?
EDIT
I've added in.next(); in the first while loop so it is not stuck at the first input element. This brings me to a further problem however of having two while loops trying to loop through the same input. I have tried to create a second scanner and resetting the first one, but it does not get the second loop to start at the first element. Previous answers show that this is not possible, is there a way to put this in one while loop while still using arrays to store the values?
P.S. The input values should be able to be any positive or negative integer.
Here is my complete code:
import java.util.Scanner;
public class LargerArraySum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int length = 0;
System.out.println("Enter your numbers seperated by spaces, end with a letter");
while(in.hasNextInt()) {
length++;
in.next();
}
System.out.println(length);
int arra[] = new int[length];
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
int evenSum = EvenArraySum(arra);
int oddSum = OddArraySum(arra);
if(evenSum<oddSum) {
System.out.println("The sum of the odd indexed elements is bigger");
} else if(oddSum<evenSum) {
System.out.println("The sum of the even indexed elements is bigger");
} else {
System.out.println("The sum of the odd and even indexed elements is equal");
}
}
public static int EvenArraySum(int[] a) {
int sum = 0;
for(int i=1;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the even indexed elements is: " + sum);
return sum;
}
public static int OddArraySum(int[] a) {
int sum = 0;
for(int i=0;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the odd indexed elements is: " + sum);
return sum;
}
}
add in.next(); in the loop. Actually you don't need array. You can sum even and odd indexed numbers while reading without saving them.
1) Your first while-loop does not work because the iterator is always checking for further numbers in from the same position.
Example:
Position 0 1 2 3 4 5
Value 1 3 5 7 9 0
At start the iterator points to position 0. If you call hasNextInt() it will check if position 1 is available, in this case it will be true. At this moment the interator still points to position 0. So you increase your length and do the same thing again, so you have an infinite loop.
To move the iterator to the next position you need to call nextInt().
2) You can't iterate over the same Scanner with a second while-loop in that way. If you would correct you first while-loop the iterator would point to position 5 (it reached the end of the scanner). So the check for hasNextInt() will be false and the second while-loop will not be entered.
3) The comments already mentioned it, you could use an ArrayList for this use case like so:
final ArrayList<Integer> input = new ArrayList<>();
while ( in.hasNextInt() ) {
input.add( in.nextInt() );
}
System.out.println( input.size() );
( or like kitxuli mentioned in his answer, dont even store the values, just count them in the first while-loop)
Your code has 2 major problems . The first and the second while loops lets take a look at your first loop .
while(in.hasNextInt()) {
length++;
}
your condition in.hasNextInt() made you insert input because no variable was initialized with in.nextInt but also returns either [true] or [false] so as long as its true it will add to the length variable without prompting you to insert a [new input] .so the code should look like.
Int length = 0;
int k ;
while(in.hasNextInt()) {
length++ ;
k = in.nextInt();
}
you insert the input into an initialized variable k for ex then prompt the user to further input into k after adding to [length] then the loop will check your condition without prompting user for input.
Lets look at your second while loop.
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
In in.NextInt() you are prompting the user to enter new input once again so you don't need int x.Not even the while loop .However you MUST declare a new scanner in this ex: I call it c .The code should look like this.
int [] a = new int [length];
Scanner c = new Scanner (System.in);
for(int i=0;i<length;i++) {
if (c.hasNextInt()){
a[i] = c.nextInt();
} else
break;
}
You must add the if statement because if you get an alphabet in the int array you will get an exception error .The array a[i] will not prompt the user.
Of course it isn't practical to make the user enter the values twice so a better code to implement without using ArrayList class which I think you may not know very well is by using an empty String .
NEW CODE :-
String g = "";
String j ="";
int y ;
int q=0;
int w = 0;
while (in.hasNextInt())
{
y = in.nextInt();
g =g+y+",";
q++;
}
int arra [] = new int [q];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(',')){
arra[w]=Integer.parseInt(j);
System.out.println(arra[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
Another even better code :-You just insert your numbers separated by spaces without a letter ,hit enter and the array is filled.
Scanner in = new Scanner (System.in);
String g = "";
String j ="";
int y ;
int q=0;
int i=0;
int w = 0;
System.out.println("inset your input separated by spaces");
g = in.nextLine();
while(i<g.length()){
if((g.charAt(i))==(' ')){
q++;
}
i++;
}
int a [] = new int [q+1];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(' ')){
a[w]=Integer.parseInt(j);
System.out.println(a[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
a[w]=Integer.parseInt(j);
System.out.println(a[w]);
I have an array with 2 spots in it(it must have 2 spots in the beginning ). i need to get user input and double the array when user enters more than the array can hold. Also Upon entering -1 the user input should stop. The array must also not accept duplicates.
i don't know how to have the not accept duplicates and end the program when the user entters -1 while still doubling the array every time it fills up.
Here's what i have so far but its flawed and wont run properly.
public class GroupArrays {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int [] numbers = new int[2];
int x;
int n=0;
for( int i = 0; i<numbers.length; i++){
System.out.println("Please enter number");
int number = input.nextInt();
while ( input.hasNextInt() )
{
x = input.nextInt();
if ( n == numbers.length )
{
int[] h;
h = new int[ 2*numbers.length ];
for ( int i1 = 0; i1 < numbers.length; i1++ )
h[i1] = numbers[i1];
numbers = h;
}
if(x == -1){
break;
}
numbers[n] = x;
n++;
}
for ( int i1 = 0; i1 < numbers.length; i1++ )
System.out.println( numbers[i1] );
}
}
I can figure out how to do all the things individually but it becomes difficult when i have to do them all to 1 array and do user input.
PS. I feel like i have made this more complicated than it needs to be.
I'm only give you hints on how to solve the problem, and on how to write code that is easier to understand and maintain, even (and most importantly) by yourself.
Split the code in methods, doing simple tasks. Don't try to write everything as a giant piece of code.
The pseudo code of the algorithm would be
loop
ask and get input number
if (number is -1)
break out of the loop
else if array already contains number
print error message
else
if no space left in array
array = copy of array with doubled length
store number in next available index in array and increment the next available spot index
end of loop
print the array
Now, you can see that there are things that can be implemented easily as separate methods:
ask and get input number
check if array already contains number
copy of array with doubled length
print the array
Start by writing the signature of these simple methods, without implementing them. Then write the algorithm by calling these methods.
Then implement the simple methods one by one and test them one by one. You can do that, for now, by just writing a main method that calls them with hard-coded arguments, and see if they do what you expect them to do.
Once every of them is written and tested, test the main algorithm. If you made a mistake, iterate, by re-testing the methods you had to modify.
While coding all the methods, choose names that indicate clearly what the variables represent, and what the methods do, even if they're long. For example, nextAvailableIndex is much much clearer than x. Using good names helps everyone, including you, to understand the code and find bugs.
Also, indent the code strictly, as you type. The code you posted is not indented correctly, which makes it difficult to understand its structure. Stick to 4 spaces as indentation level, and always use curly braces around the body of your if, for, etc. ALways place them after the if/for, and not on the next line. Be consistent.
public class GroupArrays {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int [] numbers = new int[2];
int x;
int n=0;
for( int i = 0; i<numbers.length; i++){
System.out.println("Please enter number");
int number = input.nextInt();
while ( input.hasNextInt() )
{
x = input.nextInt();
if ( n == numbers.length )
{
int[] h;
h = Arrays.copyOf[numbers,2*numbers.length ]; //change
}
if(x == -1){
break;
}
numbers[n] = x;
n++;
}
for ( int i1 = 0; i1 < numbers.length; i1++ )
System.out.println( numbers[i1] );
}
}
Use Arrays.copyOf(array_name,array_length); to create new arrays with varying lengths.
I want to write a program that figures out how many times a certain set of characters repeats itself in a longer set of characters (several times for several different set of characters)
I tried to achieve this by "importing" the long set of characters into a char array, and then make a 2D array for all the shorter sets of characters that I want to check the occurence of.
Then, I wanted my for loop to create an "interim" array of the same length as the short arrays have and compare it to each of them, however, the program keeps returning 0 occurences no matte what... And is also taking too long to compute when checking longer arrays with loads of character sets.
import java.util.*;
public class A {
public static void main (String [] args) {
Scanner sc = new Scanner (System.in);
//Preberi podatke
int dolzinaDolgi = sc.nextInt(); //D
int dolzinaKratki = sc.nextInt(); //d
int stKratkih = sc.nextInt(); //n
sc.nextLine(); // prehod v novo vrstico
char [] Dolgi = sc.nextLine().toCharArray(); //prebrano dolgo zaporedje
char [][] TabelaKratki = new char [stKratkih][dolzinaKratki];
int [] results = new int [stKratkih];
for (int i=0; i<stKratkih; i++) {
TabelaKratki[i]=sc.nextLine().toCharArray();
}
for (int i=0; i<dolzinaDolgi-dolzinaKratki; i++) {
char [] vmesnoZaporedje = new char [dolzinaKratki];
vmesnoZaporedje = Arrays.copyOfRange (Dolgi, 0+i, dolzinaKratki+i-1);
for (int j=0; j<stKratkih; j++) {
if (TabelaKratki [j] == vmesnoZaporedje) {
results [j] += 1;
}
}
}
for (int index = 0; index<stKratkih; index++) {
System.out.println(results[index]);
}
}
}
Perhaps regular expression is much better.
1. Convert the text to be searched into a pattern.
2. Store all different sets of characters into array.
3. Loop the array and loop to find occurrences using the pattern.
Refer to this answer for count the occurrences. java regex match count