I'm fairly new at coding and in java in general but I'm hoping that I could get this figured out. I have a do while loop and inside that, I have a while statement if the incorrect value is input in the Scanner. However, when I run the code it always runs the while command once regardless of whether it is incorrect or correct and then runs the code correctly.
import java.util.Scanner;
public class Practice {
public static void main (String [] args) {
int x = 0;
int i = 0;
int n = 0;
String S1 = "";
Scanner user = new Scanner(System.in);
do
{
System.out.println("Enter an integer between 1 and 15: ");
x = user.nextInt();
while ( x < 1 || x > 15);
{
System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
x = user.nextInt();
}
n = 1;
}
while (n != 1);
for (i = 1; i <= x; i++)
{
S1 = S1 + "X";
}
for (n = 1; n <= x; n++)
{
System.out.println(S1);
}
}
}
Thank you so much in advance.
Remove the extra ; from your while loop
Like this:
while ( x < 1 || x > 15){
System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
x = user.nextInt();
}
while ( x < 1 || x > 15);
The Semi-Colon will terminate the logic and the control will pass to the next line always. Be careful while you code :D
Remove the extra semicolon in the while.
Also close the scanner object(user).
Check the updated code.
public class Practice {
public static void main(String[] args) {
int x = 0;
int i = 0;
int n = 0;
String S1 = "";
Scanner user = new Scanner(System.in);
do {
System.out.println("Enter an integer between 1 and 15: ");
x = user.nextInt();
while (x < 1 || x > 15)
{
System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
x = user.nextInt();
}
n = 1;
} while (n != 1);
for (i = 1; i <= x; i++) {
S1 = S1 + "X";
}
for (n = 1; n <= x; n++) {
System.out.println(S1);
}
user.close();
}
}
Related
Easiest way to explain my problem is to give you an example. Lets say I have 2 values X and Y. I wan't to ask the user to enter X lines with Y elements and they should be only 0s and 1s and then enter that values in array.
Example
x=3 y=3
User input:
101
100
000
And then how to separate string to enter each value in different cell.
EDIT 1:
import java.util.Scanner;
public class RedVsGreen {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int x,y;
String line;
String[] lineVector = new String[3];
while ( lineVector.length !=2 || (Integer.parseInt(lineVector[0]) >= 1000 || Integer.parseInt(lineVector[0]) <= 1)
|| (Integer.parseInt(lineVector[1]) <= 1 || Integer.parseInt(lineVector[1]) >= 1000)){
System.out.print("Please enter x and y, comma separated (more than 1 and less than 1000):");
//read x,y
line = scanner.nextLine();
//separate all values by comma
lineVector = line.split("\\s*,\\s*");
}
//parsing the values to Integer
x = Integer.parseInt(lineVector[0]);
y = Integer.parseInt(lineVector[1]);
for (i = 0 ; i < x; i++){
}
//
// int[][] field = new int[x][y];
// for (int row = 0; row < field.length; row++) {
// System.out.println("");
// for (int col = 0; col < field[row].length; col++) {
// field[row][col] = 9; //dummy value
// System.out.print(field[row][col] + " ");
// }
// }
//
}
}
Receiving x and y
while ( lineVector.length !=2 ...)
Your while condition is too complicated, a do while format matches this problem much better since you are going to get the values at least once, and the code is more readable.
Also you could have used x instead of Integer.parseInt(lineVector[0]) (same for y) instead of repeating the process, this would have shortened the condition.
String line;
String[] lineVector;
int x = -1, y = -1;
do {
System.out.print("Please enter x and y, comma separated (more than 1 and less than 1000):");
line = scanner.nextLine();
lineVector = line.split("\\s*,\\s*");
if(lineVector.length != 2)
continue;
x = Integer.parseInt(lineVector[0]);
y = Integer.parseInt(lineVector[1]);
} while (!((x > 1 && x < 1000 && y > 1 && y < 1000)));
First of all I removed the initial value of lineVector as it is unnecessary to initialize it in this case (you needed to do it because of it being present in your while condition).
I initialized x and y to -1 (Any number not in our range would work) in order to make sure the do-while condition is fulfilled until proper values are offered for both of the numbers.
Function to check binary values
Create a function to check if string values are binary.
public static boolean isBinary(String s) {
for(int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if(c != '0' && c != '1')
return false;
}
return true;
}
Receive binaries
String[] binaries = new String[x];
System.out.println("Enter binaries with length " + y + " :");
//Get binaries
for(int i = 0; i < x; ++i) {
binaries[i] = scanner.nextLine();
while(!isBinary(binaries[i]) || binaries[i].length() != y) {
System.out.println("Invalid binary value. Re-enter new value:");
binaries[i] = scanner.nextLine();
}
}
Receive binary values and continue asking if invalid.
Filling the 2D array
int[][] field = new int[x][y];
for(int i = 0; i < x; ++i) {
System.out.println();
for(int j = 0; j < y; ++j) {
char c = binaries[i].charAt(j);
if(c == '0')
field[i][j] = 0;
else
field[i][j] = 1;
System.out.print(field[i][j] + " ");
}
}
Integer.parseInt is not necessary here as there are only two possible values (0 and 1)
The question is:
Write a java program to print all prime numbers in the interval [a,b] (a and b, both inclusive).
Conditions are:
Input 1 should be lesser than Input 2. Both the inputs should be positive.
Range must always be greater than zero.
If any of the condition mentioned above fails, then display "Provide valid input"
Use a minimum of one for loop and one while loop.
I came up with a code like this:
import java.util.Scanner;
class PrimeNumbers{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int a = Integer.parseInt(sc.nextLine());
int b = Integer.parseInt(sc.nextLine());
if((a > b) || a <= 0 || b <= 0){
System.out.println("Provide valid input");
}
else{
int i = 0, num = 0;
String prime = "";
for(i = a;i <= b;i++){
int counter = 0;
num = i;
while(num >= 1){
if(i % num == 0)
counter++;
num--;
}
if(counter == 2)
prime = prime + i + " ";
}
System.out.println(prime);
}
}
}
I ran it against test cases. One of the hidden test case just gave a hint "Check for equal range"
I am not sure what that means. Can someone help me out?
package monu;
import java.util.Scanner;
public class Test {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int a = Integer.parseInt(sc.nextLine());
int b = Integer.parseInt(sc.nextLine());
int c = b - a;
if(a > b || c < 0 || a < 0|| b <= 0) {
System.out.println("Provide valid input");
}
else{
int i = 0, num = 0;
String prime = "";
for(i = a; i <= b; i++){
int counter = 0;
num = i;
while (num >= 1) {
if (i % num == 0)
counter++;
num--;
}
if (counter == 2)
prime = prime + i + " ";
}
System.out.println(prime);
}
}
}
I'm very new in Java Programming Language.
I asked to make something like this with nested loops method:
.
"Masukan Angka" is "Input Number" in Indonesian Language. So if we input 9, it will print out 9 lines of * and the amount of * decreased for each line.
I tried it with nested loops, this is what i made :
The code is :
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Input your number: ");
int x = in.nextInt();
for (int y = x; y > 0; y--) {
for (int z = 0; z < y; z++)
System.out.print("*");
System.out.println();
}
}
How can i make it doesn't filled up with * in the line 2-7, but instead filled with blank space like the example in the first picture?
Thanks in advance.
Expanding a bit on #Ringuerel solution:
for (int y = x; y > 0; y--) {
for (int z = 0; z < y; z++) {
// If it's first or last or first row print "*"
if( z == 0 || z == y-1 || y == x) {
System.out.print("*");
}
else {
// Otherwise print " "
System.out.print(" ");
}
}
System.out.println();
}
Add this after the second for, before the print statement, if( z == 0 || z == y-1 ), sorry I'm using my phone
public static void main(String[] args) {
int amount = 10;
String c = "*";
String message = "";
for (int i = 0; i < amount; i++) {
message += "*";
for (int j = 1; j < amount - i; j++) {
message += c;
}
message += "*";
c = " ";
System.out.println(message);
message = "";
}
System.out.println("*");
}
You can try this if you want. Haven't tested it but I'm fairly certain it will work.
I populate an Arraylist<Integer> with palindromic numbers. I then retrieve a user-specified element from the list via its get() method, and print that number. I am trying to use a while loop to allow the user to select multiple elements, until he enters "0", but instead the program exits after the first selection. How can I make it repeat?
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
ArrayList<Integer> str = new ArrayList<Integer>();
for (int i = 1; i <= 1000; i++) {
int a = i;
int b = inverse(a);
if (a == b) {
str.add(a);
}
}
int num = cin.nextInt();
do {
int getnum = str.get(num - 1);
System.out.println(getnum);
}
while(num == 0);
}
public static int inverse(int x) {
int inv = 0;
while (x > 0) {
inv = inv * 10 + x % 10;
x = x / 10;
}
return inv;
}
Your loop test should probably be while it's not equal to zero. Also, you need to get num again.
// int num = cin.nextInt();
int num;
do{
num = cin.nextInt();
System.out.println("num is " + num);
if (num > 0 && num <= str.size()) {
System.out.println(str.get(num - 1));
}
} while(num != 0);
This code gets an integer n and displays all palindrome numbers less than n.
But seems the for loop doesn't work; because when I enter a number except 0, 1 and negatives, nothing happens.
I tried debugging, but couldn't find the problem!
Sample input: 30
Sample output: 1 2 3 4 5 6 7 8 9 11 22
import java.util.Scanner;
public class PalindromeNumbers {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
if (n == 0 || n == 1 || n < 0)
System.out.println("There's no Palindrome Number!");
else {
for (int num = 1; num < n; num++) {
int reversedNum = 0;
int temp = 0;
while (num > 0) {
// use modulus operator to strip off the last digit
temp = num % 10;
// create the reversed number
reversedNum = reversedNum * 10 + temp;
num = num / 10;
}
if (reversedNum == num)
System.out.println(num);
}
}
}
}
You run into an infinite loop: you use num in your for loop as an index, and reset it to 0 inside the loop. Use different variables, and it should work!
for (int i = 1; i < n; i++) {
int num = i;
...
if (reversedNum == i)
System.out.println(i);
}
You can do it in a more concise way:
public static void main(final String args[]) {
final Scanner input = new Scanner(System.in);
final int max = input.nextInt();
if (max <= 0) {
System.out.println("There's no Palindrome Number!");
} else {
for (int i = 1; i < max; i++) {
if (isPalindrome(i)) {
System.out.println(i);
}
}
}
}
private static boolean isPalindrome(final int num) {
final String temp = "" + num;
return new StringBuilder(temp).reverse().toString().equals(temp);
}
You are changing your num variable inside your for loop. The next time num < n is executed, the value changed (to 0). Try something like this:
for (int num = 1; num < n; num++) {
int reversedNum = 0;
int temp = 0;
int temp2 = num;
while (temp2 > 0) {
// use modulus operator to strip off the last digit
temp = temp2 % 10;
// create the reversed number
reversedNum = reversedNum * 10 + temp;
temp2 = temp2 / 10;
}
if (reversedNum == num)
System.out.println(num);
}
This way, you use a temp variable to calculate your reversedNum, and still keeps the value of num for the next loop iteration.