I need to convert this for loop into a while loop so I can avoid using a break.
double[] array = new double[100];
Scanner scan = new Scanner(System.in);
for (int index = 0; index < array.length; index++)
{
System.out.print("Sample " + (index+1) + ": ");
double x = scan.nextDouble();
count++;
if (x < 0)
{
count--;
break;
}
array[index] = x;
}
This is what I came up with but I'm getting a different output:
int index = 0;
double x = 0;
while (index < array.length && x >= 0)
{
System.out.print("Sample " + (index+1) + ": ");
x = scan.nextDouble();
count++;
if (x < 0)
{
count--;
}
array[index] = x;
index++;
}
this solution gives the same output as the for loop:
while (index < array.length && x >= 0)
{
System.out.print("Sample " + (index+1) + ": ");
x = scan.nextDouble();
count++;
if (x < 0)
{
count--;
}
else
{
array[index] = x;
index++;
}
}
EXPLANATION:
On the for loop you use the break statement so nothing happens after the program hits the break. So array[index] = x; didn't get executed.
On the while loop since there's no break, the loop continues, so the statements array[index] = x; and index++; got executed.
That's why you got different results. If you don't want the statements
array[index] = x;
index++;
To be executed you can simply make your if statement a if/else statement as above.
Change
if (x < 0)
{
count--;
}
array[index] = x;
index++;
to something like
if (x < 0)
{
count--;
}
else
{
array[index] = x;
index++;
}
If you want to avoid break, changing the for loop into a while loop doesn't help in any way.
How about this solution:
boolean exitLoop = false;
for (int index = 0; index < array.length && !exitLoop; index++)
{
System.out.print("Sample " + (index+1) + ": ");
double x = scan.nextDouble();
count++;
if (x < 0)
{
count--;
exitLoop = true;
}
else {
array[index] = x;
}
}
Related
I am solving this problem on code forces.
https://codeforces.com/contest/1675/problem/B
The break statement I have doesn't break out of the while loop.
When I use this input:
It outputs -1 one twice in the same case, which shows that the break statement isn't taking me outside the loop?
Why is this happening?
public class vanita {
public static void main (String[]args) {
Scanner in = new Scanner(System.in);
int cases = in.nextInt();
for (int i = 0; i < cases; i++) {
boolean test = true;
int arrLength = in.nextInt();
int arr[] = new int[arrLength];
for (int j = 0; j < arrLength; j++) {
arr[j] = in.nextInt();
}
int operations = 0;
int after;
for (int j = arrLength-1; j >= 1 ; j--){
after = arr[j-1];
while (arr[j] <= after) {
arr[j-1] = (int)Math.floor(arr[j-1]/2);
after = arr[j-1];
operations++;
if (arr[j] == 0 && arr[j-1] == 0) {
//System.out.println("current: " + arr[j]);
//System.out.println("after: " + arr[j-1]);
//System.out.println("Case " + i);
System.out.println("-1");
test = false;
break;
}
}
}
for (int s = 0; s < arrLength; s++) {
//System.out.print(arr[s] + " ");
}
//System.out.println(" ");
if (test == true) {
System.out.println(operations);
}
}
}
}
i think it breaks out of the inner while loop, but not the outer for loop. So the inner while loop runs multiple times.
Problems
Normally a break; will always break out of the most recent loop. If you can't break out of your loop, the problem is your algorithm or your condition.
Solutions
First, always debug to see if you enter your if statement.
Second, use something else as condition of your while loop. You could use a boolean and change its value to break the while condition. Ex:
boolean hasFoundDuplicate = false;
while(!hasFoundDuplicate){
arr[j-1] = (int)Math.floor(arr[j-1]/2);
after = arr[j-1];
operations++;
if(arr[j] == 0 && arr[j-1] == 0){
hasFoundDuplicate = true;
}
}
Im trying to make a multi dimensional array that contains numbers and I need to find the number neighbors (down or right) that slope by num(variable)
example :
{7,5,3},{1,5,9}
the numbers 3,5,7 are sloped by 2 and the counter is 3 ( 3 numbers )
I need to find the longest slope which means that if there slope with 3 numbers and also after that slope with 6 numbers I need to return the 6 numbers..
I tried already for about 5 hours but im completely lost , here is my code until now :
private static int longestSlope (int [][] mat, int num , int i , int j , int count , int temp,int oldi,int oldj)
{
System.out.println("oldi " +oldi);
System.out.println("oldj " +oldj);
System.out.println("temp " +temp);
System.out.println("count "+count);
System.out.println("i "+i);
System.out.println("j "+j);
if(i < mat.length-1 && j < mat[0].length-1 )
{
if(j < mat[0].length-1 && mat[i][j] - num == mat[i][j+1] )
{
if(temp == 0)
{
oldj = j;
oldi = i;
}
if(j == mat[0].length-1)
{
return longestSlope(mat,num,i,j,count,temp+1,oldi,oldj);
}
else
{
temp = longestSlope(mat,num,i,j+1,count,temp+1,oldi,oldj);
}
}
else if(i < mat.length-1 && mat[i][j] - num == mat[i+1][j])
{
if(temp == 0)
{
oldj = j;
oldi = i;
}
temp = longestSlope(mat,num,i+1,j,count,temp+1,oldi,oldj);
}
else
temp = longestSlope(mat,num,i,j+1,count,temp,oldi,oldj);
}
else if(i < mat.length-1 && j == mat[0].length-1 && temp == 0)
{
temp = longestSlope(mat,num,i+1,0,count,0,oldi,oldj);
}
else if(temp > count)
{
count = temp;
System.out.println("nihnas "+count);
return longestSlope(mat,num,oldi,oldj+1,count,0,0,0);
}
else if(temp < count)
{
longestSlope(mat,num,oldi,oldj+1,count,0,0,0);
}
return 0;
}
I'm working on this program where I need to verify if every odd index in a String has the letter "X". For example if my String is: AXFXTX then I should get a message: "GOOD", if not I should get a message: "BAD". Can anyone tell me what I'm missing please. Thank you in advanced.
Here's my code
import java.util.Random;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int min = 1;
int max = 10;
int randomNum = rand.nextInt((max - min) + 1) + min;
System.out.println("Random number = " + randomNum);
System.out.print("Enter a word of " + randomNum + " characters:");
String myString = scan.nextLine();
while(myString.length() != randomNum){
System.out.print("Enter a word of " + randomNum + " characters:");
myString = scan.nextLine();
}
char[] c = myString.toCharArray();
for(int i = 0 ; i < c.length ; i++){
if(c[i] == 'X'){
System.out.println("GOOD!");
}
else{
System.out.println("BAD");
}
}
}
}
If I understand your question, then it's important to note that the first odd index is 1. So you can start at 3 and check if that, and every subsequent odd number (index += 2), is the same as the first. Something like,
boolean sameLetter = true;
for (int index = 3; index < c.length && sameLetter; index += 2) {
sameLetter = (c[1] == c[index]);
}
System.out.println(sameLetter ? "GOOD!" : "BAD");
Simply evaluate odd indices only:
char[] c = myString.toCharArray();
boolean good = true;
for(int i = 3 ; i < c.length ; i+=2){
if(c[i] != c[i-2]){
good = false;
break;
}
}
if(good) System.out.println("GOOD");
else System.out.println("BAD");
I would simply use a regular expression here
str.matches(".(\\w)(.\\1)+") //true is GOOD
Try
booelan allGood = true;
for(int i = 2 ; i < c.length ; i = i + 2){
if(c[i] != c[0]){
allGood = false;
break;
}
}
To start with, you need a boolean variable here to track if it's consistent across all characters. Second, you need to improve your loop
boolean testSucceed = true;
for(int i = 1 ; i < c.length ; i += 2){
if (c[i] != 'X') testSucceed = false;
break;
}
if(testSucceed){
System.out.println("GOOD!");
} else{
System.out.println("BAD");
}
Change the for loop to :
for(int i = 0 ; i < c.length ; i+=2)
so that it goes over alternate characters.
//If NOT divisible by 2- Check only ODD number
Edited: You are suppossed to use modulus % and not division %. My bad
for(int i = 0 ; i < c.length ; i++){
if(c[i]%2 != 0){
if(c[i] == 'X'){
System.out.println("GOOD!");
}
else{
System.out.println("BAD");
}
}
}
Hi I am new in programming,so please don't laugh from my stupid question.
I wrote program which ask user for input a number than program should output all the numbers from 0 to that entered number(doesn't matter if it is positive or negative).
I have tried 3 different versions
Here is my code:
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
int num = PutiL.validNum(min, max, "number");
//this my utility methode which check if number is in range and if it is not a double or letter
int i = 0, z;
int y = 0;
//3rd version
while (i <= num) {
for (z = 0; z < 4; z++) {
System.out.print(i + " ");
i++;
}
System.out.println();
}
//2nd version
if (num > 0) {
for (i = 0; i <= num; y++) {
for (z = 0; z < 4; z++) {
System.out.print(i + ",");
i++;
}
System.out.println();
}
} else {
for (i = 0; i > num; y--) {
for (z = 0; z < 4; z++) {
System.out.print(i + ",");
i--;
}
System.out.println();
}
}
//1st version`enter code here`
if (num > 0) {
for (i = 0; i <= num; i++)
{
System.out.print(i + ",");
}
} else {
for (i = 0; i >= num; i--) {
System.out.print(i + ",");
}
}
System.out.println();
Problem is that code doesn't stop straight after number typed in by user. Will someone give me a hint what is wrong as I don't have any more ideas.
And here is the PutiL methode
public static int validNum(int min, int max, String words) {
int num;
do {
System.out.println("Please enter " + words);
while (!kb.hasNextInt()) {
System.out.println("Please re-enter ");
kb.nextLine();
}
num = kb.nextInt();
if (num < min || num > max) {
System.out.println("Not in range - re-enter\tproper range is "
+ min + " - " + max);
}
} while (num < min || num > max);
return num;
}
//2nd version
if (num > 0)
{
for (i = 0; i <= num; y++) <== THIS MAKE INFINITE too, OKAY.. ^^, change i to stop
{
for (z = 0; z < 4; z++)
{
System.out.print(i + ",");
i++;
}
System.out.println();
}
} else
{
for (i = 0; i > num; y--) <== THIS MAKE INFINITE LOOPS, OKAY.. ^^, it must i to stop
{
for (z = 0; z < 4; z++)
{
System.out.print(i + ",");
i--;
}
System.out.println();
}
}
don't forget to accepted the answer if it goes right.. ^^
public static void main(String[] args) {
int number = Integer.parseInt(args[0]);
if (number >= 0) {
for (int i = 0; i <= number; i++) {
System.out.println(i);
}
} else {
for (int i = 0; i >= number; i--) {
System.out.println(i);
}
}
}
Or a bit more concise and with duplicating the println statement...
public static void main(String[] args) {
int number = Integer.parseInt(args[0]);
int increment = number >= 0 ? 1 : -1;
for (int i = 0; i != number + increment; i += increment) {
System.out.println(i);
}
}
This will give the user a dialog and the value the user enters will count to zero.
First import:
import javax.swing.JOptionPane.*;
Then:
int user_choice = Integer.parseInt(
showInputDialog(null, "Please enter a number."));
if(user_choice > 0){
for(int temp = 0; temp <= user_choice; temp++){
System.out.println(temp);
}
}
else{
for(int temp = 0; temp >= user_choice; temp--){
System.out.println(temp);
}
}
"program should output all the numbers from 0 to that entered number"
and
"I want them print for example 4 in a one line and than skip to another line"
if(num >=0) {
for (z = 0; z <= num; z++)
{
System.out.print(z + " ");
if(z > 0 && z%4==0)
System.out.println();
}
}
else {
// similar loop for negatives
}
System.out.println();
Thank you all for help I solve it my self was really easy here is code I useit and now its work perfectly
for(i = 0; i <= num; i++)
{
System.out.print(i + " ");
y++;
if(y % 4 == 0)
{
System.out.println();
}
}
for(i = 0; i >= num; i--)
{
System.out.print(i + " ");
y++;
if(y % 4 == 0)
{
System.out.println();
}
}
But thank you all again for giving my ideas.
I have this program that takes user input and displays the number of times each integer is entered. I pretty much have it down pat but need another loop to omit the shown occurrence of 0. In other words any number with 0 in it cannot be read, also for some reason i am getting two outputs from the same number in my program. For example, if I enter 3,3 I will get 3 occurs 1 time and 3 occurs 2 times as output. The 2 times one being correct and the first one being incorrect.
public class Six_Three {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("enter integers between 1 and 100: ");
int[] num = new int[100];
int data = input.nextInt();
while ((data = input.nextInt()) != 0) {
num[data]++;
}
for (int i = 1; i < 100; ++i) {
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
}
You need two separate loops: the first to gather the information, and the second to print the results:
int data = 0;
while ((data = input.nextInt()) != 0)
{
num[data]++;
}
for (int i = 0; i < 100; ++i)
{
if (num[i] != 0) { /* print num[i] */ }
}
Just loop over the num array after your while loop to print the counts.
for (int index = 0; index < num.length; index++) {
if (num[index] != 0)
System.out.println(data + " occurs " + num[data] + " time(s).");
}
You are printing an output every time an integer is read. Your program is behaving as expected.
To get what you want, you need to scan all the input before you produce any output.
Try this instead:
while (data != 0){
data = input.nextInt();
num[data]++;
}
for (int i = 1; i < 100; ++i) { // your version is 0...99, else array index out of bounds
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
The way you write it the last number has to be 0 to make the scanning stop. It might be a good idea to check if there's another int available and use that as a condition for the scanning loop. That way your program can accept any integer.
while (input.hasNextInt()){
num[input.nextInt()]++;
}
it's so simple
int data = 0;
int[] num = new int[100];
int i = 0;
while (i < num.length) {
if ((data = input.nextInt()) == 0)
break;
num[i] = data;
i++;
}
for (i = 0; i < 100; ++i) {
int times = 0;
if (num[i] != 0) {
for (int j = 0; j < 100; j++) {
if (num[j] == 0) {
break;
} else if (num[i] == num[j]) {
times++;
}
}
System.out.println(num[i] + " occurs " + times + " times ");
} else {
break;
}
}