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.
Related
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.
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.
How do you write a for loop that will input 10 integer values from the user and keep track of smallest value entered? This is what I have so far. I'm so confused right now.
int value;
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
System.out.print("Enter 1st number:");
value = scan.nextInt();
This is a simple use of an if statement. You have to maintain a variable to keep track of lowest value entered and compare every input to it, if it is lower you replace it with the value new value.
I have provided a solution below, there are multiple ways of doing it. Try and see if you can find an alternative way so you can practice. Also notice the or statement if i == 0, analyze what happen if you remove that.
int value=0;
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 10; i++)
{
System.out.print( "Enter 1st number:" );
int inValue = scan.nextInt();
if(inValue < value || i==0 )
value = inValue;
}
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'm just getting back on the programming horse so I'm doing some basic problems in Java on CodeAbbey.com. I am given a standard input where the first integer in the input is the number of pairs followed by all subsequent inputs being pairs of numbers. I input this by just running the code and pasting it then using Scanner to read it. My code is supposed to add together each of those pairs of numbers individually then output each answer separated with a space. For example:
data:
3
100 8
15 245
1945 54
answer:
108 260 1999
Here is my attempt:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
for (int i = 1; i <= size; i++) {
int sum = in.nextInt() + in.nextInt();
System.out.print(sum);
if (i < size) {
System.out.print(" ");
}
}
}
}
The code actually works, but the issue is that it is not initially outputting the last sum. It prints all the sums up to the last one, but I have to press enter again for the last sum to print, and it prints one line down from all the others. This happens no matter the number of pairs or the platform I'm using; the last sum never prints until I once again hit enter. Any idea as to why this is occurring?
The Scanner won't receive any input until Enter is pressed.
When you press Enter, the line of text, e.g. "1945 54", is entered into the scanner. Now it can return the next int. The Scanner will block until it can read sufficient input, and if you don't press Enter yet, it will remain blocked. That is why pressing Enter allows the program to print the sum.
Until you hit enter, it is hanging on the input routine, because you might actually be preparing to add a more scannable data (or another digit to the last number) you typed.
You should split the printing out part in a seperate loop not in that for loop that also asks for value inputs.
So with the code you have currently modified would be:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
for (int i = 1; i <= size; i++) {
int sum = in.nextInt() + in.nextInt();
System.out.print(sum);
}
for (int i = 1; i <= size; i++){
if (i < size)
System.out.print(" ");
}
}
}
}
splitting it should stop you needing to press enter before it prints the last value